OR-Tools  9.6
linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2022 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 <optional>
144 #include <ostream>
145 #include <string>
146 #include <utility>
147 #include <vector>
148 
149 #include "absl/base/port.h"
150 #include "absl/flags/parse.h"
151 #include "absl/flags/usage.h"
152 #include "absl/status/status.h"
153 #include "absl/strings/match.h"
154 #include "absl/strings/str_format.h"
155 #include "absl/types/optional.h"
157 #include "ortools/base/logging.h"
158 #include "ortools/base/macros.h"
159 #include "ortools/base/timer.h"
161 #include "ortools/linear_solver/linear_solver.pb.h"
164 
165 ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
166 
167 namespace operations_research {
168 
169 constexpr double kDefaultPrimalTolerance = 1e-07;
170 
171 class MPConstraint;
172 class MPObjective;
173 class MPSolverInterface;
174 class MPSolverParameters;
175 class MPVariable;
176 
177 // There is a homonymous version taking a MPSolver::OptimizationProblemType.
179 
184 class MPSolver {
185  public:
193  // Linear programming problems.
194  // ----------------------------
197  GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
198  // In-house linear programming solver based on the primal-dual hybrid
199  // gradient method. Sometimes faster than Glop for medium-size problems and
200  // scales to much larger problems than Glop.
203 
204  // Integer programming problems.
205  // -----------------------------
206  // Recommended default value for MIP problems.
210 
211  // Commercial software (need license).
219 
220  // Boolean optimization problem (requires only integer variables and works
221  // best with only Boolean variables).
223 
224  // SAT based solver (requires only integer and Boolean variables).
225  // If you pass it mixed integer problems, it will scale coefficients to
226  // integer values, and solver continuous variables as integral variables.
227  //
228  // Recommended default value for pure integral problems problems.
230 
231  // Dedicated knapsack solvers.
233  };
234 
236  MPSolver(const std::string& name, OptimizationProblemType problem_type);
237  virtual ~MPSolver();
238 
267  static MPSolver* CreateSolver(const std::string& solver_id);
268 
274 
280  static bool ParseSolverType(absl::string_view solver_id,
282 
288  const std::string& solver_id);
289 
290  bool IsMIP() const;
291 
293  const std::string& Name() const {
294  return name_; // Set at construction.
295  }
296 
299  return problem_type_; // Set at construction.
300  }
301 
307  void Clear();
308 
310  int NumVariables() const { return variables_.size(); }
311 
316  const std::vector<MPVariable*>& variables() const { return variables_; }
317 
321  MPVariable* variable(int index) const { return variables_[index]; }
322 
328  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
329 
337  MPVariable* MakeVar(double lb, double ub, bool integer,
338  const std::string& name);
339 
341  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
342 
344  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
345 
347  MPVariable* MakeBoolVar(const std::string& name);
348 
363  void MakeVarArray(int nb, double lb, double ub, bool integer,
364  const std::string& name_prefix,
365  std::vector<MPVariable*>* vars);
366 
368  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
369  std::vector<MPVariable*>* vars);
370 
372  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
373  std::vector<MPVariable*>* vars);
374 
376  void MakeBoolVarArray(int nb, const std::string& name,
377  std::vector<MPVariable*>* vars);
378 
380  int NumConstraints() const { return constraints_.size(); }
381 
387  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
388 
390  MPConstraint* constraint(int index) const { return constraints_[index]; }
391 
400  const std::string& constraint_name) const;
401 
410  MPConstraint* MakeRowConstraint(double lb, double ub);
411 
414 
416  MPConstraint* MakeRowConstraint(double lb, double ub,
417  const std::string& name);
418 
420  MPConstraint* MakeRowConstraint(const std::string& name);
421 
427 
430  const std::string& name);
431 
438  const MPObjective& Objective() const { return *objective_; }
439 
441  MPObjective* MutableObjective() { return objective_.get(); }
442 
463  NOT_SOLVED = 6
464  };
465 
468 
470  ResultStatus Solve(const MPSolverParameters& param);
471 
476  void Write(const std::string& file_name);
477 
484  std::vector<double> ComputeConstraintActivities() const;
485 
504  bool VerifySolution(double tolerance, bool log_errors) const;
505 
514  void Reset();
515 
525  bool InterruptSolve();
526 
534  MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
535  std::string* error_message);
543  MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(
544  const MPModelProto& input_model, std::string* error_message);
545 
547  void FillSolutionResponseProto(MPSolutionResponse* response) const;
548 
564  static void SolveWithProto(const MPModelRequest& model_request,
565  MPSolutionResponse* response,
566  // `interrupt` is non-const because the internal
567  // solver may set it to true itself, in some cases.
568  std::atomic<bool>* interrupt = nullptr);
569 
571  const MPModelRequest::SolverType solver) {
572  // Interruption requires that MPSolver::InterruptSolve is supported for the
573  // underlying solver. Interrupting requests using SCIP is also not supported
574  // as of 2021/08/23, since InterruptSolve is not go/thread-safe
575  // for SCIP (see e.g. cl/350545631 for details).
576  return solver == MPModelRequest::GLOP_LINEAR_PROGRAMMING ||
577  solver == MPModelRequest::GUROBI_LINEAR_PROGRAMMING ||
578  solver == MPModelRequest::GUROBI_MIXED_INTEGER_PROGRAMMING ||
579  solver == MPModelRequest::SAT_INTEGER_PROGRAMMING ||
580  solver == MPModelRequest::PDLP_LINEAR_PROGRAMMING;
581  }
582 
584  void ExportModelToProto(MPModelProto* output_model) const;
585 
619  absl::Status LoadSolutionFromProto(
620  const MPSolutionResponse& response,
621  double tolerance = std::numeric_limits<double>::infinity());
622 
627  absl::Status ClampSolutionWithinBounds();
628 
635  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
636  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
637  std::string* model_str) const;
638 
649  absl::Status SetNumThreads(int num_threads);
650 
652  int GetNumThreads() const { return num_threads_; }
653 
660  bool SetSolverSpecificParametersAsString(const std::string& parameters);
662  return solver_specific_parameter_string_;
663  }
664 
680  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
681 
686  enum BasisStatus {
687  FREE = 0,
691  BASIC
692  };
693 
705  void SetStartingLpBasis(
706  const std::vector<MPSolver::BasisStatus>& variable_statuses,
707  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
708 
714  static double infinity() { return std::numeric_limits<double>::infinity(); }
715 
724  bool OutputIsEnabled() const;
725 
727  void EnableOutput();
728 
730  void SuppressOutput();
731 
732  absl::Duration TimeLimit() const { return time_limit_; }
733  void SetTimeLimit(absl::Duration time_limit) {
734  DCHECK_GE(time_limit, absl::ZeroDuration());
735  time_limit_ = time_limit;
736  }
737 
738  absl::Duration DurationSinceConstruction() const {
739  return absl::Now() - construction_time_;
740  }
741 
743  int64_t iterations() const;
744 
750  int64_t nodes() const;
751 
753  std::string SolverVersion() const;
754 
768  void* underlying_solver();
769 
793  double ComputeExactConditionNumber() const;
794 
809  ABSL_MUST_USE_RESULT bool NextSolution();
810 
811  // Does not take ownership of "mp_callback".
812  //
813  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
814  // SCIP does not support suggesting a heuristic solution in the callback.
815  //
816  // See go/mpsolver-callbacks for additional documentation.
817  void SetCallback(MPCallback* mp_callback);
818  bool SupportsCallbacks() const;
819 
820  // Global counters of variables and constraints ever created across all
821  // MPSolver instances. Those are only updated after the destruction
822  // (or Clear()) of each MPSolver instance.
823  static int64_t global_num_variables();
824  static int64_t global_num_constraints();
825 
826  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
827  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
828  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
829  int64_t time_limit() const {
830  return time_limit_ == absl::InfiniteDuration()
831  ? 0
832  : absl::ToInt64Milliseconds(time_limit_);
833  }
834  void set_time_limit(int64_t time_limit_milliseconds) {
835  SetTimeLimit(time_limit_milliseconds == 0
836  ? absl::InfiniteDuration()
837  : absl::Milliseconds(time_limit_milliseconds));
838  }
839  double time_limit_in_secs() const {
840  return static_cast<double>(time_limit()) / 1000.0;
841  }
842 
843  // DEPRECATED: Use DurationSinceConstruction() instead.
844  int64_t wall_time() const {
845  return absl::ToInt64Milliseconds(DurationSinceConstruction());
846  }
847 
848  friend class GLPKInterface;
849  friend class CLPInterface;
850  friend class CBCInterface;
851  friend class SCIPInterface;
852  friend class GurobiInterface;
853  friend class CplexInterface;
854  friend class XpressInterface;
855  friend class SLMInterface;
856  friend class MPSolverInterface;
857  friend class GLOPInterface;
858  friend class BopInterface;
859  friend class SatInterface;
860  friend class PdlpInterface;
861  friend class HighsInterface;
862  friend class KnapsackInterface;
863 
864  // Debugging: verify that the given MPVariable* belongs to this solver.
865  bool OwnsVariable(const MPVariable* var) const;
866 
867  private:
868  // Computes the size of the constraint with the largest number of
869  // coefficients with index in [min_constraint_index,
870  // max_constraint_index)
871  int ComputeMaxConstraintSize(int min_constraint_index,
872  int max_constraint_index) const;
873 
874  // Returns true if the model has constraints with lower bound > upper bound.
875  bool HasInfeasibleConstraints() const;
876 
877  // Returns true if the model has at least 1 integer variable.
878  bool HasIntegerVariables() const;
879 
880  // Generates the map from variable names to their indices.
881  void GenerateVariableNameIndex() const;
882 
883  // Generates the map from constraint names to their indices.
884  void GenerateConstraintNameIndex() const;
885 
886  // The name of the linear programming problem.
887  const std::string name_;
888 
889  // The type of the linear programming problem.
890  const OptimizationProblemType problem_type_;
891 
892  // The solver interface.
893  std::unique_ptr<MPSolverInterface> interface_;
894 
895  // The vector of variables in the problem.
896  std::vector<MPVariable*> variables_;
897  // A map from a variable's name to its index in variables_.
898  mutable std::optional<absl::flat_hash_map<std::string, int> >
899  variable_name_to_index_;
900  // Whether variables have been extracted to the underlying interface.
901  std::vector<bool> variable_is_extracted_;
902 
903  // The vector of constraints in the problem.
904  std::vector<MPConstraint*> constraints_;
905  // A map from a constraint's name to its index in constraints_.
906  mutable std::optional<absl::flat_hash_map<std::string, int> >
907  constraint_name_to_index_;
908  // Whether constraints have been extracted to the underlying interface.
909  std::vector<bool> constraint_is_extracted_;
910 
911  // The linear objective function.
912  std::unique_ptr<MPObjective> objective_;
913 
914  // Initial values for all or some of the problem variables that can be
915  // exploited as a starting hint by a solver.
916  //
917  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
918  //
919  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
920  // hint is provided and a std::vector<double> for the hint value.
921  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
922 
923  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
924 
925  const absl::Time construction_time_;
926 
927  // Permanent storage for the number of threads.
928  int num_threads_ = 1;
929 
930  // Permanent storage for SetSolverSpecificParametersAsString().
931  std::string solver_specific_parameter_string_;
932 
933  static absl::Mutex global_count_mutex_;
934 #ifndef SWIG
935  static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
936  static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
937 #endif
938 
939  MPSolverResponseStatus LoadModelFromProtoInternal(
940  const MPModelProto& input_model, bool clear_names,
941  bool check_model_validity, std::string* error_message);
942 
944 };
945 
947  return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
948 }
949 
950 const absl::string_view ToString(
951  MPSolver::OptimizationProblemType optimization_problem_type);
952 
953 inline std::ostream& operator<<(
954  std::ostream& os,
955  MPSolver::OptimizationProblemType optimization_problem_type) {
956  return os << ToString(optimization_problem_type);
957 }
958 
959 inline std::ostream& operator<<(std::ostream& os,
961  return os << ProtoEnumToString<MPSolverResponseStatus>(
962  static_cast<MPSolverResponseStatus>(status));
963 }
964 
965 bool AbslParseFlag(absl::string_view text,
967  std::string* error);
968 
969 inline std::string AbslUnparseFlag(
970  MPSolver::OptimizationProblemType solver_type) {
971  return std::string(ToString(solver_type));
972 }
973 
975 class MPObjective {
976  public:
981  void Clear();
982 
989  void SetCoefficient(const MPVariable* const var, double coeff);
990 
996  double GetCoefficient(const MPVariable* const var) const;
997 
1003  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1004  return coefficients_;
1005  }
1006 
1008  void SetOffset(double value);
1009 
1011  double offset() const { return offset_; }
1012 
1017  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1018 
1020  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1021  OptimizeLinearExpr(linear_expr, true);
1022  }
1024  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1025  OptimizeLinearExpr(linear_expr, false);
1026  }
1027 
1029  void AddLinearExpr(const LinearExpr& linear_expr);
1030 
1032  void SetOptimizationDirection(bool maximize);
1033 
1036 
1039 
1041  bool maximization() const;
1042 
1044  bool minimization() const;
1045 
1057  double Value() const;
1058 
1065  double BestBound() const;
1066 
1067  private:
1068  friend class MPSolver;
1069  friend class MPSolverInterface;
1070  friend class CBCInterface;
1071  friend class CLPInterface;
1072  friend class GLPKInterface;
1073  friend class SCIPInterface;
1074  friend class SLMInterface;
1075  friend class GurobiInterface;
1076  friend class CplexInterface;
1077  friend class XpressInterface;
1078  friend class GLOPInterface;
1079  friend class BopInterface;
1080  friend class SatInterface;
1081  friend class PdlpInterface;
1082  friend class HighsInterface;
1083  friend class KnapsackInterface;
1084 
1085  // Constructor. An objective points to a single MPSolverInterface
1086  // that is specified in the constructor. An objective cannot belong
1087  // to several models.
1088  // At construction, an MPObjective has no terms (which is equivalent
1089  // on having a coefficient of 0 for all variables), and an offset of 0.
1090  explicit MPObjective(MPSolverInterface* const interface_in)
1091  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1092 
1093  MPSolverInterface* const interface_;
1094 
1095  // Mapping var -> coefficient.
1096  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1097  // Constant term.
1098  double offset_;
1099 
1101 };
1102 
1104 class MPVariable {
1105  public:
1107  const std::string& name() const { return name_; }
1108 
1110  void SetInteger(bool integer);
1111 
1113  bool integer() const { return integer_; }
1114 
1122  double solution_value() const;
1123 
1125  int index() const { return index_; }
1126 
1128  double lb() const { return lb_; }
1129 
1131  double ub() const { return ub_; }
1132 
1134  void SetLB(double lb) { SetBounds(lb, ub_); }
1135 
1137  void SetUB(double ub) { SetBounds(lb_, ub); }
1138 
1140  void SetBounds(double lb, double ub);
1141 
1148  double unrounded_solution_value() const;
1149 
1154  double reduced_cost() const;
1155 
1163 
1174  int branching_priority() const { return branching_priority_; }
1175  void SetBranchingPriority(int priority);
1176 
1177  protected:
1178  friend class MPSolver;
1179  friend class MPSolverInterface;
1180  friend class CBCInterface;
1181  friend class CLPInterface;
1182  friend class GLPKInterface;
1183  friend class SCIPInterface;
1184  friend class SLMInterface;
1185  friend class GurobiInterface;
1186  friend class CplexInterface;
1187  friend class XpressInterface;
1188  friend class GLOPInterface;
1190  friend class BopInterface;
1191  friend class SatInterface;
1192  friend class PdlpInterface;
1193  friend class HighsInterface;
1194  friend class KnapsackInterface;
1195 
1196  // Constructor. A variable points to a single MPSolverInterface that
1197  // is specified in the constructor. A variable cannot belong to
1198  // several models.
1199  MPVariable(int index, double lb, double ub, bool integer,
1200  const std::string& name, MPSolverInterface* const interface_in)
1201  : index_(index),
1202  lb_(lb),
1203  ub_(ub),
1204  integer_(integer),
1205  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1206  solution_value_(0.0),
1207  reduced_cost_(0.0),
1208  interface_(interface_in) {}
1209 
1210  void set_solution_value(double value) { solution_value_ = value; }
1211  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1212 
1213  private:
1214  const int index_;
1215  double lb_;
1216  double ub_;
1217  bool integer_;
1218  const std::string name_;
1219  double solution_value_;
1220  double reduced_cost_;
1221  int branching_priority_ = 0;
1222  MPSolverInterface* const interface_;
1224 };
1225 
1232  public:
1234  const std::string& name() const { return name_; }
1235 
1237  void Clear();
1238 
1245  void SetCoefficient(const MPVariable* const var, double coeff);
1246 
1251  double GetCoefficient(const MPVariable* const var) const;
1252 
1258  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1259  return coefficients_;
1260  }
1261 
1263  double lb() const { return lb_; }
1264 
1266  double ub() const { return ub_; }
1267 
1269  void SetLB(double lb) { SetBounds(lb, ub_); }
1270 
1272  void SetUB(double ub) { SetBounds(lb_, ub); }
1273 
1275  void SetBounds(double lb, double ub);
1276 
1278  bool is_lazy() const { return is_lazy_; }
1279 
1293  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1294 
1295  const MPVariable* indicator_variable() const { return indicator_variable_; }
1296  bool indicator_value() const { return indicator_value_; }
1297 
1299  int index() const { return index_; }
1300 
1305  double dual_value() const;
1306 
1320 
1321  protected:
1322  friend class MPSolver;
1323  friend class MPSolverInterface;
1324  friend class CBCInterface;
1325  friend class CLPInterface;
1326  friend class GLPKInterface;
1327  friend class SCIPInterface;
1328  friend class SLMInterface;
1329  friend class GurobiInterface;
1330  friend class CplexInterface;
1331  friend class XpressInterface;
1332  friend class GLOPInterface;
1333  friend class BopInterface;
1334  friend class SatInterface;
1335  friend class PdlpInterface;
1336  friend class HighsInterface;
1337  friend class KnapsackInterface;
1338 
1339  // Constructor. A constraint points to a single MPSolverInterface
1340  // that is specified in the constructor. A constraint cannot belong
1341  // to several models.
1342  MPConstraint(int index, double lb, double ub, const std::string& name,
1343  MPSolverInterface* const interface_in)
1344  : coefficients_(1),
1345  index_(index),
1346  lb_(lb),
1347  ub_(ub),
1348  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1349  is_lazy_(false),
1350  indicator_variable_(nullptr),
1351  dual_value_(0.0),
1352  interface_(interface_in) {}
1353 
1354  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1355 
1356  private:
1357  // Returns true if the constraint contains variables that have not
1358  // been extracted yet.
1359  bool ContainsNewVariables();
1360 
1361  // Mapping var -> coefficient.
1362  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1363 
1364  const int index_; // See index().
1365 
1366  // The lower bound for the linear constraint.
1367  double lb_;
1368 
1369  // The upper bound for the linear constraint.
1370  double ub_;
1371 
1372  // Name.
1373  const std::string name_;
1374 
1375  // True if the constraint is "lazy", i.e. the constraint is added to the
1376  // underlying Linear Programming solver only if it is violated.
1377  // By default this parameter is 'false'.
1378  bool is_lazy_;
1379 
1380  // If given, this constraint is only active if `indicator_variable_`'s value
1381  // is equal to `indicator_value_`.
1382  const MPVariable* indicator_variable_;
1383  bool indicator_value_;
1384 
1385  double dual_value_;
1386  MPSolverInterface* const interface_;
1388 };
1389 
1417  public:
1422 
1431  DUAL_TOLERANCE = 2
1432  };
1433 
1437  PRESOLVE = 1000,
1443  SCALING = 1003
1444  };
1445 
1451  PRESOLVE_ON = 1
1452  };
1453 
1457  DUAL = 10,
1459  PRIMAL = 11,
1461  BARRIER = 12
1462  };
1463 
1468 
1473  INCREMENTALITY_ON = 1
1474  };
1475 
1481  SCALING_ON = 1
1482  };
1483 
1484  // Placeholder value to indicate that a parameter is set to
1485  // the default value defined in the wrapper.
1486  static const double kDefaultDoubleParamValue;
1487  static const int kDefaultIntegerParamValue;
1488 
1489  // Placeholder value to indicate that a parameter is unknown.
1490  static const double kUnknownDoubleParamValue;
1491  static const int kUnknownIntegerParamValue;
1492 
1493  // Default values for parameters. Only parameters that define the
1494  // properties of the solution returned need to have a default value
1495  // (that is the same for all solvers). You can also define a default
1496  // value for performance parameters when you are confident it is a
1497  // good choice (example: always turn presolve on).
1498  static const double kDefaultRelativeMipGap;
1499  static const double kDefaultPrimalTolerance;
1500  static const double kDefaultDualTolerance;
1503 
1506 
1509 
1512 
1519 
1526 
1528  void Reset();
1529 
1531  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1532 
1535 
1536  private:
1537  // Parameter value for each parameter.
1538  // @see DoubleParam
1539  // @see IntegerParam
1540  double relative_mip_gap_value_;
1541  double primal_tolerance_value_;
1542  double dual_tolerance_value_;
1543  int presolve_value_;
1544  int scaling_value_;
1545  int lp_algorithm_value_;
1546  int incrementality_value_;
1547 
1548  // Boolean value indicating whether each parameter is set to the
1549  // solver's default value. Only parameters for which the wrapper
1550  // does not define a default value need such an indicator.
1551  bool lp_algorithm_is_default_;
1552 
1553  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1554 };
1555 
1556 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1557 // error when happening on the linear solver stubby server, see
1558 // ./linear_solver_service.proto.
1559 // Note that RPC errors forbid to carry a response to the client, who can only
1560 // see the RPC error itself (error code + error message).
1561 bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status);
1562 
1563 // This class wraps the actual mathematical programming solvers. Each
1564 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1565 // derives from this abstract class. This class is never directly
1566 // accessed by the user.
1567 // @see glop_interface.cc
1568 // @see cbc_interface.cc
1569 // @see clp_interface.cc
1570 // @see glpk_interface.cc
1571 // @see scip_interface.cc
1573  public:
1575  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1576  // sync for the model nor for the solution.
1578  // The underlying solver and MPSolver are in sync for the model
1579  // but not for the solution: the model has changed since the
1580  // solution was computed last.
1582  // The underlying solver and MPSolver are in sync for the model and
1583  // the solution.
1585  };
1586 
1587  // When the underlying solver does not provide the number of simplex
1588  // iterations.
1589  static constexpr int64_t kUnknownNumberOfIterations = -1;
1590  // When the underlying solver does not provide the number of
1591  // branch-and-bound nodes.
1592  static constexpr int64_t kUnknownNumberOfNodes = -1;
1593 
1594  // Constructor. The user will access the MPSolverInterface through the
1595  // MPSolver passed as argument.
1596  explicit MPSolverInterface(MPSolver* const solver);
1597  virtual ~MPSolverInterface();
1598 
1599  // ----- Solve -----
1600  // Solves problem with specified parameter values. Returns true if the
1601  // solution is optimal.
1603 
1604  // Attempts to directly solve a MPModelRequest, bypassing the MPSolver data
1605  // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1606  // an 'interrupt' boolean.
1607  // Returns {} (eg. absl::nullopt) if direct-solve is not supported by the
1608  // underlying solver (possibly because interrupt != nullptr), in which case
1609  // the user should fall back to using MPSolver.
1610  virtual std::optional<MPSolutionResponse> DirectlySolveProto(
1611  const MPModelRequest& request,
1612  // `interrupt` is non-const because the internal
1613  // solver may set it to true itself, in some cases.
1614  std::atomic<bool>* interrupt) {
1615  return std::nullopt;
1616  }
1617 
1618  // Writes the model using the solver internal write function. Currently only
1619  // available for GurobiInterface.
1620  virtual void Write(const std::string& filename);
1621 
1622  // ----- Model modifications and extraction -----
1623  // Resets extracted model.
1624  virtual void Reset() = 0;
1625 
1626  // Sets the optimization direction (min/max).
1627  virtual void SetOptimizationDirection(bool maximize) = 0;
1628 
1629  // Modifies bounds of an extracted variable.
1630  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1631 
1632  // Modifies integrality of an extracted variable.
1633  virtual void SetVariableInteger(int index, bool integer) = 0;
1634 
1635  // Modify bounds of an extracted variable.
1636  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1637 
1638  // Adds a linear constraint.
1639  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1640 
1641  // Adds an indicator constraint. Returns true if the feature is supported by
1642  // the underlying solver.
1643  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1644  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1645  return false;
1646  }
1647 
1648  // Add a variable.
1649  virtual void AddVariable(MPVariable* const var) = 0;
1650 
1651  // Changes a coefficient in a constraint.
1652  virtual void SetCoefficient(MPConstraint* const constraint,
1653  const MPVariable* const variable,
1654  double new_value, double old_value) = 0;
1655 
1656  // Clears a constraint from all its terms.
1657  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1658 
1659  // Changes a coefficient in the linear objective.
1660  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1661  double coefficient) = 0;
1662 
1663  // Changes the constant term in the linear objective.
1664  virtual void SetObjectiveOffset(double value) = 0;
1665 
1666  // Clears the objective from all its terms.
1667  virtual void ClearObjective() = 0;
1668 
1669  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1670  // ------ Query statistics on the solution and the solve ------
1671  // Returns the number of simplex iterations. The problem must be discrete,
1672  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1673  virtual int64_t iterations() const = 0;
1674  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1675  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1676  virtual int64_t nodes() const = 0;
1677  // Returns the best objective bound. The problem must be discrete, otherwise
1678  // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1679  double best_objective_bound() const;
1680  // Returns the objective value of the best solution found so far.
1681  double objective_value() const;
1682 
1683  // Returns the basis status of a row.
1684  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1685  // Returns the basis status of a constraint.
1686  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1687 
1688  // Checks whether the solution is synchronized with the model, i.e. whether
1689  // the model has changed since the solution was computed last.
1690  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1691  bool CheckSolutionIsSynchronized() const;
1692  // Checks whether a feasible solution exists. The behavior is similar to
1693  // CheckSolutionIsSynchronized() above.
1694  virtual bool CheckSolutionExists() const;
1695  // Handy shortcut to do both checks above (it is often used).
1698  }
1699 
1700  // ----- Misc -----
1701  // Queries problem type. For simplicity, the distinction between
1702  // continuous and discrete is based on the declaration of the user
1703  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1704  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1705  // the model.
1706  // Returns true if the problem is continuous.
1707  virtual bool IsContinuous() const = 0;
1708  // Returns true if the problem is continuous and linear.
1709  virtual bool IsLP() const = 0;
1710  // Returns true if the problem is discrete and linear.
1711  virtual bool IsMIP() const = 0;
1712 
1713  // Returns the index of the last variable extracted.
1715 
1716  bool variable_is_extracted(int var_index) const {
1717  return solver_->variable_is_extracted_[var_index];
1718  }
1719  void set_variable_as_extracted(int var_index, bool extracted) {
1720  solver_->variable_is_extracted_[var_index] = extracted;
1721  }
1722  bool constraint_is_extracted(int ct_index) const {
1723  return solver_->constraint_is_extracted_[ct_index];
1724  }
1725  void set_constraint_as_extracted(int ct_index, bool extracted) {
1726  solver_->constraint_is_extracted_[ct_index] = extracted;
1727  }
1728 
1729  // Returns the boolean indicating the verbosity of the solver output.
1730  bool quiet() const { return quiet_; }
1731  // Sets the boolean indicating the verbosity of the solver output.
1732  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1733 
1734  // Returns the result status of the last solve.
1737  return result_status_;
1738  }
1739 
1740  // Returns a string describing the underlying solver and its version.
1741  virtual std::string SolverVersion() const = 0;
1742 
1743  // Returns the underlying solver.
1744  virtual void* underlying_solver() = 0;
1745 
1746  // Computes exact condition number. Only available for continuous
1747  // problems and only implemented in GLPK.
1748  virtual double ComputeExactConditionNumber() const;
1749 
1750  // See MPSolver::SetStartingLpBasis().
1751  virtual void SetStartingLpBasis(
1752  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1753  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1754  LOG(FATAL) << "Not supported by this solver.";
1755  }
1756 
1757  virtual bool InterruptSolve() { return false; }
1758 
1759  // See MPSolver::NextSolution() for contract.
1760  virtual bool NextSolution() { return false; }
1761 
1762  // See MPSolver::SetCallback() for details.
1763  virtual void SetCallback(MPCallback* mp_callback) {
1764  LOG(FATAL) << "Callbacks not supported for this solver.";
1765  }
1766 
1767  virtual bool SupportsCallbacks() const { return false; }
1768 
1769  friend class MPSolver;
1770 
1771  // To access the maximize_ bool and the MPSolver.
1772  friend class MPConstraint;
1773  friend class MPObjective;
1774 
1775  protected:
1777  // Indicates whether the model and the solution are synchronized.
1779  // Indicates whether the solve has reached optimality,
1780  // infeasibility, a limit, etc.
1782  // Optimization direction.
1784 
1785  // Index in MPSolver::variables_ of last constraint extracted.
1787  // Index in MPSolver::constraints_ of last variable extracted.
1789 
1790  // The value of the objective function.
1792 
1793  // The value of the best objective bound. Used only for MIP solvers.
1795 
1796  // Boolean indicator for the verbosity of the solver output.
1797  bool quiet_;
1798 
1799  // Index of dummy variable created for empty constraints or the
1800  // objective offset.
1801  static const int kDummyVariableIndex;
1802 
1803  // Extracts model stored in MPSolver.
1804  void ExtractModel();
1805  // Extracts the variables that have not been extracted yet.
1806  virtual void ExtractNewVariables() = 0;
1807  // Extracts the constraints that have not been extracted yet.
1808  virtual void ExtractNewConstraints() = 0;
1809  // Extracts the objective.
1810  virtual void ExtractObjective() = 0;
1811  // Resets the extraction information.
1813  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1814  // MODEL_SYNCHRONIZED. To be used for model changes.
1816 
1817  // Sets parameters common to LP and MIP in the underlying solver.
1818  void SetCommonParameters(const MPSolverParameters& param);
1819  // Sets MIP specific parameters in the underlying solver.
1820  void SetMIPParameters(const MPSolverParameters& param);
1821  // Sets all parameters in the underlying solver.
1822  virtual void SetParameters(const MPSolverParameters& param) = 0;
1823  // Sets an unsupported double parameter.
1825  // Sets an unsupported integer parameter.
1826  virtual void SetUnsupportedIntegerParam(
1828  // Sets a supported double parameter to an unsupported value.
1830  double value);
1831  // Sets a supported integer parameter to an unsupported value.
1832  virtual void SetIntegerParamToUnsupportedValue(
1834  // Sets each parameter in the underlying solver.
1835  virtual void SetRelativeMipGap(double value) = 0;
1836  virtual void SetPrimalTolerance(double value) = 0;
1837  virtual void SetDualTolerance(double value) = 0;
1838  virtual void SetPresolveMode(int value) = 0;
1839 
1840  // Sets the number of threads to be used by the solver.
1841  virtual absl::Status SetNumThreads(int num_threads);
1842 
1843  // Pass solver specific parameters in text format. The format is
1844  // solver-specific and is the same as the corresponding solver configuration
1845  // file format. Returns true if the operation was successful.
1846  //
1847  // Default implementation returns true if the input is empty. It returns false
1848  // and logs a WARNING if the input is not empty.
1850  const std::string& parameters);
1851 
1852  // Sets the scaling mode.
1853  virtual void SetScalingMode(int value) = 0;
1854  virtual void SetLpAlgorithm(int value) = 0;
1855 };
1856 
1857 } // namespace operations_research
1858 
1859 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
An expression of the form:
Definition: linear_expr.h:192
The class for constraints of a Mathematical Programming (MP) model.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
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 SetUB(double ub)
Sets the upper bound.
double ub() const
Returns the upper bound.
const MPVariable * indicator_variable() const
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
double lb() const
Returns the lower bound.
void set_dual_value(double dual_value)
const std::string & name() const
Returns the name of the constraint.
void SetLB(double lb)
Sets the lower bound.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
A class to express a linear objective.
void SetMaximization()
Sets the optimization direction to maximize.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
void SetOffset(double value)
Sets the constant term in the objective.
bool maximization() const
Is the optimization direction set to maximize?
void OptimizeLinearExpr(const LinearExpr &linear_expr, bool is_maximization)
Resets the current objective to take the value of linear_expr, and sets the objective direction to ma...
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
double Value() const
Returns the objective value of the best solution found so far.
double offset() const
Gets the constant term in the objective.
double BestBound() const
Returns the best objective bound.
bool minimization() const
Is the optimization direction set to minimize?
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
void SetMinimization()
Sets the optimization direction to minimize.
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
This mathematical programming (MP) solver class is the main class though which users build and solve ...
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
int NumConstraints() const
Returns the number of constraints.
static int64_t global_num_constraints()
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
Parses the name of the solver and returns the correct optimization type or dies.
const std::string & Name() const
Returns the name of the model set at construction.
MPConstraint * constraint(int index) const
Returns the constraint at the given index.
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
MPObjective * MutableObjective()
Returns the mutable objective object.
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
absl::Duration DurationSinceConstruction() const
void Reset()
Advanced usage: resets extracted model to solve from scratch.
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
int64_t iterations() const
Returns the number of simplex iterations.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
static MPSolver * CreateSolver(const std::string &solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
const MPObjective & Objective() const
Returns the objective object.
ResultStatus
The status of solving the problem.
@ FEASIBLE
feasible, or stopped by limit.
@ NOT_SOLVED
not been solved yet.
@ INFEASIBLE
proven infeasible.
@ UNBOUNDED
proven unbounded.
@ ABNORMAL
abnormal, i.e., error of some kind.
@ MODEL_INVALID
the model is trivially invalid (NaN coefficients, etc).
static int64_t global_num_variables()
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
void * underlying_solver()
Advanced usage: returns the underlying solver.
void set_time_limit(int64_t time_limit_milliseconds)
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=std::numeric_limits< double >::infinity())
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
absl::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
int GetNumThreads() const
Returns the number of threads to be used during solve.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
static double infinity()
Infinity.
std::string GetSolverSpecificParametersAsString() const
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
Parses the name of the solver.
int NumVariables() const
Returns the number of variables.
absl::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
bool OwnsVariable(const MPVariable *var) const
int64_t nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
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.
void SetCallback(MPCallback *mp_callback)
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
MPVariable * variable(int index) const
Returns the variable at position index.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
ResultStatus Solve()
Solves the problem using the default parameter values.
void EnableOutput()
Enables solver logging.
void SuppressOutput()
Suppresses solver logging.
static bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
absl::Duration TimeLimit() const
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
void SetTimeLimit(absl::Duration time_limit)
virtual void SetLpAlgorithm(int value)=0
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
virtual void AddVariable(MPVariable *const var)=0
void SetMIPParameters(const MPSolverParameters &param)
virtual bool IsContinuous() const =0
virtual double ComputeExactConditionNumber() const
virtual int64_t iterations() const =0
virtual void Write(const std::string &filename)
virtual int64_t nodes() const =0
MPSolverInterface(MPSolver *const solver)
bool constraint_is_extracted(int ct_index) const
virtual void SetVariableBounds(int index, double lb, double ub)=0
virtual void SetPrimalTolerance(double value)=0
static constexpr int64_t kUnknownNumberOfNodes
virtual void BranchingPriorityChangedForVariable(int var_index)
virtual void SetParameters(const MPSolverParameters &param)=0
virtual void SetRelativeMipGap(double value)=0
virtual void SetOptimizationDirection(bool maximize)=0
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
virtual void SetScalingMode(int value)=0
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual std::string SolverVersion() const =0
virtual absl::Status SetNumThreads(int num_threads)
virtual void ClearConstraint(MPConstraint *const constraint)=0
virtual void SetObjectiveOffset(double value)=0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
virtual void SetVariableInteger(int index, bool integer)=0
virtual void SetCallback(MPCallback *mp_callback)
bool variable_is_extracted(int var_index) const
virtual void SetDualTolerance(double value)=0
virtual std::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request, std::atomic< bool > *interrupt)
virtual void SetPresolveMode(int value)=0
static constexpr int64_t kUnknownNumberOfIterations
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
MPSolver::ResultStatus result_status() const
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
void set_variable_as_extracted(int var_index, bool extracted)
virtual void SetConstraintBounds(int index, double lb, double ub)=0
void SetCommonParameters(const MPSolverParameters &param)
virtual void AddRowConstraint(MPConstraint *const ct)=0
This class stores parameter settings for LP and MIP solvers.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
IncrementalityValues
Advanced usage: Incrementality options.
@ INCREMENTALITY_OFF
Start solve from scratch.
@ INCREMENTALITY_ON
Reuse results from previous solve as much as the underlying solver allows.
ScalingValues
Advanced usage: Scaling options.
static const IncrementalityValues kDefaultIncrementality
void Reset()
Sets all parameters to their default value.
DoubleParam
Enumeration of parameters that take continuous values.
@ DUAL_TOLERANCE
Advanced usage: tolerance for dual feasibility of basic solutions.
@ PRIMAL_TOLERANCE
Advanced usage: tolerance for primal feasibility of basic solutions.
@ RELATIVE_MIP_GAP
Limit for relative MIP gap.
static const PresolveValues kDefaultPresolve
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
IntegerParam
Enumeration of parameters that take integer or categorical values.
@ LP_ALGORITHM
Algorithm to solve linear programs.
@ SCALING
Advanced usage: enable or disable matrix scaling.
@ PRESOLVE
Advanced usage: presolve mode.
@ INCREMENTALITY
Advanced usage: incrementality from one solve to the next.
PresolveValues
For each categorical parameter, enumeration of possible values.
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
MPSolverParameters()
The constructor sets all parameters to their default value.
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
The class for variables of a Mathematical Programming (MP) model.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
int branching_priority() const
Advanced usage: Certain MIP solvers (e.g.
void set_solution_value(double value)
void SetBranchingPriority(int priority)
void SetUB(double ub)
Sets the upper bound.
double ub() const
Returns the upper bound.
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
void set_reduced_cost(double reduced_cost)
bool integer() const
Returns the integrality requirement of the variable.
int index() const
Returns the index of the variable in the MPSolver::variables_.
double lb() const
Returns the lower bound.
const std::string & name() const
Returns the name of the variable.
void SetLB(double lb)
Sets the lower bound.
double solution_value() const
Returns the value of the variable in the current solution.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
SatParameters parameters
SharedResponseManager * response
const std::string name
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
absl::Status status
Definition: g_gurobi.cc:41
const int64_t offset_
Definition: interval.cc:2109
This file allows you to write natural code (like a mathematical equation) to model optimization probl...
MPSolver::OptimizationProblemType problem_type
ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
int index
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: macros.h:29
Definition: cleanup.h:22
Collection of objects used to extend the Constraint Solver library.
constexpr double kDefaultPrimalTolerance
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
bool AbslParseFlag(const absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
int64_t coefficient
IntVar *const objective_
Definition: search.cc:3068
const std::optional< Range > & range
Definition: statistics.cc:36