C++ Reference

C++ Reference: Linear solver

linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
134 #ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
135 #define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
136 
137 #include <functional>
138 #include <limits>
139 #include <map>
140 #include <memory>
141 #include <string>
142 #include <utility>
143 #include <vector>
144 
145 #include "absl/container/flat_hash_map.h"
146 #include "absl/strings/match.h"
147 #include "absl/strings/str_format.h"
148 #include "absl/types/optional.h"
149 #include "ortools/base/commandlineflags.h"
150 #include "ortools/base/integral_types.h"
151 #include "ortools/base/logging.h"
152 #include "ortools/base/macros.h"
153 #include "ortools/base/status.h"
154 #include "ortools/base/timer.h"
156 #include "ortools/linear_solver/linear_solver.pb.h"
157 #include "ortools/port/proto_utils.h"
158 
159 namespace operations_research {
160 
161 constexpr double kDefaultPrimalTolerance = 1e-07;
162 
163 class MPConstraint;
164 class MPObjective;
165 class MPSolverInterface;
166 class MPSolverParameters;
167 class MPVariable;
168 
173 class MPSolver {
174  public:
182 #ifdef USE_CLP
183  CLP_LINEAR_PROGRAMMING = 0,
185 #endif
186 #ifdef USE_GLPK
187  GLPK_LINEAR_PROGRAMMING = 1,
189 #endif
192 #ifdef USE_GUROBI
193  GUROBI_LINEAR_PROGRAMMING = 6,
195 #endif
196 #ifdef USE_CPLEX
197  CPLEX_LINEAR_PROGRAMMING = 10,
199 #endif
200 
201 // Integer programming problems.
202 #ifdef USE_SCIP
203  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
205 #endif
206 #ifdef USE_GLPK
207  GLPK_MIXED_INTEGER_PROGRAMMING = 4,
209 #endif
210 #ifdef USE_CBC
213 #endif
214 #if defined(USE_GUROBI)
215  GUROBI_MIXED_INTEGER_PROGRAMMING = 7,
217 #endif
218 #if defined(USE_CPLEX)
219  CPLEX_MIXED_INTEGER_PROGRAMMING = 11,
221 #endif
228 #if defined(USE_XPRESS)
229  XPRESS_LINEAR_PROGRAMMING = 101,
230  XPRESS_MIXED_INTEGER_PROGRAMMING = 102,
231 #endif
232  };
233 
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 
254  const std::string& Name() const {
255  return name_; // Set at construction.
256  }
257 
260  return problem_type_; // Set at construction.
261  }
262 
268  void Clear();
269 
271  int NumVariables() const { return variables_.size(); }
272 
277  const std::vector<MPVariable*>& variables() const { return variables_; }
278 
284  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
285 
293  MPVariable* MakeVar(double lb, double ub, bool integer,
294  const std::string& name);
295 
297  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
298 
300  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
301 
303  MPVariable* MakeBoolVar(const std::string& name);
304 
319  void MakeVarArray(int nb, double lb, double ub, bool integer,
320  const std::string& name_prefix,
321  std::vector<MPVariable*>* vars);
322 
324  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
325  std::vector<MPVariable*>* vars);
326 
328  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
329  std::vector<MPVariable*>* vars);
330 
332  void MakeBoolVarArray(int nb, const std::string& name,
333  std::vector<MPVariable*>* vars);
334 
336  int NumConstraints() const { return constraints_.size(); }
337 
343  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
344 
353  const std::string& constraint_name) const;
354 
363  MPConstraint* MakeRowConstraint(double lb, double ub);
364 
367 
369  MPConstraint* MakeRowConstraint(double lb, double ub,
370  const std::string& name);
371 
373  MPConstraint* MakeRowConstraint(const std::string& name);
374 
380 
383  const std::string& name);
384 
391  const MPObjective& Objective() const { return *objective_; }
392 
394  MPObjective* MutableObjective() { return objective_.get(); }
395 
417  };
418 
421 
423  ResultStatus Solve(const MPSolverParameters& param);
424 
429  void Write(const std::string& file_name);
430 
437  std::vector<double> ComputeConstraintActivities() const;
438 
457  bool VerifySolution(double tolerance, bool log_errors) const;
458 
467  void Reset();
468 
476  bool InterruptSolve();
477 
485  MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
486  std::string* error_message);
494  MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(
495  const MPModelProto& input_model, std::string* error_message);
496 
498  void FillSolutionResponseProto(MPSolutionResponse* response) const;
499 
509  static void SolveWithProto(const MPModelRequest& model_request,
510  MPSolutionResponse* response);
511 
513  void ExportModelToProto(MPModelProto* output_model) const;
514 
546  util::Status LoadSolutionFromProto(
547  const MPSolutionResponse& response,
548  double tolerance = kDefaultPrimalTolerance);
549 
554  util::Status ClampSolutionWithinBounds();
555 
562  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
563  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
564  std::string* model_str) const;
565 
576  util::Status SetNumThreads(int num_threads);
577 
579  int GetNumThreads() const { return num_threads_; }
580 
587  bool SetSolverSpecificParametersAsString(const std::string& parameters);
589  return solver_specific_parameter_string_;
590  }
591 
605  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
606 
611  enum BasisStatus {
612  FREE = 0,
617  };
618 
630  void SetStartingLpBasis(
631  const std::vector<MPSolver::BasisStatus>& variable_statuses,
632  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
633 
639  static double infinity() { return std::numeric_limits<double>::infinity(); }
640 
649  bool OutputIsEnabled() const;
650 
652  void EnableOutput();
653 
655  void SuppressOutput();
656 
657  absl::Duration TimeLimit() const { return time_limit_; }
658  void SetTimeLimit(absl::Duration time_limit) {
659  DCHECK_GE(time_limit, absl::ZeroDuration());
660  time_limit_ = time_limit;
661  }
662 
663  absl::Duration DurationSinceConstruction() const {
664  return absl::Now() - construction_time_;
665  }
666 
668  int64 iterations() const;
669 
675  int64 nodes() const;
676 
678  std::string SolverVersion() const;
679 
693  void* underlying_solver();
694 
718  double ComputeExactConditionNumber() const;
719 
734  ABSL_MUST_USE_RESULT bool NextSolution();
735 
736  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
737  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
738  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
739  int64 time_limit() const {
740  return time_limit_ == absl::InfiniteDuration()
741  ? 0
742  : absl::ToInt64Milliseconds(time_limit_);
743  }
744  void set_time_limit(int64 time_limit_milliseconds) {
745  SetTimeLimit(time_limit_milliseconds == 0
746  ? absl::InfiniteDuration()
747  : absl::Milliseconds(time_limit_milliseconds));
748  }
749  double time_limit_in_secs() const {
750  return static_cast<double>(time_limit()) / 1000.0;
751  }
752 
753  // DEPRECATED: Use DurationSinceConstruction() instead.
754  int64 wall_time() const {
755  return absl::ToInt64Milliseconds(DurationSinceConstruction());
756  }
757 
758  friend class GLPKInterface;
759  friend class CLPInterface;
760  friend class CBCInterface;
761  friend class SCIPInterface;
762  friend class GurobiInterface;
763  friend class CplexInterface;
764  friend class XpressInterface;
765  friend class SLMInterface;
766  friend class MPSolverInterface;
767  friend class GLOPInterface;
768  friend class BopInterface;
769  friend class SatInterface;
770  friend class KnapsackInterface;
771 
772  // Debugging: verify that the given MPVariable* belongs to this solver.
773  bool OwnsVariable(const MPVariable* var) const;
774 
775  private:
776  // Computes the size of the constraint with the largest number of
777  // coefficients with index in [min_constraint_index,
778  // max_constraint_index)
779  int ComputeMaxConstraintSize(int min_constraint_index,
780  int max_constraint_index) const;
781 
782  // Returns true if the model has constraints with lower bound > upper bound.
783  bool HasInfeasibleConstraints() const;
784 
785  // Returns true if the model has at least 1 integer variable.
786  bool HasIntegerVariables() const;
787 
788  // Generates the map from variable names to their indices.
789  void GenerateVariableNameIndex() const;
790 
791  // Generates the map from constraint names to their indices.
792  void GenerateConstraintNameIndex() const;
793 
794  // The name of the linear programming problem.
795  const std::string name_;
796 
797  // The type of the linear programming problem.
798  const OptimizationProblemType problem_type_;
799 
800  // The solver interface.
801  std::unique_ptr<MPSolverInterface> interface_;
802 
803  // The vector of variables in the problem.
804  std::vector<MPVariable*> variables_;
805  // A map from a variable's name to its index in variables_.
806  mutable absl::optional<absl::flat_hash_map<std::string, int> >
807  variable_name_to_index_;
808  // Whether variables have been extracted to the underlying interface.
809  std::vector<bool> variable_is_extracted_;
810 
811  // The vector of constraints in the problem.
812  std::vector<MPConstraint*> constraints_;
813  // A map from a constraint's name to its index in constraints_.
814  mutable absl::optional<absl::flat_hash_map<std::string, int> >
815  constraint_name_to_index_;
816  // Whether constraints have been extracted to the underlying interface.
817  std::vector<bool> constraint_is_extracted_;
818 
819  // The linear objective function.
820  std::unique_ptr<MPObjective> objective_;
821 
822  // Initial values for all or some of the problem variables that can be
823  // exploited as a starting hint by a solver.
824  //
825  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
826  //
827  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
828  // hint is provided and a std::vector<double> for the hint value.
829  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
830 
831  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
832 
833  const absl::Time construction_time_;
834 
835  // Permanent storage for the number of threads.
836  int num_threads_ = 1;
837 
838  // Permanent storage for SetSolverSpecificParametersAsString().
839  std::string solver_specific_parameter_string_;
840 
841  MPSolverResponseStatus LoadModelFromProtoInternal(
842  const MPModelProto& input_model, bool clear_names,
843  bool check_model_validity, std::string* error_message);
844 
845  DISALLOW_COPY_AND_ASSIGN(MPSolver);
846 };
847 
848 const absl::string_view ToString(
849  MPSolver::OptimizationProblemType optimization_problem_type);
850 
851 inline std::ostream& operator<<(
852  std::ostream& os,
853  MPSolver::OptimizationProblemType optimization_problem_type) {
854  return os << ToString(optimization_problem_type);
855 }
856 
857 inline std::ostream& operator<<(std::ostream& os,
858  MPSolver::ResultStatus status) {
859  return os << ProtoEnumToString<MPSolverResponseStatus>(
860  static_cast<MPSolverResponseStatus>(status));
861 }
862 
863 bool AbslParseFlag(absl::string_view text,
865  std::string* error);
866 
867 inline std::string AbslUnparseFlag(
868  MPSolver::OptimizationProblemType solver_type) {
869  return std::string(ToString(solver_type));
870 }
871 
873 class MPObjective {
874  public:
879  void Clear();
880 
887  void SetCoefficient(const MPVariable* const var, double coeff);
888 
894  double GetCoefficient(const MPVariable* const var) const;
895 
901  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
902  return coefficients_;
903  }
904 
906  void SetOffset(double value);
907 
909  double offset() const { return offset_; }
910 
915  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
916 
918  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
919  OptimizeLinearExpr(linear_expr, true);
920  }
922  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
923  OptimizeLinearExpr(linear_expr, false);
924  }
925 
927  void AddLinearExpr(const LinearExpr& linear_expr);
928 
930  void SetOptimizationDirection(bool maximize);
931 
934 
937 
939  bool maximization() const;
940 
942  bool minimization() const;
943 
955  double Value() const;
956 
963  double BestBound() const;
964 
965  private:
966  friend class MPSolver;
967  friend class MPSolverInterface;
968  friend class CBCInterface;
969  friend class CLPInterface;
970  friend class GLPKInterface;
971  friend class SCIPInterface;
972  friend class SLMInterface;
973  friend class GurobiInterface;
974  friend class CplexInterface;
975  friend class XpressInterface;
976  friend class GLOPInterface;
977  friend class BopInterface;
978  friend class SatInterface;
979  friend class KnapsackInterface;
980 
981  // Constructor. An objective points to a single MPSolverInterface
982  // that is specified in the constructor. An objective cannot belong
983  // to several models.
984  // At construction, an MPObjective has no terms (which is equivalent
985  // on having a coefficient of 0 for all variables), and an offset of 0.
986  explicit MPObjective(MPSolverInterface* const interface_in)
987  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
988 
989  MPSolverInterface* const interface_;
990 
991  // Mapping var -> coefficient.
992  absl::flat_hash_map<const MPVariable*, double> coefficients_;
993  // Constant term.
994  double offset_;
995 
996  DISALLOW_COPY_AND_ASSIGN(MPObjective);
997 };
998 
1000 class MPVariable {
1001  public:
1003  const std::string& name() const { return name_; }
1004 
1006  void SetInteger(bool integer);
1007 
1009  bool integer() const { return integer_; }
1010 
1018  double solution_value() const;
1019 
1021  int index() const { return index_; }
1022 
1024  double lb() const { return lb_; }
1025 
1027  double ub() const { return ub_; }
1028 
1030  void SetLB(double lb) { SetBounds(lb, ub_); }
1031 
1033  void SetUB(double ub) { SetBounds(lb_, ub); }
1034 
1036  void SetBounds(double lb, double ub);
1037 
1044  double unrounded_solution_value() const;
1045 
1050  double reduced_cost() const;
1051 
1059 
1070  int branching_priority() const { return branching_priority_; }
1071  void SetBranchingPriority(int priority);
1072 
1073  protected:
1074  friend class MPSolver;
1075  friend class MPSolverInterface;
1076  friend class CBCInterface;
1077  friend class CLPInterface;
1078  friend class GLPKInterface;
1079  friend class SCIPInterface;
1080  friend class SLMInterface;
1081  friend class GurobiInterface;
1082  friend class CplexInterface;
1083  friend class XpressInterface;
1084  friend class GLOPInterface;
1086  friend class BopInterface;
1087  friend class SatInterface;
1088  friend class KnapsackInterface;
1089 
1090  // Constructor. A variable points to a single MPSolverInterface that
1091  // is specified in the constructor. A variable cannot belong to
1092  // several models.
1093  MPVariable(int index, double lb, double ub, bool integer,
1094  const std::string& name, MPSolverInterface* const interface_in)
1095  : index_(index),
1096  lb_(lb),
1097  ub_(ub),
1098  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1099  solution_value_(0.0),
1100  reduced_cost_(0.0),
1101  interface_(interface_in),
1102  integer_(integer){}
1103 
1104  void set_solution_value(double value) { solution_value_ = value; }
1105  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1106 
1107  private:
1108  const int index_;
1109  int branching_priority_ = 0;
1110  double lb_;
1111  double ub_;
1112  const std::string name_;
1113  double solution_value_;
1114  double reduced_cost_;
1115  MPSolverInterface* const interface_;
1116  bool integer_;
1117  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1118 };
1119 
1126  public:
1128  const std::string& name() const { return name_; }
1129 
1131  void Clear();
1132 
1139  void SetCoefficient(const MPVariable* const var, double coeff);
1140 
1145  double GetCoefficient(const MPVariable* const var) const;
1146 
1152  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1153  return coefficients_;
1154  }
1155 
1157  double lb() const { return lb_; }
1158 
1160  double ub() const { return ub_; }
1161 
1163  void SetLB(double lb) { SetBounds(lb, ub_); }
1164 
1166  void SetUB(double ub) { SetBounds(lb_, ub); }
1167 
1169  void SetBounds(double lb, double ub);
1170 
1172  bool is_lazy() const { return is_lazy_; }
1173 
1187  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1188 
1189  const MPVariable* indicator_variable() const { return indicator_variable_; }
1190  bool indicator_value() const { return indicator_value_; }
1191 
1193  int index() const { return index_; }
1194 
1199  double dual_value() const;
1200 
1214 
1215  protected:
1216  friend class MPSolver;
1217  friend class MPSolverInterface;
1218  friend class CBCInterface;
1219  friend class CLPInterface;
1220  friend class GLPKInterface;
1221  friend class SCIPInterface;
1222  friend class SLMInterface;
1223  friend class GurobiInterface;
1224  friend class CplexInterface;
1225  friend class XpressInterface;
1226  friend class GLOPInterface;
1227  friend class BopInterface;
1228  friend class SatInterface;
1229  friend class KnapsackInterface;
1230 
1231  // Constructor. A constraint points to a single MPSolverInterface
1232  // that is specified in the constructor. A constraint cannot belong
1233  // to several models.
1234  MPConstraint(int index, double lb, double ub, const std::string& name,
1235  MPSolverInterface* const interface_in)
1236  : coefficients_(1),
1237  index_(index),
1238  lb_(lb),
1239  ub_(ub),
1240  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1241  indicator_variable_(nullptr),
1242  is_lazy_(false),
1243  dual_value_(0.0),
1244  interface_(interface_in) {}
1245 
1246  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1247 
1248  private:
1249  // Returns true if the constraint contains variables that have not
1250  // been extracted yet.
1251  bool ContainsNewVariables();
1252 
1253  // Mapping var -> coefficient.
1254  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1255 
1256  const int index_; // See index().
1257 
1258  // The lower bound for the linear constraint.
1259  double lb_;
1260 
1261  // The upper bound for the linear constraint.
1262  double ub_;
1263 
1264  // Name.
1265  const std::string name_;
1266 
1267  // If given, this constraint is only active if `indicator_variable_`'s value
1268  // is equal to `indicator_value_`.
1269  const MPVariable* indicator_variable_;
1270  bool indicator_value_;
1271 
1272  // True if the constraint is "lazy", i.e. the constraint is added to the
1273  // underlying Linear Programming solver only if it is violated.
1274  // By default this parameter is 'false'.
1275  bool is_lazy_;
1276 
1277  double dual_value_;
1278  MPSolverInterface* const interface_;
1279  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1280 };
1281 
1309  public:
1314 
1324  };
1325 
1329  PRESOLVE = 1000,
1335  SCALING = 1003
1336  };
1337 
1344  };
1345 
1349  DUAL = 10,
1351  PRIMAL = 11,
1353  BARRIER = 12
1354  };
1355 
1360 
1366  };
1367 
1374  };
1375 
1376  // Placeholder value to indicate that a parameter is set to
1377  // the default value defined in the wrapper.
1378  static const double kDefaultDoubleParamValue;
1379  static const int kDefaultIntegerParamValue;
1380 
1381  // Placeholder value to indicate that a parameter is unknown.
1382  static const double kUnknownDoubleParamValue;
1383  static const int kUnknownIntegerParamValue;
1384 
1385  // Default values for parameters. Only parameters that define the
1386  // properties of the solution returned need to have a default value
1387  // (that is the same for all solvers). You can also define a default
1388  // value for performance parameters when you are confident it is a
1389  // good choice (example: always turn presolve on).
1390  static const double kDefaultRelativeMipGap;
1391  static const double kDefaultPrimalTolerance;
1392  static const double kDefaultDualTolerance;
1395 
1398 
1400  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1401 
1403  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1404 
1411 
1418 
1420  void Reset();
1421 
1423  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1424 
1427 
1428  private:
1429  // Parameter value for each parameter.
1430  // @see DoubleParam
1431  // @see IntegerParam
1432  double relative_mip_gap_value_;
1433  double primal_tolerance_value_;
1434  double dual_tolerance_value_;
1435  int presolve_value_;
1436  int scaling_value_;
1437  int lp_algorithm_value_;
1438  int incrementality_value_;
1439 
1440  // Boolean value indicating whether each parameter is set to the
1441  // solver's default value. Only parameters for which the wrapper
1442  // does not define a default value need such an indicator.
1443  bool lp_algorithm_is_default_;
1444 
1445  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1446 };
1447 
1448 // This class wraps the actual mathematical programming solvers. Each
1449 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1450 // derives from this abstract class. This class is never directly
1451 // accessed by the user.
1452 // @see glop_interface.cc
1453 // @see cbc_interface.cc
1454 // @see clp_interface.cc
1455 // @see glpk_interface.cc
1456 // @see scip_interface.cc
1458  public:
1460  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1461  // sync for the model nor for the solution.
1463  // The underlying solver and MPSolver are in sync for the model
1464  // but not for the solution: the model has changed since the
1465  // solution was computed last.
1467  // The underlying solver and MPSolver are in sync for the model and
1468  // the solution.
1470  };
1471 
1472  // When the underlying solver does not provide the number of simplex
1473  // iterations.
1474  static const int64 kUnknownNumberOfIterations = -1;
1475  // When the underlying solver does not provide the number of
1476  // branch-and-bound nodes.
1477  static const int64 kUnknownNumberOfNodes = -1;
1478 
1479  // Constructor. The user will access the MPSolverInterface through the
1480  // MPSolver passed as argument.
1481  explicit MPSolverInterface(MPSolver* const solver);
1482  virtual ~MPSolverInterface();
1483 
1484  // ----- Solve -----
1485  // Solves problem with specified parameter values. Returns true if the
1486  // solution is optimal.
1487  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1488 
1489  // Directly solves a MPModelRequest, bypassing the MPSolver data structures
1490  // entirely. Returns {} (eg. absl::nullopt) if the feature is not supported by
1491  // the underlying solver.
1492  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1493  const MPModelRequest& request) {
1494  return absl::nullopt;
1495  }
1496 
1497  // Writes the model using the solver internal write function. Currently only
1498  // available for GurobiInterface.
1499  virtual void Write(const std::string& filename);
1500 
1501  // ----- Model modifications and extraction -----
1502  // Resets extracted model.
1503  virtual void Reset() = 0;
1504 
1505  // Sets the optimization direction (min/max).
1506  virtual void SetOptimizationDirection(bool maximize) = 0;
1507 
1508  // Modifies bounds of an extracted variable.
1509  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1510 
1511  // Modifies integrality of an extracted variable.
1512  virtual void SetVariableInteger(int index, bool integer) = 0;
1513 
1514  // Modify bounds of an extracted variable.
1515  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1516 
1517  // Adds a linear constraint.
1518  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1519 
1520  // Adds an indicator constraint. Returns true if the feature is supported by
1521  // the underlying solver.
1522  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1523  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1524  return false;
1525  }
1526 
1527  // Add a variable.
1528  virtual void AddVariable(MPVariable* const var) = 0;
1529 
1530  // Changes a coefficient in a constraint.
1531  virtual void SetCoefficient(MPConstraint* const constraint,
1532  const MPVariable* const variable,
1533  double new_value, double old_value) = 0;
1534 
1535  // Clears a constraint from all its terms.
1536  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1537 
1538  // Changes a coefficient in the linear objective.
1539  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1540  double coefficient) = 0;
1541 
1542  // Changes the constant term in the linear objective.
1543  virtual void SetObjectiveOffset(double value) = 0;
1544 
1545  // Clears the objective from all its terms.
1546  virtual void ClearObjective() = 0;
1547 
1548  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1549  // ------ Query statistics on the solution and the solve ------
1550  // Returns the number of simplex iterations. The problem must be discrete,
1551  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1552  virtual int64 iterations() const = 0;
1553  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1554  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1555  virtual int64 nodes() const = 0;
1556  // Returns the best objective bound. The problem must be discrete, otherwise
1557  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1558  virtual double best_objective_bound() const = 0;
1559  // A trivial objective bound: the worst possible value of the objective,
1560  // which will be +infinity if minimizing and -infinity if maximing.
1561  double trivial_worst_objective_bound() const;
1562  // Returns the objective value of the best solution found so far.
1563  double objective_value() const;
1564 
1565  // Returns the basis status of a row.
1566  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1567  // Returns the basis status of a constraint.
1568  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1569 
1570  // Checks whether the solution is synchronized with the model, i.e. whether
1571  // the model has changed since the solution was computed last.
1572  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1573  bool CheckSolutionIsSynchronized() const;
1574  // Checks whether a feasible solution exists. The behavior is similar to
1575  // CheckSolutionIsSynchronized() above.
1576  virtual bool CheckSolutionExists() const;
1577  // Handy shortcut to do both checks above (it is often used).
1580  }
1581  // Checks whether information on the best objective bound exists. The behavior
1582  // is similar to CheckSolutionIsSynchronized() above.
1583  virtual bool CheckBestObjectiveBoundExists() const;
1584 
1585  // ----- Misc -----
1586  // Queries problem type. For simplicity, the distinction between
1587  // continuous and discrete is based on the declaration of the user
1588  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1589  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1590  // the model.
1591  // Returns true if the problem is continuous.
1592  virtual bool IsContinuous() const = 0;
1593  // Returns true if the problem is continuous and linear.
1594  virtual bool IsLP() const = 0;
1595  // Returns true if the problem is discrete and linear.
1596  virtual bool IsMIP() const = 0;
1597 
1598  // Returns the index of the last variable extracted.
1600 
1601  bool variable_is_extracted(int var_index) const {
1602  return solver_->variable_is_extracted_[var_index];
1603  }
1604  void set_variable_as_extracted(int var_index, bool extracted) {
1605  solver_->variable_is_extracted_[var_index] = extracted;
1606  }
1607  bool constraint_is_extracted(int ct_index) const {
1608  return solver_->constraint_is_extracted_[ct_index];
1609  }
1610  void set_constraint_as_extracted(int ct_index, bool extracted) {
1611  solver_->constraint_is_extracted_[ct_index] = extracted;
1612  }
1613 
1614  // Returns the boolean indicating the verbosity of the solver output.
1615  bool quiet() const { return quiet_; }
1616  // Sets the boolean indicating the verbosity of the solver output.
1617  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1618 
1619  // Returns the result status of the last solve.
1622  return result_status_;
1623  }
1624 
1625  // Returns a std::string describing the underlying solver and its version.
1626  virtual std::string SolverVersion() const = 0;
1627 
1628  // Returns the underlying solver.
1629  virtual void* underlying_solver() = 0;
1630 
1631  // Computes exact condition number. Only available for continuous
1632  // problems and only implemented in GLPK.
1633  virtual double ComputeExactConditionNumber() const;
1634 
1635  // See MPSolver::SetStartingLpBasis().
1636  virtual void SetStartingLpBasis(
1637  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1638  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1639  LOG(FATAL) << "Not supported by this solver.";
1640  }
1641 
1642  virtual bool InterruptSolve() { return false; }
1643 
1644  // See MPSolver::NextSolution() for contract.
1645  virtual bool NextSolution() { return false; }
1646 
1647  friend class MPSolver;
1648 
1649  // To access the maximize_ bool and the MPSolver.
1650  friend class MPConstraint;
1651  friend class MPObjective;
1652 
1653  protected:
1655  // Indicates whether the model and the solution are synchronized.
1657  // Indicates whether the solve has reached optimality,
1658  // infeasibility, a limit, etc.
1660  // Optimization direction.
1662 
1663  // Index in MPSolver::variables_ of last constraint extracted.
1665  // Index in MPSolver::constraints_ of last variable extracted.
1667 
1668  // The value of the objective function.
1670 
1671  // Boolean indicator for the verbosity of the solver output.
1672  bool quiet_;
1673 
1674  // Index of dummy variable created for empty constraints or the
1675  // objective offset.
1676  static const int kDummyVariableIndex;
1677 
1678  // Extracts model stored in MPSolver.
1679  void ExtractModel();
1680  // Extracts the variables that have not been extracted yet.
1681  virtual void ExtractNewVariables() = 0;
1682  // Extracts the constraints that have not been extracted yet.
1683  virtual void ExtractNewConstraints() = 0;
1684  // Extracts the objective.
1685  virtual void ExtractObjective() = 0;
1686  // Resets the extraction information.
1688  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1689  // MODEL_SYNCHRONIZED. To be used for model changes.
1691 
1692  // Sets parameters common to LP and MIP in the underlying solver.
1693  void SetCommonParameters(const MPSolverParameters& param);
1694  // Sets MIP specific parameters in the underlying solver.
1695  void SetMIPParameters(const MPSolverParameters& param);
1696  // Sets all parameters in the underlying solver.
1697  virtual void SetParameters(const MPSolverParameters& param) = 0;
1698  // Sets an unsupported double parameter.
1700  // Sets an unsupported integer parameter.
1701  virtual void SetUnsupportedIntegerParam(
1703  // Sets a supported double parameter to an unsupported value.
1705  double value);
1706  // Sets a supported integer parameter to an unsupported value.
1707  virtual void SetIntegerParamToUnsupportedValue(
1708  MPSolverParameters::IntegerParam param, int value);
1709  // Sets each parameter in the underlying solver.
1710  virtual void SetRelativeMipGap(double value) = 0;
1711  virtual void SetPrimalTolerance(double value) = 0;
1712  virtual void SetDualTolerance(double value) = 0;
1713  virtual void SetPresolveMode(int value) = 0;
1714 
1715  // Sets the number of threads to be used by the solver.
1716  virtual util::Status SetNumThreads(int num_threads);
1717 
1718  // Pass solver specific parameters in text format. The format is
1719  // solver-specific and is the same as the corresponding solver configuration
1720  // file format. Returns true if the operation was successful.
1721  //
1722  // The default implementation of this method stores the parameters in a
1723  // temporary file and calls ReadParameterFile to import the parameter file
1724  // into the solver. Solvers that support passing the parameters directly can
1725  // override this method to skip the temporary file logic.
1727  const std::string& parameters);
1728 
1729  // Reads a solver-specific file of parameters and set them.
1730  // Returns true if there was no errors.
1731  virtual bool ReadParameterFile(const std::string& filename);
1732 
1733  // Returns a file extension like ".tmp", this is needed because some solvers
1734  // require a given extension for the ReadParameterFile() filename and we need
1735  // to know it to generate a temporary parameter file.
1736  virtual std::string ValidFileExtensionForParameterFile() const;
1737 
1738  // Sets the scaling mode.
1739  virtual void SetScalingMode(int value) = 0;
1740  virtual void SetLpAlgorithm(int value) = 0;
1741 };
1742 
1743 } // namespace operations_research
1744 
1745 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
int NumConstraints() const
Returns the number of constraints.
bool variable_is_extracted(int var_index) const
void SetMaximization()
Sets the optimization direction to maximize.
Linear Programming solver using GLOP (Recommended solver).
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
Algorithm to solve linear programs.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
void * underlying_solver()
Advanced usage: returns the underlying solver.
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
virtual bool IsContinuous() const =0
void Reset()
Advanced usage: resets extracted model to solve from scratch.
virtual bool NextSolution()
friend class XpressInterface
The class for variables of a Mathematical Programming (MP) model.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
friend class KnapsackInterface
MPSolverInterface(MPSolver *const solver)
Presolve is off.
bool indicator_value() const
MPSolver::ResultStatus result_status_
friend class KnapsackInterface
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
friend class CLPInterface
Advanced usage: tolerance for dual feasibility of basic solutions.
int index() const
Returns the index of the variable in the MPSolver::variables_.
static const PresolveValues kDefaultPresolve
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
virtual void SetVariableBounds(int index, double lb, double ub)=0
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
static bool ParseSolverType(absl::string_view solver, OptimizationProblemType *type)
Parses the name of the solver.
friend class BopInterface
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
friend class SatInterface
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
void SuppressOutput()
Suppresses solver logging.
friend class CplexInterface
The class for constraints of a Mathematical Programming (MP) model.
virtual bool CheckSolutionExists() const
friend class XpressInterface
friend class CBCInterface
feasible, or stopped by limit.
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
virtual void ExtractNewVariables()=0
friend class CBCInterface
virtual void SetOptimizationDirection(bool maximize)=0
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
double objective_value_
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
Scaling is off.
virtual bool IsMIP() const =0
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
bool minimization() const
Is the optimization direction set to minimize?
int64 time_limit() const
static const double kDefaultRelativeMipGap
double offset() const
Gets the constant term in the objective.
virtual void ClearConstraint(MPConstraint *const constraint)=0
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
void SetLB(double lb)
Sets the lower bound.
friend class KnapsackInterface
virtual util::Status SetNumThreads(int num_threads)
Dual simplex.
void set_variable_as_extracted(int var_index, bool extracted)
static const double kDefaultDualTolerance
util::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
void set_time_limit(int64 time_limit_milliseconds)
friend class XpressInterface
Definition: linear_expr.h:84
virtual bool InterruptSolve()
Advanced usage: enable or disable matrix scaling.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
static double infinity()
Infinity.
friend class GurobiInterface
virtual void * underlying_solver()=0
PresolveValues
For each categorical parameter, enumeration of possible values.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
static const int kDummyVariableIndex
void SetUB(double ub)
Sets the upper bound.
friend class GLOPInterface
LpAlgorithmValues
LP algorithm to use.
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
friend class SatInterface
const std::string & name() const
Returns the name of the variable.
static const IncrementalityValues kDefaultIncrementality
static const double kUnknownDoubleParamValue
Limit for relative MIP gap.
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 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)
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".
SynchronizationStatus
friend class GurobiInterface
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
static const double kDefaultPrimalTolerance
void SetTimeLimit(absl::Duration time_limit)
virtual int64 nodes() const =0
friend class MPVariableSolutionValueTest
std::string GetSolverSpecificParametersAsString() const
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
Advanced usage: incrementality from one solve to the next.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
const std::string & name() const
Returns the name of the constraint.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
void SetOffset(double value)
Sets the constant term in the objective.
friend class GLOPInterface
static const int64 kUnknownNumberOfIterations
friend class BopInterface
friend class GLOPInterface
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
void SetCommonParameters(const MPSolverParameters &param)
ScalingValues
Advanced usage: Scaling options.
virtual void BranchingPriorityChangedForVariable(int var_index)
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
void Reset()
Sets all parameters to their default value.
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
void set_dual_value(double dual_value)
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
void ExtractModel()
IncrementalityValues
Advanced usage: Incrementality options.
void set_solution_value(double value)
virtual void SetPresolveMode(int value)=0
bool CheckSolutionIsSynchronizedAndExists() const
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable on the constraint (which is 0 if the variable does not appea...
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
int64 nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
virtual void AddRowConstraint(MPConstraint *const ct)=0
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
friend class SatInterface
Primal simplex.
virtual std::string SolverVersion() const =0
MPSolverParameters()
The constructor sets all parameters to their default value.
static const int kDefaultIntegerParamValue
bool AbslParseFlag(absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
SAT based solver (requires only integer and Boolean variables).
bool OwnsVariable(const MPVariable *var) const
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
abnormal, i.e., error of some kind.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
friend class CLPInterface
void ResetExtractionInformation()
double objective_value() const
int64 wall_time() const
bool quiet_
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
Start solve from scratch.
friend class SLMInterface
bool maximize_
static const int kUnknownIntegerParamValue
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
virtual void SetObjectiveOffset(double value)=0
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
virtual int64 iterations() const =0
virtual ~MPSolverInterface()
double lb() const
Returns the lower bound.
friend class CplexInterface
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
friend class SLMInterface
Mixed integer Programming Solver using SCIP.
virtual bool CheckBestObjectiveBoundExists() const
virtual void AddVariable(MPVariable *const var)=0
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
bool integer() const
Returns the integrality requirement of the variable.
virtual void SetParameters(const MPSolverParameters &param)=0
virtual double best_objective_bound() const =0
absl::Duration TimeLimit() const
virtual double ComputeExactConditionNumber() const
IntegerParam
Enumeration of parameters that take integer or categorical values.
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
Scaling is on.
std::ostream & operator<<(std::ostream &stream, const LinearExpr &linear_expr)
virtual void SetRelativeMipGap(double value)=0
friend class SCIPInterface
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
Mixed integer Programming Solver using Coin CBC.
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
friend class GurobiInterface
void SetMIPParameters(const MPSolverParameters &param)
virtual bool ReadParameterFile(const std::string &filename)
friend class GLPKInterface
MPObjective * MutableObjective()
Returns the mutable objective object.
virtual void SetScalingMode(int value)=0
Advanced usage: presolve mode.
void EnableOutput()
Enables solver logging.
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
const MPObjective & Objective() const
Returns the objective object.
optimal.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
friend class CBCInterface
friend class SCIPInterface
ResultStatus
The status of solving the problem.
friend class XpressInterface
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
double ub() const
Returns the upper bound.
virtual void ExtractObjective()=0
const std::string & Name() const
Returns the name of the model set at construction.
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
the model is trivially invalid (NaN coefficients, etc).
util::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=kDefaultPrimalTolerance)
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
void SetUB(double ub)
Sets the upper bound.
virtual std::string ValidFileExtensionForParameterFile() const
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
virtual void SetDualTolerance(double value)=0
friend class CLPInterface
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
virtual void SetConstraintBounds(int index, double lb, double ub)=0
bool maximization() const
Is the optimization direction set to maximize?
friend class SatInterface
static const int64 kUnknownNumberOfNodes
friend class SLMInterface
int GetNumThreads() const
Returns the number of threads to be used during solve.
friend class GLPKInterface
Barrier algorithm.
double Value() const
Returns the objective value of the best solution found so far.
virtual void SetLpAlgorithm(int value)=0
friend class GurobiInterface
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
void OptimizeLinearExpr(const LinearExpr &linear_expr, bool is_maximization)
Resets the current objective to take the value of linear_expr, and sets the objective direction to ma...
Linear Boolean Programming Solver.
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
virtual void SetPrimalTolerance(double value)=0
A class to express a linear objective.
util::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
int NumVariables() const
Returns the number of variables.
Advanced usage: tolerance for primal feasibility of basic solutions.
absl::Duration DurationSinceConstruction() const
friend class CplexInterface
double time_limit_in_secs() const
friend class SCIPInterface
std::string SolverVersion() const
Returns a std::string describing the underlying solver and its version.
MPSolver *const solver_
friend class GLPKInterface
friend class BopInterface
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
static const double kDefaultDoubleParamValue
friend class SLMInterface
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
friend class CLPInterface
const MPVariable * indicator_variable() const
void set_quiet(bool quiet_value)
friend class SCIPInterface
bool constraint_is_extracted(int ct_index) const
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
Reuse results from previous solve as much as the underlying solver allows.
constexpr double kDefaultPrimalTolerance
virtual void ClearObjective()=0
DoubleParam
Enumeration of parameters that take continuous values.
double solution_value() const
Returns the value of the variable in the current solution.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
virtual absl::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request)
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
void SetBranchingPriority(int priority)
void SetLB(double lb)
Sets the lower bound.
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
void set_reduced_cost(double reduced_cost)
friend class CBCInterface
MPSolver::ResultStatus result_status() const
int last_constraint_index_
Presolve is on.
friend class KnapsackInterface
double BestBound() const
Returns the best objective bound.
double trivial_worst_objective_bound() const
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
double lb() const
Returns the lower bound.
bool quiet() const
friend class GLOPInterface
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
virtual ~MPSolver()
friend class BopInterface
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
proven infeasible.
int last_variable_index() const
friend class CplexInterface
int64 iterations() const
Returns the number of simplex iterations.
virtual void Write(const std::string &filename)
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
SynchronizationStatus sync_status_
void InvalidateSolutionSynchronization()
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
virtual void SetVariableInteger(int index, bool integer)=0
proven unbounded.
not been solved yet.
friend class GLPKInterface