C++ Reference

C++ Reference: Linear solver

linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2021 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 <atomic>
138 #include <cstdint>
139 #include <functional>
140 #include <limits>
141 #include <map>
142 #include <memory>
143 #include <string>
144 #include <utility>
145 #include <vector>
146 
147 #include "absl/container/flat_hash_map.h"
148 #include "absl/flags/parse.h"
149 #include "absl/flags/usage.h"
150 #include "absl/status/status.h"
151 #include "absl/strings/match.h"
152 #include "absl/strings/str_format.h"
153 #include "absl/types/optional.h"
154 #include "ortools/base/integral_types.h"
155 #include "ortools/base/logging.h"
156 #include "ortools/base/macros.h"
157 #include "ortools/base/timer.h"
160 #include "ortools/linear_solver/linear_solver_callback.h"
161 #include "ortools/port/proto_utils.h"
162 
163 ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
164 
165 namespace operations_research {
166 
167 constexpr double kDefaultPrimalTolerance = 1e-07;
168 
169 class MPConstraint;
170 class MPObjective;
171 class MPSolverInterface;
172 class MPSolverParameters;
173 class MPVariable;
174 
175 // There is a homonymous version taking a MPSolver::OptimizationProblemType.
177 
182 class MPSolver {
183  public:
191  // Linear programming problems.
192  // ----------------------------
195  GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
196 
197  // Integer programming problems.
198  // -----------------------------
199  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
202 
203  // Commercial software (need license).
210 
211  // Boolean optimization problem (requires only integer variables and works
212  // best with only Boolean variables).
214 
215  // SAT based solver (requires only integer and Boolean variables).
216  // If you pass it mixed integer problems, it will scale coefficients to
217  // integer values, and solver continuous variables as integral variables.
219 
220  // Dedicated knapsack solvers.
222  };
223 
225  MPSolver(const std::string& name, OptimizationProblemType problem_type);
226  virtual ~MPSolver();
227 
256  static MPSolver* CreateSolver(const std::string& solver_id);
257 
262  static bool SupportsProblemType(OptimizationProblemType problem_type);
263 
269  static bool ParseSolverType(absl::string_view solver_id,
271 
277  const std::string& solver_id);
278 
279  bool IsMIP() const;
280 
282  const std::string& Name() const {
283  return name_; // Set at construction.
284  }
285 
288  return problem_type_; // Set at construction.
289  }
290 
296  void Clear();
297 
299  int NumVariables() const { return variables_.size(); }
300 
305  const std::vector<MPVariable*>& variables() const { return variables_; }
306 
310  MPVariable* variable(int index) const { return variables_[index]; }
311 
317  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
318 
326  MPVariable* MakeVar(double lb, double ub, bool integer,
327  const std::string& name);
328 
330  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
331 
333  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
334 
336  MPVariable* MakeBoolVar(const std::string& name);
337 
352  void MakeVarArray(int nb, double lb, double ub, bool integer,
353  const std::string& name_prefix,
354  std::vector<MPVariable*>* vars);
355 
357  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
358  std::vector<MPVariable*>* vars);
359 
361  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
362  std::vector<MPVariable*>* vars);
363 
365  void MakeBoolVarArray(int nb, const std::string& name,
366  std::vector<MPVariable*>* vars);
367 
369  int NumConstraints() const { return constraints_.size(); }
370 
376  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
377 
379  MPConstraint* constraint(int index) const { return constraints_[index]; }
380 
389  const std::string& constraint_name) const;
390 
399  MPConstraint* MakeRowConstraint(double lb, double ub);
400 
403 
405  MPConstraint* MakeRowConstraint(double lb, double ub,
406  const std::string& name);
407 
409  MPConstraint* MakeRowConstraint(const std::string& name);
410 
416 
419  const std::string& name);
420 
427  const MPObjective& Objective() const { return *objective_; }
428 
430  MPObjective* MutableObjective() { return objective_.get(); }
431 
453  };
454 
457 
459  ResultStatus Solve(const MPSolverParameters& param);
460 
465  void Write(const std::string& file_name);
466 
473  std::vector<double> ComputeConstraintActivities() const;
474 
493  bool VerifySolution(double tolerance, bool log_errors) const;
494 
503  void Reset();
504 
514  bool InterruptSolve();
515 
524  std::string* error_message);
533  const MPModelProto& input_model, std::string* error_message);
534 
536  void FillSolutionResponseProto(MPSolutionResponse* response) const;
537 
553  static void SolveWithProto(const MPModelRequest& model_request,
554  MPSolutionResponse* response,
555  const std::atomic<bool>* interrupt = nullptr);
556 
558  const MPModelRequest::SolverType solver) {
559  // Interruption requires that MPSolver::InterruptSolve is supported for the
560  // underlying solver. Interrupting requests using SCIP is also not supported
561  // as of 2021/08/23, since InterruptSolve is not thread-safe for SCIP.
562  return solver == MPModelRequest::GLOP_LINEAR_PROGRAMMING ||
566  }
567 
569  void ExportModelToProto(MPModelProto* output_model) const;
570 
604  absl::Status LoadSolutionFromProto(
605  const MPSolutionResponse& response,
606  double tolerance = kDefaultPrimalTolerance);
607 
612  absl::Status ClampSolutionWithinBounds();
613 
620  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
621  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
622  std::string* model_str) const;
623 
634  absl::Status SetNumThreads(int num_threads);
635 
637  int GetNumThreads() const { return num_threads_; }
638 
645  bool SetSolverSpecificParametersAsString(const std::string& parameters);
647  return solver_specific_parameter_string_;
648  }
649 
663  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
664 
669  enum BasisStatus {
670  FREE = 0,
675  };
676 
688  void SetStartingLpBasis(
689  const std::vector<MPSolver::BasisStatus>& variable_statuses,
690  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
691 
697  static double infinity() { return std::numeric_limits<double>::infinity(); }
698 
707  bool OutputIsEnabled() const;
708 
710  void EnableOutput();
711 
713  void SuppressOutput();
714 
715  absl::Duration TimeLimit() const { return time_limit_; }
716  void SetTimeLimit(absl::Duration time_limit) {
717  DCHECK_GE(time_limit, absl::ZeroDuration());
718  time_limit_ = time_limit;
719  }
720 
721  absl::Duration DurationSinceConstruction() const {
722  return absl::Now() - construction_time_;
723  }
724 
726  int64_t iterations() const;
727 
733  int64_t nodes() const;
734 
736  std::string SolverVersion() const;
737 
751  void* underlying_solver();
752 
776  double ComputeExactConditionNumber() const;
777 
792  ABSL_MUST_USE_RESULT bool NextSolution();
793 
794  // Does not take ownership of "mp_callback".
795  //
796  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
797  // SCIP does not support suggesting a heuristic solution in the callback.
798  //
799  // See go/mpsolver-callbacks for additional documentation.
800  void SetCallback(MPCallback* mp_callback);
801  bool SupportsCallbacks() const;
802 
803  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
804  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
805  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
806  int64_t time_limit() const {
807  return time_limit_ == absl::InfiniteDuration()
808  ? 0
809  : absl::ToInt64Milliseconds(time_limit_);
810  }
811  void set_time_limit(int64_t time_limit_milliseconds) {
812  SetTimeLimit(time_limit_milliseconds == 0
813  ? absl::InfiniteDuration()
814  : absl::Milliseconds(time_limit_milliseconds));
815  }
816  double time_limit_in_secs() const {
817  return static_cast<double>(time_limit()) / 1000.0;
818  }
819 
820  // DEPRECATED: Use DurationSinceConstruction() instead.
821  int64_t wall_time() const {
822  return absl::ToInt64Milliseconds(DurationSinceConstruction());
823  }
824 
825  friend class GLPKInterface;
826  friend class CLPInterface;
827  friend class CBCInterface;
828  friend class SCIPInterface;
829  friend class GurobiInterface;
830  friend class CplexInterface;
831  friend class XpressInterface;
832  friend class SLMInterface;
833  friend class MPSolverInterface;
834  friend class GLOPInterface;
835  friend class BopInterface;
836  friend class SatInterface;
837  friend class KnapsackInterface;
838 
839  // Debugging: verify that the given MPVariable* belongs to this solver.
840  bool OwnsVariable(const MPVariable* var) const;
841 
842  private:
843  // Computes the size of the constraint with the largest number of
844  // coefficients with index in [min_constraint_index,
845  // max_constraint_index)
846  int ComputeMaxConstraintSize(int min_constraint_index,
847  int max_constraint_index) const;
848 
849  // Returns true if the model has constraints with lower bound > upper bound.
850  bool HasInfeasibleConstraints() const;
851 
852  // Returns true if the model has at least 1 integer variable.
853  bool HasIntegerVariables() const;
854 
855  // Generates the map from variable names to their indices.
856  void GenerateVariableNameIndex() const;
857 
858  // Generates the map from constraint names to their indices.
859  void GenerateConstraintNameIndex() const;
860 
861  // The name of the linear programming problem.
862  const std::string name_;
863 
864  // The type of the linear programming problem.
865  const OptimizationProblemType problem_type_;
866 
867  // The solver interface.
868  std::unique_ptr<MPSolverInterface> interface_;
869 
870  // The vector of variables in the problem.
871  std::vector<MPVariable*> variables_;
872  // A map from a variable's name to its index in variables_.
873  mutable absl::optional<absl::flat_hash_map<std::string, int> >
874  variable_name_to_index_;
875  // Whether variables have been extracted to the underlying interface.
876  std::vector<bool> variable_is_extracted_;
877 
878  // The vector of constraints in the problem.
879  std::vector<MPConstraint*> constraints_;
880  // A map from a constraint's name to its index in constraints_.
881  mutable absl::optional<absl::flat_hash_map<std::string, int> >
882  constraint_name_to_index_;
883  // Whether constraints have been extracted to the underlying interface.
884  std::vector<bool> constraint_is_extracted_;
885 
886  // The linear objective function.
887  std::unique_ptr<MPObjective> objective_;
888 
889  // Initial values for all or some of the problem variables that can be
890  // exploited as a starting hint by a solver.
891  //
892  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
893  //
894  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
895  // hint is provided and a std::vector<double> for the hint value.
896  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
897 
898  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
899 
900  const absl::Time construction_time_;
901 
902  // Permanent storage for the number of threads.
903  int num_threads_ = 1;
904 
905  // Permanent storage for SetSolverSpecificParametersAsString().
906  std::string solver_specific_parameter_string_;
907 
908  MPSolverResponseStatus LoadModelFromProtoInternal(
909  const MPModelProto& input_model, bool clear_names,
910  bool check_model_validity, std::string* error_message);
911 
912  DISALLOW_COPY_AND_ASSIGN(MPSolver);
913 };
914 
916  return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
917 }
918 
919 const absl::string_view ToString(
920  MPSolver::OptimizationProblemType optimization_problem_type);
921 
922 inline std::ostream& operator<<(
923  std::ostream& os,
924  MPSolver::OptimizationProblemType optimization_problem_type) {
925  return os << ToString(optimization_problem_type);
926 }
927 
928 inline std::ostream& operator<<(std::ostream& os,
929  MPSolver::ResultStatus status) {
930  return os << ProtoEnumToString<MPSolverResponseStatus>(
931  static_cast<MPSolverResponseStatus>(status));
932 }
933 
934 bool AbslParseFlag(absl::string_view text,
936  std::string* error);
937 
938 inline std::string AbslUnparseFlag(
939  MPSolver::OptimizationProblemType solver_type) {
940  return std::string(ToString(solver_type));
941 }
942 
944 class MPObjective {
945  public:
950  void Clear();
951 
958  void SetCoefficient(const MPVariable* const var, double coeff);
959 
965  double GetCoefficient(const MPVariable* const var) const;
966 
972  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
973  return coefficients_;
974  }
975 
977  void SetOffset(double value);
978 
980  double offset() const { return offset_; }
981 
986  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
987 
989  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
990  OptimizeLinearExpr(linear_expr, true);
991  }
993  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
994  OptimizeLinearExpr(linear_expr, false);
995  }
996 
998  void AddLinearExpr(const LinearExpr& linear_expr);
999 
1001  void SetOptimizationDirection(bool maximize);
1002 
1005 
1008 
1010  bool maximization() const;
1011 
1013  bool minimization() const;
1014 
1026  double Value() const;
1027 
1034  double BestBound() const;
1035 
1036  private:
1037  friend class MPSolver;
1038  friend class MPSolverInterface;
1039  friend class CBCInterface;
1040  friend class CLPInterface;
1041  friend class GLPKInterface;
1042  friend class SCIPInterface;
1043  friend class SLMInterface;
1044  friend class GurobiInterface;
1045  friend class CplexInterface;
1046  friend class XpressInterface;
1047  friend class GLOPInterface;
1048  friend class BopInterface;
1049  friend class SatInterface;
1050  friend class KnapsackInterface;
1051 
1052  // Constructor. An objective points to a single MPSolverInterface
1053  // that is specified in the constructor. An objective cannot belong
1054  // to several models.
1055  // At construction, an MPObjective has no terms (which is equivalent
1056  // on having a coefficient of 0 for all variables), and an offset of 0.
1057  explicit MPObjective(MPSolverInterface* const interface_in)
1058  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1059 
1060  MPSolverInterface* const interface_;
1061 
1062  // Mapping var -> coefficient.
1063  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1064  // Constant term.
1065  double offset_;
1066 
1067  DISALLOW_COPY_AND_ASSIGN(MPObjective);
1068 };
1069 
1071 class MPVariable {
1072  public:
1074  const std::string& name() const { return name_; }
1075 
1077  void SetInteger(bool integer);
1078 
1080  bool integer() const { return integer_; }
1081 
1089  double solution_value() const;
1090 
1092  int index() const { return index_; }
1093 
1095  double lb() const { return lb_; }
1096 
1098  double ub() const { return ub_; }
1099 
1101  void SetLB(double lb) { SetBounds(lb, ub_); }
1102 
1104  void SetUB(double ub) { SetBounds(lb_, ub); }
1105 
1107  void SetBounds(double lb, double ub);
1108 
1115  double unrounded_solution_value() const;
1116 
1121  double reduced_cost() const;
1122 
1130 
1141  int branching_priority() const { return branching_priority_; }
1142  void SetBranchingPriority(int priority);
1143 
1144  protected:
1145  friend class MPSolver;
1146  friend class MPSolverInterface;
1147  friend class CBCInterface;
1148  friend class CLPInterface;
1149  friend class GLPKInterface;
1150  friend class SCIPInterface;
1151  friend class SLMInterface;
1152  friend class GurobiInterface;
1153  friend class CplexInterface;
1154  friend class XpressInterface;
1155  friend class GLOPInterface;
1157  friend class BopInterface;
1158  friend class SatInterface;
1159  friend class KnapsackInterface;
1160 
1161  // Constructor. A variable points to a single MPSolverInterface that
1162  // is specified in the constructor. A variable cannot belong to
1163  // several models.
1164  MPVariable(int index, double lb, double ub, bool integer,
1165  const std::string& name, MPSolverInterface* const interface_in)
1166  : index_(index),
1167  lb_(lb),
1168  ub_(ub),
1169  integer_(integer),
1170  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1171  solution_value_(0.0),
1172  reduced_cost_(0.0),
1173  interface_(interface_in) {}
1174 
1175  void set_solution_value(double value) { solution_value_ = value; }
1176  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1177 
1178  private:
1179  const int index_;
1180  double lb_;
1181  double ub_;
1182  bool integer_;
1183  const std::string name_;
1184  double solution_value_;
1185  double reduced_cost_;
1186  int branching_priority_ = 0;
1187  MPSolverInterface* const interface_;
1188  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1189 };
1190 
1197  public:
1199  const std::string& name() const { return name_; }
1200 
1202  void Clear();
1203 
1210  void SetCoefficient(const MPVariable* const var, double coeff);
1211 
1216  double GetCoefficient(const MPVariable* const var) const;
1217 
1223  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1224  return coefficients_;
1225  }
1226 
1228  double lb() const { return lb_; }
1229 
1231  double ub() const { return ub_; }
1232 
1234  void SetLB(double lb) { SetBounds(lb, ub_); }
1235 
1237  void SetUB(double ub) { SetBounds(lb_, ub); }
1238 
1240  void SetBounds(double lb, double ub);
1241 
1243  bool is_lazy() const { return is_lazy_; }
1244 
1258  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1259 
1260  const MPVariable* indicator_variable() const { return indicator_variable_; }
1261  bool indicator_value() const { return indicator_value_; }
1262 
1264  int index() const { return index_; }
1265 
1270  double dual_value() const;
1271 
1285 
1286  protected:
1287  friend class MPSolver;
1288  friend class MPSolverInterface;
1289  friend class CBCInterface;
1290  friend class CLPInterface;
1291  friend class GLPKInterface;
1292  friend class SCIPInterface;
1293  friend class SLMInterface;
1294  friend class GurobiInterface;
1295  friend class CplexInterface;
1296  friend class XpressInterface;
1297  friend class GLOPInterface;
1298  friend class BopInterface;
1299  friend class SatInterface;
1300  friend class KnapsackInterface;
1301 
1302  // Constructor. A constraint points to a single MPSolverInterface
1303  // that is specified in the constructor. A constraint cannot belong
1304  // to several models.
1305  MPConstraint(int index, double lb, double ub, const std::string& name,
1306  MPSolverInterface* const interface_in)
1307  : coefficients_(1),
1308  index_(index),
1309  lb_(lb),
1310  ub_(ub),
1311  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1312  is_lazy_(false),
1313  indicator_variable_(nullptr),
1314  dual_value_(0.0),
1315  interface_(interface_in) {}
1316 
1317  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1318 
1319  private:
1320  // Returns true if the constraint contains variables that have not
1321  // been extracted yet.
1322  bool ContainsNewVariables();
1323 
1324  // Mapping var -> coefficient.
1325  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1326 
1327  const int index_; // See index().
1328 
1329  // The lower bound for the linear constraint.
1330  double lb_;
1331 
1332  // The upper bound for the linear constraint.
1333  double ub_;
1334 
1335  // Name.
1336  const std::string name_;
1337 
1338  // True if the constraint is "lazy", i.e. the constraint is added to the
1339  // underlying Linear Programming solver only if it is violated.
1340  // By default this parameter is 'false'.
1341  bool is_lazy_;
1342 
1343  // If given, this constraint is only active if `indicator_variable_`'s value
1344  // is equal to `indicator_value_`.
1345  const MPVariable* indicator_variable_;
1346  bool indicator_value_;
1347 
1348  double dual_value_;
1349  MPSolverInterface* const interface_;
1350  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1351 };
1352 
1380  public:
1385 
1395  };
1396 
1400  PRESOLVE = 1000,
1406  SCALING = 1003
1407  };
1408 
1415  };
1416 
1420  DUAL = 10,
1422  PRIMAL = 11,
1424  BARRIER = 12
1425  };
1426 
1431 
1437  };
1438 
1445  };
1446 
1447  // Placeholder value to indicate that a parameter is set to
1448  // the default value defined in the wrapper.
1449  static const double kDefaultDoubleParamValue;
1450  static const int kDefaultIntegerParamValue;
1451 
1452  // Placeholder value to indicate that a parameter is unknown.
1453  static const double kUnknownDoubleParamValue;
1454  static const int kUnknownIntegerParamValue;
1455 
1456  // Default values for parameters. Only parameters that define the
1457  // properties of the solution returned need to have a default value
1458  // (that is the same for all solvers). You can also define a default
1459  // value for performance parameters when you are confident it is a
1460  // good choice (example: always turn presolve on).
1461  static const double kDefaultRelativeMipGap;
1462  static const double kDefaultPrimalTolerance;
1463  static const double kDefaultDualTolerance;
1466 
1469 
1471  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1472 
1474  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1475 
1482 
1489 
1491  void Reset();
1492 
1494  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1495 
1498 
1499  private:
1500  // Parameter value for each parameter.
1501  // @see DoubleParam
1502  // @see IntegerParam
1503  double relative_mip_gap_value_;
1504  double primal_tolerance_value_;
1505  double dual_tolerance_value_;
1506  int presolve_value_;
1507  int scaling_value_;
1508  int lp_algorithm_value_;
1509  int incrementality_value_;
1510 
1511  // Boolean value indicating whether each parameter is set to the
1512  // solver's default value. Only parameters for which the wrapper
1513  // does not define a default value need such an indicator.
1514  bool lp_algorithm_is_default_;
1515 
1516  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1517 };
1518 
1519 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1520 // error when happening on the linear solver stubby server, see
1521 // ./linear_solver_service.proto.
1522 // Note that RPC errors forbid to carry a response to the client, who can only
1523 // see the RPC error itself (error code + error message).
1525 
1526 // This class wraps the actual mathematical programming solvers. Each
1527 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1528 // derives from this abstract class. This class is never directly
1529 // accessed by the user.
1530 // @see glop_interface.cc
1531 // @see cbc_interface.cc
1532 // @see clp_interface.cc
1533 // @see glpk_interface.cc
1534 // @see scip_interface.cc
1536  public:
1538  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1539  // sync for the model nor for the solution.
1541  // The underlying solver and MPSolver are in sync for the model
1542  // but not for the solution: the model has changed since the
1543  // solution was computed last.
1545  // The underlying solver and MPSolver are in sync for the model and
1546  // the solution.
1548  };
1549 
1550  // When the underlying solver does not provide the number of simplex
1551  // iterations.
1552  static constexpr int64_t kUnknownNumberOfIterations = -1;
1553  // When the underlying solver does not provide the number of
1554  // branch-and-bound nodes.
1555  static constexpr int64_t kUnknownNumberOfNodes = -1;
1556 
1557  // Constructor. The user will access the MPSolverInterface through the
1558  // MPSolver passed as argument.
1559  explicit MPSolverInterface(MPSolver* const solver);
1560  virtual ~MPSolverInterface();
1561 
1562  // ----- Solve -----
1563  // Solves problem with specified parameter values. Returns true if the
1564  // solution is optimal.
1565  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1566 
1567  // Directly solves a MPModelRequest, bypassing the MPSolver data structures
1568  // entirely. Returns {} (eg. absl::nullopt) if the feature is not supported by
1569  // the underlying solver.
1570  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1571  const MPModelRequest& request) {
1572  return absl::nullopt;
1573  }
1574 
1575  // Writes the model using the solver internal write function. Currently only
1576  // available for GurobiInterface.
1577  virtual void Write(const std::string& filename);
1578 
1579  // ----- Model modifications and extraction -----
1580  // Resets extracted model.
1581  virtual void Reset() = 0;
1582 
1583  // Sets the optimization direction (min/max).
1584  virtual void SetOptimizationDirection(bool maximize) = 0;
1585 
1586  // Modifies bounds of an extracted variable.
1587  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1588 
1589  // Modifies integrality of an extracted variable.
1590  virtual void SetVariableInteger(int index, bool integer) = 0;
1591 
1592  // Modify bounds of an extracted variable.
1593  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1594 
1595  // Adds a linear constraint.
1596  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1597 
1598  // Adds an indicator constraint. Returns true if the feature is supported by
1599  // the underlying solver.
1600  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1601  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1602  return false;
1603  }
1604 
1605  // Add a variable.
1606  virtual void AddVariable(MPVariable* const var) = 0;
1607 
1608  // Changes a coefficient in a constraint.
1609  virtual void SetCoefficient(MPConstraint* const constraint,
1610  const MPVariable* const variable,
1611  double new_value, double old_value) = 0;
1612 
1613  // Clears a constraint from all its terms.
1614  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1615 
1616  // Changes a coefficient in the linear objective.
1617  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1618  double coefficient) = 0;
1619 
1620  // Changes the constant term in the linear objective.
1621  virtual void SetObjectiveOffset(double value) = 0;
1622 
1623  // Clears the objective from all its terms.
1624  virtual void ClearObjective() = 0;
1625 
1626  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1627  // ------ Query statistics on the solution and the solve ------
1628  // Returns the number of simplex iterations. The problem must be discrete,
1629  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1630  virtual int64_t iterations() const = 0;
1631  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1632  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1633  virtual int64_t nodes() const = 0;
1634  // Returns the best objective bound. The problem must be discrete, otherwise
1635  // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1636  double best_objective_bound() const;
1637  // Returns the objective value of the best solution found so far.
1638  double objective_value() const;
1639 
1640  // Returns the basis status of a row.
1641  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1642  // Returns the basis status of a constraint.
1643  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1644 
1645  // Checks whether the solution is synchronized with the model, i.e. whether
1646  // the model has changed since the solution was computed last.
1647  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1648  bool CheckSolutionIsSynchronized() const;
1649  // Checks whether a feasible solution exists. The behavior is similar to
1650  // CheckSolutionIsSynchronized() above.
1651  virtual bool CheckSolutionExists() const;
1652  // Handy shortcut to do both checks above (it is often used).
1655  }
1656 
1657  // ----- Misc -----
1658  // Queries problem type. For simplicity, the distinction between
1659  // continuous and discrete is based on the declaration of the user
1660  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1661  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1662  // the model.
1663  // Returns true if the problem is continuous.
1664  virtual bool IsContinuous() const = 0;
1665  // Returns true if the problem is continuous and linear.
1666  virtual bool IsLP() const = 0;
1667  // Returns true if the problem is discrete and linear.
1668  virtual bool IsMIP() const = 0;
1669 
1670  // Returns the index of the last variable extracted.
1672 
1673  bool variable_is_extracted(int var_index) const {
1674  return solver_->variable_is_extracted_[var_index];
1675  }
1676  void set_variable_as_extracted(int var_index, bool extracted) {
1677  solver_->variable_is_extracted_[var_index] = extracted;
1678  }
1679  bool constraint_is_extracted(int ct_index) const {
1680  return solver_->constraint_is_extracted_[ct_index];
1681  }
1682  void set_constraint_as_extracted(int ct_index, bool extracted) {
1683  solver_->constraint_is_extracted_[ct_index] = extracted;
1684  }
1685 
1686  // Returns the boolean indicating the verbosity of the solver output.
1687  bool quiet() const { return quiet_; }
1688  // Sets the boolean indicating the verbosity of the solver output.
1689  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1690 
1691  // Returns the result status of the last solve.
1694  return result_status_;
1695  }
1696 
1697  // Returns a string describing the underlying solver and its version.
1698  virtual std::string SolverVersion() const = 0;
1699 
1700  // Returns the underlying solver.
1701  virtual void* underlying_solver() = 0;
1702 
1703  // Computes exact condition number. Only available for continuous
1704  // problems and only implemented in GLPK.
1705  virtual double ComputeExactConditionNumber() const;
1706 
1707  // See MPSolver::SetStartingLpBasis().
1708  virtual void SetStartingLpBasis(
1709  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1710  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1711  LOG(FATAL) << "Not supported by this solver.";
1712  }
1713 
1714  virtual bool InterruptSolve() { return false; }
1715 
1716  // See MPSolver::NextSolution() for contract.
1717  virtual bool NextSolution() { return false; }
1718 
1719  // See MPSolver::SetCallback() for details.
1720  virtual void SetCallback(MPCallback* mp_callback) {
1721  LOG(FATAL) << "Callbacks not supported for this solver.";
1722  }
1723 
1724  virtual bool SupportsCallbacks() const { return false; }
1725 
1726  friend class MPSolver;
1727 
1728  // To access the maximize_ bool and the MPSolver.
1729  friend class MPConstraint;
1730  friend class MPObjective;
1731 
1732  protected:
1734  // Indicates whether the model and the solution are synchronized.
1736  // Indicates whether the solve has reached optimality,
1737  // infeasibility, a limit, etc.
1739  // Optimization direction.
1741 
1742  // Index in MPSolver::variables_ of last constraint extracted.
1744  // Index in MPSolver::constraints_ of last variable extracted.
1746 
1747  // The value of the objective function.
1749 
1750  // The value of the best objective bound. Used only for MIP solvers.
1752 
1753  // Boolean indicator for the verbosity of the solver output.
1754  bool quiet_;
1755 
1756  // Index of dummy variable created for empty constraints or the
1757  // objective offset.
1758  static const int kDummyVariableIndex;
1759 
1760  // Extracts model stored in MPSolver.
1761  void ExtractModel();
1762  // Extracts the variables that have not been extracted yet.
1763  virtual void ExtractNewVariables() = 0;
1764  // Extracts the constraints that have not been extracted yet.
1765  virtual void ExtractNewConstraints() = 0;
1766  // Extracts the objective.
1767  virtual void ExtractObjective() = 0;
1768  // Resets the extraction information.
1770  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1771  // MODEL_SYNCHRONIZED. To be used for model changes.
1773 
1774  // Sets parameters common to LP and MIP in the underlying solver.
1775  void SetCommonParameters(const MPSolverParameters& param);
1776  // Sets MIP specific parameters in the underlying solver.
1777  void SetMIPParameters(const MPSolverParameters& param);
1778  // Sets all parameters in the underlying solver.
1779  virtual void SetParameters(const MPSolverParameters& param) = 0;
1780  // Sets an unsupported double parameter.
1782  // Sets an unsupported integer parameter.
1783  virtual void SetUnsupportedIntegerParam(
1785  // Sets a supported double parameter to an unsupported value.
1787  double value);
1788  // Sets a supported integer parameter to an unsupported value.
1789  virtual void SetIntegerParamToUnsupportedValue(
1790  MPSolverParameters::IntegerParam param, int value);
1791  // Sets each parameter in the underlying solver.
1792  virtual void SetRelativeMipGap(double value) = 0;
1793  virtual void SetPrimalTolerance(double value) = 0;
1794  virtual void SetDualTolerance(double value) = 0;
1795  virtual void SetPresolveMode(int value) = 0;
1796 
1797  // Sets the number of threads to be used by the solver.
1798  virtual absl::Status SetNumThreads(int num_threads);
1799 
1800  // Pass solver specific parameters in text format. The format is
1801  // solver-specific and is the same as the corresponding solver configuration
1802  // file format. Returns true if the operation was successful.
1803  //
1804  // Default implementation returns true if the input is empty. It returns false
1805  // and logs a WARNING if the input is not empty.
1807  const std::string& parameters);
1808 
1809  // Sets the scaling mode.
1810  virtual void SetScalingMode(int value) = 0;
1811  virtual void SetLpAlgorithm(int value) = 0;
1812 };
1813 
1814 } // namespace operations_research
1815 
1816 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
ResultStatus
The status of solving the problem.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
static const IncrementalityValues kDefaultIncrementality
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
void set_variable_as_extracted(int var_index, bool extracted)
virtual void Write(const std::string &filename)
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
Advanced usage: incrementality from one solve to the next.
virtual absl::Status SetNumThreads(int num_threads)
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
virtual void SetLpAlgorithm(int value)=0
ScalingValues
Advanced usage: Scaling options.
double Value() const
Returns the objective value of the best solution found so far.
virtual void SetOptimizationDirection(bool maximize)=0
virtual void SetPresolveMode(int value)=0
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
MPSolver::ResultStatus result_status() const
void set_constraint_as_extracted(int ct_index, bool extracted)
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
void SetOffset(double value)
Sets the constant term in the objective.
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
const std::string & name() const
Returns the name of the constraint.
const MPObjective & Objective() const
Returns the objective object.
MPSolverParameters()
The constructor sets all parameters to their default value.
double ub() const
Returns the upper bound.
static double infinity()
Infinity.
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
virtual void ClearConstraint(MPConstraint *const constraint)=0
virtual void SetCallback(MPCallback *mp_callback)
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
double BestBound() const
Returns the best objective bound.
int NumVariables() const
Returns the number of variables.
bool integer() const
Returns the integrality requirement of the variable.
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
Parses the name of the solver.
bool minimization() const
Is the optimization direction set to minimize?
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
void SetMinimization()
Sets the optimization direction to minimize.
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
A class to express a linear objective.
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
virtual absl::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request)
const MPVariable * indicator_variable() const
ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
IntegerParam
Enumeration of parameters that take integer or categorical values.
virtual bool IsContinuous() const =0
MPObjective * MutableObjective()
Returns the mutable objective object.
void Reset()
Advanced usage: resets extracted model to solve from scratch.
virtual int64_t nodes() const =0
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...
void set_dual_value(double dual_value)
MPSolverInterface(MPSolver *const solver)
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
virtual int64_t iterations() const =0
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
virtual void SetRelativeMipGap(double value)=0
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
absl::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
void set_solution_value(double value)
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
virtual bool CheckSolutionExists() const
The class for variables of a Mathematical Programming (MP) model.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
virtual double ComputeExactConditionNumber() const
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, const std::atomic< bool > *interrupt=nullptr)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
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...
virtual void SetObjectiveOffset(double value)=0
the model is trivially invalid (NaN coefficients, etc).
DoubleParam
Enumeration of parameters that take continuous values.
virtual void SetDualTolerance(double value)=0
void * underlying_solver()
Advanced usage: returns the underlying solver.
virtual void SetScalingMode(int value)=0
std::ostream & operator<<(std::ostream &stream, const LinearExpr &linear_expr)
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
double ub() const
Returns the upper bound.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
absl::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying 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 SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
ResultStatus Solve()
Solves the problem using the default parameter values.
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
int64_t iterations() const
Returns the number of simplex iterations.
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 SetConstraintBounds(int index, double lb, double ub)=0
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
void SetCommonParameters(const MPSolverParameters &param)
static constexpr int64_t kUnknownNumberOfIterations
virtual std::string SolverVersion() const =0
const std::string & name() const
Returns the name of the variable.
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
void SuppressOutput()
Suppresses solver logging.
void Reset()
Sets all parameters to their default value.
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
Parses the name of the solver and returns the correct optimization type or dies.
double solution_value() const
Returns the value of the variable in the current solution.
virtual void SetVariableBounds(int index, double lb, double ub)=0
void SetLB(double lb)
Sets the lower bound.
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
The class for constraints of a Mathematical Programming (MP) model.
feasible, or stopped by limit.
static constexpr SolverType SAT_INTEGER_PROGRAMMING
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
void SetMIPParameters(const MPSolverParameters &param)
static bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
void EnableOutput()
Enables solver logging.
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
bool constraint_is_extracted(int ct_index) const
Advanced usage: tolerance for primal feasibility of basic solutions.
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
absl::Duration DurationSinceConstruction() const
static constexpr SolverType GLOP_LINEAR_PROGRAMMING
void SetLB(double lb)
Sets the lower bound.
This file allows you to write natural code (like a mathematical equation) to model optimization probl...
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
virtual void BranchingPriorityChangedForVariable(int var_index)
int NumConstraints() const
Returns the number of constraints.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
int index() const
Returns the index of the variable in the MPSolver::variables_.
Advanced usage: enable or disable matrix scaling.
void SetCallback(MPCallback *mp_callback)
void SetBranchingPriority(int priority)
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
std::string GetSolverSpecificParametersAsString() const
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
virtual void AddRowConstraint(MPConstraint *const ct)=0
static constexpr int64_t kUnknownNumberOfNodes
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
Advanced usage: tolerance for dual feasibility of basic solutions.
bool AbslParseFlag(absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
absl::Duration TimeLimit() const
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool maximization() const
Is the optimization direction set to maximize?
double lb() const
Returns the lower bound.
void SetTimeLimit(absl::Duration time_limit)
MPVariable * variable(int index) const
Returns the variable at position index.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
int64_t nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
static constexpr SolverType GUROBI_MIXED_INTEGER_PROGRAMMING
static constexpr SolverType GUROBI_LINEAR_PROGRAMMING
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
double lb() const
Returns the lower bound.
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=kDefaultPrimalTolerance)
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
static const PresolveValues kDefaultPresolve
Reuse results from previous solve as much as the underlying solver allows.
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
static MPSolver * CreateSolver(const std::string &solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
IncrementalityValues
Advanced usage: Incrementality options.
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
bool OwnsVariable(const MPVariable *var) const
virtual void SetVariableInteger(int index, bool integer)=0
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
abnormal, i.e., error of some kind.
void SetUB(double ub)
Sets the upper bound.
void SetUB(double ub)
Sets the upper bound.
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
const std::string & Name() const
Returns the name of the model set at construction.
This class stores parameter settings for LP and MIP solvers.
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
PresolveValues
For each categorical parameter, enumeration of possible values.
An expression of the form:
Definition: linear_expr.h:192
virtual void SetPrimalTolerance(double value)=0
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
int GetNumThreads() const
Returns the number of threads to be used during solve.
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
MPConstraint * constraint(int index) const
Returns the constraint at the given index.
constexpr double kDefaultPrimalTolerance
void set_time_limit(int64_t time_limit_milliseconds)
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
virtual void AddVariable(MPVariable *const var)=0
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
double offset() const
Gets the constant term in the objective.
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
void set_reduced_cost(double reduced_cost)
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
bool variable_is_extracted(int var_index) const
virtual void SetParameters(const MPSolverParameters &param)=0
void SetMaximization()
Sets the optimization direction to maximize.
int branching_priority() const
Advanced usage: Certain MIP solvers (e.g.
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".