linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //
15 //
16 // A C++ wrapper that provides a simple and unified interface to
17 // several linear programming and mixed integer programming solvers:
18 // GLOP, GLPK, CLP, CBC, and SCIP. The wrapper can also be used in Java, C#,
19 // and Python via SWIG.
20 //
21 //
22 // -----------------------------------
23 //
24 // What is Linear Programming?
25 //
26 // In mathematics, linear programming (LP) is a technique for optimization of
27 // a linear objective function, subject to linear equality and linear
28 // inequality constraints. Informally, linear programming determines the way
29 // to achieve the best outcome (such as maximum profit or lowest cost) in a
30 // given mathematical model and given some list of requirements represented
31 // as linear equations.
32 //
33 // The most widely used technique for solving a linear program is the Simplex
34 // algorithm, devised by George Dantzig in 1947. It performs very well on
35 // most instances, for which its running time is polynomial. A lot of effort
36 // has been put into improving the algorithm and its implementation. As a
37 // byproduct, it has however been shown that one can always construct
38 // problems that take exponential time for the Simplex algorithm to solve.
39 // Research has thus focused on trying to find a polynomial algorithm for
40 // linear programming, or to prove that linear programming is indeed
41 // polynomial.
42 //
43 // Leonid Khachiyan first exhibited in 1979 a weakly polynomial algorithm for
44 // linear programming. "Weakly polynomial" means that the running time of the
45 // algorithm is in O(P(n) * 2^p) where P(n) is a polynomial of the size of the
46 // problem, and p is the precision of computations expressed in number of
47 // bits. With a fixed-precision, floating-point-based implementation, a weakly
48 // polynomial algorithm will thus run in polynomial time. No implementation
49 // of Khachiyan's algorithm has proved efficient, but a larger breakthrough in
50 // the field came in 1984 when Narendra Karmarkar introduced a new interior
51 // point method for solving linear programming problems. Interior point
52 // algorithms have proved efficient on very large linear programs.
53 //
54 // Check Wikipedia for more detail:
55 // http://en.wikipedia.org/wiki/Linear_programming
56 //
57 // -----------------------------------
58 //
59 // Example of a Linear Program
60 //
61 // maximize:
62 // 3x + y
63 // subject to:
64 // 1.5 x + 2 y <= 12
65 // 0 <= x <= 3
66 // 0 <= y <= 5
67 //
68 // A linear program has:
69 // 1) a linear objective function
70 // 2) linear constraints that can be equalities or inequalities
71 // 3) bounds on variables that can be positive, negative, finite or
72 // infinite.
73 //
74 // -----------------------------------
75 //
76 // What is Mixed Integer Programming?
77 //
78 // Here, the constraints and the objective are still linear but
79 // there are additional integrality requirements for variables. If
80 // all variables are required to take integer values, then the
81 // problem is called an integer program (IP). In most cases, only
82 // some variables are required to be integer and the rest of the
83 // variables are continuous: this is called a mixed integer program
84 // (MIP). IPs and MIPs are generally NP-hard.
85 //
86 // Integer variables can be used to model discrete decisions (build a
87 // datacenter in city A or city B), logical relationships (only
88 // place machines in datacenter A if we have decided to build
89 // datacenter A) and approximate non-linear functions with piecewise
90 // linear functions (for example, the cost of machines as a function
91 // of how many machines are bought, or the latency of a server as a
92 // function of its load).
93 //
94 // -----------------------------------
95 //
96 // How to use the wrapper
97 //
98 // The user builds the model and solves it through the MPSolver class,
99 // then queries the solution through the MPSolver, MPVariable and
100 // MPConstraint classes. To be able to query a solution, you need the
101 // following:
102 // - A solution exists: MPSolver::Solve has been called and a solution
103 // has been found.
104 // - The model has not been modified since the last time
105 // MPSolver::Solve was called. Otherwise, the solution obtained
106 // before the model modification may not longer be feasible or
107 // optimal.
108 //
109 // @see ../examples/linear_programming.cc for a simple LP example.
110 //
111 // @see ../examples/integer_programming.cc for a simple MIP example.
112 //
113 // All methods cannot be called successfully in all cases. For
114 // example: you cannot query a solution when no solution exists, you
115 // cannot query a reduced cost value (which makes sense only on
116 // continuous problems) on a discrete problem. When a method is
117 // called in an unsuitable context, it aborts with a
118 // LOG(FATAL).
119 // TODO(user): handle failures gracefully.
120 //
121 // -----------------------------------
122 //
123 // For developers: How the wrapper works
124 //
125 // MPSolver stores a representation of the model (variables,
126 // constraints and objective) in its own data structures and a
127 // pointer to a MPSolverInterface that wraps the underlying solver
128 // (GLOP, CBC, CLP, GLPK, or SCIP) that does the actual work. The
129 // underlying solver also keeps a representation of the model in its
130 // own data structures. The model representations in MPSolver and in
131 // the underlying solver are kept in sync by the 'extraction'
132 // mechanism: synchronously for some changes and asynchronously
133 // (when MPSolver::Solve is called) for others. Synchronicity
134 // depends on the modification applied and on the underlying solver.
135 
136 #ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
137 #define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
138 
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/strings/match.h"
149 #include "absl/strings/str_format.h"
150 #include "absl/types/optional.h"
151 #include "ortools/base/commandlineflags.h"
152 #include "ortools/base/integral_types.h"
153 #include "ortools/base/logging.h"
154 #include "ortools/base/macros.h"
155 #include "ortools/base/status.h"
156 #include "ortools/base/timer.h"
157 #include "ortools/glop/parameters.pb.h"
158 #include "ortools/linear_solver/linear_expr.h"
160 #include "ortools/port/proto_utils.h"
161 
162 namespace operations_research {
163 
164 constexpr double kDefaultPrimalTolerance = 1e-07;
165 
166 class MPConstraint;
167 class MPObjective;
168 class MPSolverInterface;
169 class MPSolverParameters;
170 class MPVariable;
171 
172 // This mathematical programming (MP) solver class is the main class
173 // though which users build and solve problems.
174 class MPSolver {
175  public:
176  // The type of problems (LP or MIP) that will be solved and the
177  // underlying solver (GLOP, GLPK, CLP, CBC or SCIP) that will solve them.
178  // This must remain consistent with MPModelRequest::OptimizationProblemType
179  // (take particular care of the open-source version).
180  enum OptimizationProblemType {
181 // Linear programming problems.
182 #ifdef USE_CLP
183  CLP_LINEAR_PROGRAMMING = 0, // Recommended default value.
184 #endif
185 #ifdef USE_GLPK
186  GLPK_LINEAR_PROGRAMMING = 1,
187 #endif
188 #ifdef USE_GLOP
189  GLOP_LINEAR_PROGRAMMING = 2,
190 #endif
191 #ifdef USE_GUROBI
192  GUROBI_LINEAR_PROGRAMMING = 6,
193 #endif
194 #ifdef USE_CPLEX
195  CPLEX_LINEAR_PROGRAMMING = 10,
196 #endif
197 
198 // Integer programming problems.
199 #ifdef USE_SCIP
200  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
201 #endif
202 #ifdef USE_GLPK
203  GLPK_MIXED_INTEGER_PROGRAMMING = 4,
204 #endif
205 #ifdef USE_CBC
206  CBC_MIXED_INTEGER_PROGRAMMING = 5,
207 #endif
208 #if defined(USE_GUROBI)
209  GUROBI_MIXED_INTEGER_PROGRAMMING = 7,
210 #endif
211 #if defined(USE_CPLEX)
212  CPLEX_MIXED_INTEGER_PROGRAMMING = 11,
213 #endif
214 #if defined(USE_BOP)
215  BOP_INTEGER_PROGRAMMING = 12,
216 #endif
217  };
218 
219  MPSolver(const std::string& name, OptimizationProblemType problem_type);
220  virtual ~MPSolver();
221 
222  // Whether the given problem type is supported (this will depend on the
223  // targets that you linked).
224  static bool SupportsProblemType(OptimizationProblemType problem_type);
225 
226  // Parses the name of the solver. Returns true if the solver type is
227  // successfully parsed as one of the OptimizationProblemType.
228  static bool ParseSolverType(absl::string_view solver,
229  OptimizationProblemType* type);
230 
231  bool IsMIP() const;
232 
233  const std::string& Name() const {
234  return name_; // Set at construction.
235  }
236 
237  virtual OptimizationProblemType ProblemType() const {
238  return problem_type_; // Set at construction.
239  }
240 
241  // Clears the objective (including the optimization direction), all
242  // variables and constraints. All the other properties of the MPSolver
243  // (like the time limit) are kept untouched.
244  void Clear();
245 
246  // ----- Variables ------
247  // Returns the number of variables.
248  int NumVariables() const { return variables_.size(); }
249  // Returns the array of variables handled by the MPSolver.
250  // (They are listed in the order in which they were created.)
251  const std::vector<MPVariable*>& variables() const { return variables_; }
252  // Looks up a variable by name, and returns nullptr if it does not exist.
253  // The first call has a O(n) complexity, as the variable name index is lazily
254  // created upon first use. Will crash if variable names are not unique.
255  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
256 
257  // Creates a variable with the given bounds, integrality requirement
258  // and name. Bounds can be finite or +/- MPSolver::infinity().
259  // The MPSolver owns the variable (i.e. the returned pointer is borrowed).
260  // Variable names are optional. If you give an empty name, name() will
261  // auto-generate one for you upon request.
262 
263  MPVariable* MakeVar(double lb, double ub, bool integer,
264  const std::string& name);
265  // Creates a continuous variable.
266  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
267  // Creates an integer variable.
268  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
269  // Creates a boolean variable.
270  MPVariable* MakeBoolVar(const std::string& name);
271 
272  // Creates an array of variables. All variables created have the
273  // same bounds and integrality requirement. If nb <= 0, no variables are
274  // created, the function crashes in non-opt mode.
275  // @param name the prefix of the variable names. Variables are named
276  // name0, name1, ...
277  void MakeVarArray(int nb, double lb, double ub, bool integer,
278  const std::string& name_prefix,
279  std::vector<MPVariable*>* vars);
280  // Creates an array of continuous variables.
281  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
282  std::vector<MPVariable*>* vars);
283  // Creates an array of integer variables.
284  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
285  std::vector<MPVariable*>* vars);
286  // Creates an array of boolean variables.
287  void MakeBoolVarArray(int nb, const std::string& name,
288  std::vector<MPVariable*>* vars);
289 
290  // ----- Constraints -----
291  // Returns the number of constraints.
292  int NumConstraints() const { return constraints_.size(); }
293  // Returns the array of constraints handled by the MPSolver.
294  // (They are listed in the order in which they were created.)
295  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
296 
297  // Looks up a constraint by name, and returns nullptr if it does not exist.
298  // The first call has a O(n) complexity, as the constraint name index is
299  // lazily created upon first use. Will crash if constraint names are not
300  // unique.
301  MPConstraint* LookupConstraintOrNull(
302  const std::string& constraint_name) const;
303 
304  // Creates a linear constraint with given bounds. Bounds can be
305  // finite or +/- MPSolver::infinity(). The MPSolver class assumes
306  // ownership of the constraint.
307  // @return a pointer to the newly created constraint.
308  MPConstraint* MakeRowConstraint(double lb, double ub);
309  // Creates a constraint with -infinity and +infinity bounds.
310  MPConstraint* MakeRowConstraint();
311  // Creates a named constraint with given bounds.
312  MPConstraint* MakeRowConstraint(double lb, double ub,
313  const std::string& name);
314  // Creates a named constraint with -infinity and +infinity bounds.
315  MPConstraint* MakeRowConstraint(const std::string& name);
316 
317  // Creates a constraint owned by MPSolver enforcing:
318  // range.lower_bound() <= range.linear_expr() <= range.upper_bound()
319  MPConstraint* MakeRowConstraint(const LinearRange& range);
320  // As above, but also names the constraint.
321  MPConstraint* MakeRowConstraint(const LinearRange& range,
322  const std::string& name);
323 
324  // ----- Objective -----
325  // Note that the objective is owned by the solver, and is initialized to
326  // its default value (see the MPObjective class below) at construction.
327  const MPObjective& Objective() const { return *objective_; }
328  MPObjective* MutableObjective() { return objective_.get(); }
329 
330  // ----- Solve -----
331 
332  // The status of solving the problem. The straightforward translation to
333  // homonymous enum values of MPSolverResponseStatus
334  // (see ./linear_solver.proto) is guaranteed by ./enum_consistency_test.cc,
335  // you may rely on it.
336  enum ResultStatus {
337  OPTIMAL, // optimal.
338  FEASIBLE, // feasible, or stopped by limit.
339  INFEASIBLE, // proven infeasible.
340  UNBOUNDED, // proven unbounded.
341  ABNORMAL, // abnormal, i.e., error of some kind.
342  MODEL_INVALID, // the model is trivially invalid (NaN coefficients, etc).
343  NOT_SOLVED = 6 // not been solved yet.
344  };
345 
346  // Solves the problem using default parameter values.
347  ResultStatus Solve();
348  // Solves the problem using the specified parameter values.
349  ResultStatus Solve(const MPSolverParameters& param);
350 
351  // Writes the model using the solver internal write function. Currently only
352  // available for Gurobi.
353  void Write(const std::string& file_name);
354 
355  // Advanced usage: compute the "activities" of all constraints, which are the
356  // sums of their linear terms. The activities are returned in the same order
357  // as constraints(), which is the order in which constraints were added; but
358  // you can also use MPConstraint::index() to get a constraint's index.
359  std::vector<double> ComputeConstraintActivities() const;
360 
361  // Advanced usage:
362  // Verifies the *correctness* of the solution: all variables must be within
363  // their domains, all constraints must be satisfied, and the reported
364  // objective value must be accurate.
365  // Usage:
366  // - This can only be called after Solve() was called.
367  // - "tolerance" is interpreted as an absolute error threshold.
368  // - For the objective value only, if the absolute error is too large,
369  // the tolerance is interpreted as a relative error threshold instead.
370  // - If "log_errors" is true, every single violation will be logged.
371  // - If "tolerance" is negative, it will be set to infinity().
372  //
373  // Most users should just set the --verify_solution flag and not bother
374  // using this method directly.
375  bool VerifySolution(double tolerance, bool log_errors) const;
376 
377  // Advanced usage: resets extracted model to solve from scratch. This won't
378  // reset the parameters that were set with
379  // SetSolverSpecificParametersAsString() or set_time_limit() or even clear the
380  // linear program. It will just make sure that next Solve() will be as if
381  // everything was reconstructed from scratch.
382  void Reset();
383 
384  // Interrupts the Solve() execution to terminate processing early if possible.
385  // If the underlying interface supports interruption; it does that and returns
386  // true regardless of whether there's an ongoing Solve() or not. The Solve()
387  // call may still linger for a while depending on the conditions. If
388  // interruption is not supported; returns false and does nothing.
389  bool InterruptSolve();
390 
391  // ----- Methods using protocol buffers -----
392 
393  // Loads model from protocol buffer. Returns MPSOLVER_MODEL_IS_VALID if the
394  // model is valid, and another status otherwise (currently only
395  // MPSOLVER_MODEL_INVALID and MPSOLVER_INFEASIBLE). If the model isn't
396  // valid, populates "error_message".
397  MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
398  std::string* error_message);
399  // The same as above, except that the loading keeps original variable and
400  // constraint names. Caller should make sure that all variable names and
401  // constraint names are unique, respectively.
402  MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(
403  const MPModelProto& input_model, std::string* error_message);
404 
405  // Encodes the current solution in a solution response protocol buffer.
406 
407  void FillSolutionResponseProto(MPSolutionResponse* response) const;
408 
409  // Solves the model encoded by a MPModelRequest protocol buffer and
410  // fills the solution encoded as a MPSolutionResponse.
411  // Note(user): This creates a temporary MPSolver and destroys it at the
412  // end. If you want to keep the MPSolver alive (for debugging, or for
413  // incremental solving), you should write another version of this function
414  // that creates the MPSolver object on the heap and returns it.
415  //
416  // TODO(user): populate an error message in the response.
417  static void SolveWithProto(const MPModelRequest& model_request,
418  MPSolutionResponse* response);
419 
420  // Exports model to protocol buffer.
421  void ExportModelToProto(MPModelProto* output_model) const;
422 
423  // Load a solution encoded in a protocol buffer onto this solver for easy
424  // access via the MPSolver interface.
425  //
426  // IMPORTANT: This may only be used in conjunction with ExportModel(),
427  // following this example:
428  // MPSolver my_solver;
429  // ... add variables and constraints ...
430  // MPModelProto model_proto;
431  // my_solver.ExportModelToProto(&model_proto);
432  // MPSolutionResponse solver_response;
433  // // This can be replaced by a stubby call to the linear solver server.
434  // MPSolver::SolveWithProto(model_proto, &solver_response);
435  // if (solver_response.result_status() == MPSolutionResponse::OPTIMAL) {
436  // CHECK_OK(my_solver.LoadSolutionFromProto(solver_response));
437  // ... inspect the solution using the usual API: solution_value(), etc...
438  // }
439  //
440  // This allows users of the pythonic API to conveniently communicate with
441  // a linear solver stubby server, via the MPSolver object as a proxy.
442  // See /.linear_solver_server_integration_test.py.
443  //
444  // The response must be in OPTIMAL or FEASIBLE status.
445  // Returns a non-OK status if a problem arised (typically, if it wasn't used
446  // like it should be):
447  // - loading a solution whose variables don't correspond to the solver's
448  // current variables
449  // - loading a solution with a status other than OPTIMAL / FEASIBLE.
450  // Note: the objective value isnn't checked. You can use VerifySolution()
451  // for that.
452  // TODO(b/116117536) split this into two separate functions: Load...() without
453  // checking for tolerance and SolutionIsFeasibleWithTolerance().
454  util::Status LoadSolutionFromProto(
455  const MPSolutionResponse& response,
456  double tolerance = kDefaultPrimalTolerance);
457 
458  // Resets values of out of bound variables to the corresponding bound
459  // and returns an error if any of the variables have NaN value.
460  util::Status ClampSolutionWithinBounds();
461 
462  // ----- Export model to files or strings -----
463  // Shortcuts to the homonymous MPModelProtoExporter methods, via
464  // exporting to a MPModelProto with ExportModelToProto() (see above).
465  //
466  // Produces empty std::string on portable platforms (e.g. android, ios).
467  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
468  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
469  std::string* model_str) const;
470  // ----- Misc -----
471 
472  // Sets the number of threads to use by the underlying solver. Returns
473  // OkStatus if the operation was successful. num_threads must be equal
474  // to or greater than 1. Note that the behaviour of this call depends on
475  // the underlying solver. E.g., it may set the exact number of threads or
476  // the max number of threads (check the solver's interface implementation
477  // for details). Also, some solvers may not (yet) support this function,
478  // but still enable multi-threading via SetSolverSpecificParametersAsString().
479  util::Status SetNumThreads(int num_threads);
480  int GetNumThreads() const { return num_threads_; }
481 
482  // Advanced usage: pass solver specific parameters in text format. The format
483  // is solver-specific and is the same as the corresponding solver
484  // configuration file format. Returns true if the operation was successful.
485  //
486  // TODO(user): Currently SCIP will always return true even if the format is
487  // wrong (you can check the log if you suspect an issue there). This seems to
488  // be a bug in SCIP though.
489  bool SetSolverSpecificParametersAsString(const std::string& parameters);
490  std::string GetSolverSpecificParametersAsString() const {
491  return solver_specific_parameter_string_;
492  }
493 
494  // Set a hint for solution.
495  //
496  // If a feasible or almost-feasible solution to the problem is already known,
497  // it may be helpful to pass it to the solver so that it can be used. A solver
498  // that supports this feature will try to use this information to create its
499  // initial feasible solution.
500  //
501  // Note that it may not always be faster to give a hint like this to the
502  // solver. There is also no guarantee that the solver will use this hint or
503  // try to return a solution "close" to this assignment in case of multiple
504  // optimal solutions.
505  //
506  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
507 
508  // Advanced usage: possible basis status values for a variable and the
509  // slack variable of a linear constraint.
510  enum BasisStatus {
511  FREE = 0,
512  AT_LOWER_BOUND,
513  AT_UPPER_BOUND,
514  FIXED_VALUE,
515  BASIC
516  };
517 
518  // Advanced usage: Incrementality. This function takes a starting basis to be
519  // used in the next LP Solve() call. The statuses of a current solution can be
520  // retrieved via the basis_status() function of a MPVariable or a
521  // MPConstraint.
522  //
523  // WARNING: With Glop, you should disable presolve when using this because
524  // this information will not be modified in sync with the presolve and will
525  // likely not mean much on the presolved problem.
526  void SetStartingLpBasis(
527  const std::vector<MPSolver::BasisStatus>& variable_statuses,
528  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
529 
530  // Infinity. You can use -MPSolver::infinity() for negative infinity.
531  static double infinity() { return std::numeric_limits<double>::infinity(); }
532 
533  // Controls (or queries) the amount of output produced by the underlying
534  // solver. The output can surface to LOGs, or to stdout or stderr, depending
535  // on the implementation. The amount of output will greatly vary with each
536  // implementation and each problem.
537  //
538  // Output is suppressed by default.
539  bool OutputIsEnabled() const;
540  void EnableOutput();
541  void SuppressOutput();
542 
543  absl::Duration TimeLimit() const { return time_limit_; }
544  void SetTimeLimit(absl::Duration time_limit) {
545  DCHECK_GE(time_limit, absl::ZeroDuration());
546  time_limit_ = time_limit;
547  }
548 
549  absl::Duration DurationSinceConstruction() const {
550  return absl::Now() - construction_time_;
551  }
552 
553  // Returns the number of simplex iterations.
554  int64 iterations() const;
555 
556  // Returns the number of branch-and-bound nodes evaluated during the solve.
557  // Only available for discrete problems.
558  int64 nodes() const;
559 
560  // Returns a std::string describing the underlying solver and its version.
561  std::string SolverVersion() const;
562 
563  // Advanced usage: returns the underlying solver so that the user
564  // can use solver-specific features or features that are not exposed
565  // in the simple API of MPSolver. This method is for advanced users,
566  // use at your own risk! In particular, if you modify the model or
567  // the solution by accessing the underlying solver directly, then
568  // the underlying solver will be out of sync with the information
569  // kept in the wrapper (MPSolver, MPVariable, MPConstraint,
570  // MPObjective). You need to cast the void* returned back to its
571  // original type that depends on the interface (CBC:
572  // OsiClpSolverInterface*, CLP: ClpSimplex*, GLPK: glp_prob*, SCIP:
573  // SCIP*).
574  void* underlying_solver();
575 
576  // Advanced usage: computes the exact condition number of the
577  // current scaled basis: L1norm(B) * L1norm(inverse(B)), where B is
578  // the scaled basis.
579  // This method requires that a basis exists: it should be called
580  // after Solve. It is only available for continuous problems. It is
581  // implemented for GLPK but not CLP because CLP does not provide the
582  // API for doing it.
583  // The condition number measures how well the constraint matrix is
584  // conditioned and can be used to predict whether numerical issues
585  // will arise during the solve: the model is declared infeasible
586  // whereas it is feasible (or vice-versa), the solution obtained is
587  // not optimal or violates some constraints, the resolution is slow
588  // because of repeated singularities.
589  // The rule of thumb to interpret the condition number kappa is:
590  // o kappa <= 1e7: virtually no chance of numerical issues
591  // o 1e7 < kappa <= 1e10: small chance of numerical issues
592  // o 1e10 < kappa <= 1e13: medium chance of numerical issues
593  // o kappa > 1e13: high chance of numerical issues
594  // The computation of the condition number depends on the quality of
595  // the LU decomposition, so it is not very accurate when the matrix
596  // is ill conditioned.
597  double ComputeExactConditionNumber() const;
598 
599  // Some solvers (MIP only, not LP) can produce multiple solutions to the
600  // problem. Returns true when another solution is available, and updates the
601  // MPVariable* objects to make the new solution queryable. Call only after
602  // calling solve.
603  //
604  // The optimality properties of the additional solutions found, and whether
605  // or not the solver computes them ahead of time or when NextSolution() is
606  // called is solver specific.
607  //
608  // As of 2018-08-09, only Gurobi supports NextSolution(), see
609  // linear_solver_underlying_gurobi_test for an example of how to configure
610  // Gurobi for this purpose. The other solvers return false unconditionally.
611  ABSL_MUST_USE_RESULT bool NextSolution();
612 
613  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
614  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
615  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
616  int64 time_limit() const {
617  return time_limit_ == absl::InfiniteDuration()
618  ? 0
619  : absl::ToInt64Milliseconds(time_limit_);
620  }
621  void set_time_limit(int64 time_limit_milliseconds) {
622  SetTimeLimit(time_limit_milliseconds == 0
623  ? absl::InfiniteDuration()
624  : absl::Milliseconds(time_limit_milliseconds));
625  }
626  double time_limit_in_secs() const {
627  return static_cast<double>(time_limit()) / 1000.0;
628  }
629 
630  // DEPRECATED: Use DurationSinceConstruction() instead.
631  int64 wall_time() const {
632  return absl::ToInt64Milliseconds(DurationSinceConstruction());
633  }
634 
635  friend class GLPKInterface;
636  friend class CLPInterface;
637  friend class CBCInterface;
638  friend class SCIPInterface;
639  friend class GurobiInterface;
640  friend class CplexInterface;
641  friend class SLMInterface;
642  friend class MPSolverInterface;
643  friend class GLOPInterface;
644  friend class BopInterface;
645  friend class SatInterface;
646  friend class KnapsackInterface;
647 
648  // Debugging: verify that the given MPVariable* belongs to this solver.
649  bool OwnsVariable(const MPVariable* var) const;
650 
651  private:
652  // Computes the size of the constraint with the largest number of
653  // coefficients with index in [min_constraint_index,
654  // max_constraint_index)
655  int ComputeMaxConstraintSize(int min_constraint_index,
656  int max_constraint_index) const;
657 
658  // Returns true if the model has constraints with lower bound > upper bound.
659  bool HasInfeasibleConstraints() const;
660 
661  // Returns true if the model has at least 1 integer variable.
662  bool HasIntegerVariables() const;
663 
664  // Generates the map from variable names to their indices.
665  void GenerateVariableNameIndex() const;
666 
667  // Generates the map from constraint names to their indices.
668  void GenerateConstraintNameIndex() const;
669 
670  // The name of the linear programming problem.
671  const std::string name_;
672 
673  // The type of the linear programming problem.
674  const OptimizationProblemType problem_type_;
675 
676  // The solver interface.
677  std::unique_ptr<MPSolverInterface> interface_;
678 
679  // The vector of variables in the problem.
680  std::vector<MPVariable*> variables_;
681  // A map from a variable's name to its index in variables_.
682  mutable absl::optional<absl::flat_hash_map<std::string, int> >
683  variable_name_to_index_;
684  // Whether variables have been extracted to the underlying interface.
685  std::vector<bool> variable_is_extracted_;
686 
687  // The vector of constraints in the problem.
688  std::vector<MPConstraint*> constraints_;
689  // A map from a constraint's name to its index in constraints_.
690  mutable absl::optional<absl::flat_hash_map<std::string, int> >
691  constraint_name_to_index_;
692  // Whether constraints have been extracted to the underlying interface.
693  std::vector<bool> constraint_is_extracted_;
694 
695  // The linear objective function.
696  std::unique_ptr<MPObjective> objective_;
697 
698  // Initial values for all or some of the problem variables that can be
699  // exploited as a starting hint by a solver.
700  //
701  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
702  //
703  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
704  // hint is provided and a std::vector<double> for the hint value.
705  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
706 
707  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
708 
709  const absl::Time construction_time_;
710 
711  // Permanent storage for the number of threads.
712  int num_threads_ = 1;
713 
714  // Permanent storage for SetSolverSpecificParametersAsString().
715  std::string solver_specific_parameter_string_;
716 
717  MPSolverResponseStatus LoadModelFromProtoInternal(
718  const MPModelProto& input_model, bool clear_names,
719  std::string* error_message);
720 
721  DISALLOW_COPY_AND_ASSIGN(MPSolver);
722 };
723 
724 const absl::string_view ToString(
725  MPSolver::OptimizationProblemType optimization_problem_type);
726 
727 inline std::ostream& operator<<(
728  std::ostream& os,
729  MPSolver::OptimizationProblemType optimization_problem_type) {
730  return os << ToString(optimization_problem_type);
731 }
732 
733 inline std::ostream& operator<<(std::ostream& os,
734  MPSolver::ResultStatus status) {
735  return os << ProtoEnumToString<MPSolverResponseStatus>(
736  static_cast<MPSolverResponseStatus>(status));
737 }
738 
739 bool AbslParseFlag(absl::string_view text,
740  MPSolver::OptimizationProblemType* solver_type,
741  std::string* error);
742 
743 inline std::string AbslUnparseFlag(
744  MPSolver::OptimizationProblemType solver_type) {
745  return std::string(ToString(solver_type));
746 }
747 
748 // A class to express a linear objective.
749 class MPObjective {
750  public:
751  // Clears the offset, all variables and coefficients, and the optimization
752  // direction.
753  void Clear();
754 
755  // Sets the coefficient of the variable in the objective. If the variable
756  // does not belong to the solver, the function just returns, or crashes in
757  // non-opt mode.
758  void SetCoefficient(const MPVariable* const var, double coeff);
759  // Gets the coefficient of a given variable in the objective (which
760  // is 0 if the variable does not appear in the objective).
761  double GetCoefficient(const MPVariable* const var) const;
762 
763  // Returns a map from variables to their coefficients in the objective. If a
764  // variable is not present in the map, then its coefficient is zero.
765  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
766  return coefficients_;
767  }
768 
769  // Sets the constant term in the objective.
770  void SetOffset(double value);
771  // Gets the constant term in the objective.
772  double offset() const { return offset_; }
773 
774  // Resets the current objective to take the value of linear_expr, and sets
775  // the objective direction to maximize if "is_maximize", otherwise minimizes.
776  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
777  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
778  OptimizeLinearExpr(linear_expr, true);
779  }
780  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
781  OptimizeLinearExpr(linear_expr, false);
782  }
783 
784  // Adds linear_expr to the current objective, does not change the direction.
785  void AddLinearExpr(const LinearExpr& linear_expr);
786 
787  // Sets the optimization direction (maximize: true or minimize: false).
788  void SetOptimizationDirection(bool maximize);
789  // Sets the optimization direction to minimize.
790  void SetMinimization() { SetOptimizationDirection(false); }
791  // Sets the optimization direction to maximize.
792  void SetMaximization() { SetOptimizationDirection(true); }
793  // Is the optimization direction set to maximize?
794  bool maximization() const;
795  // Is the optimization direction set to minimize?
796  bool minimization() const;
797 
798  // Returns the objective value of the best solution found so far. It
799  // is the optimal objective value if the problem has been solved to
800  // optimality.
801  //
802  // Note: the objective value may be slightly different than what you
803  // could compute yourself using MPVariable::solution_value();
804  // please use the --verify_solution flag to gain confidence about the
805  // numerical stability of your solution.
806  double Value() const;
807 
808  // Returns the best objective bound. In case of minimization, it is
809  // a lower bound on the objective value of the optimal integer
810  // solution. Only available for discrete problems.
811  double BestBound() const;
812 
813  private:
814  friend class MPSolver;
815  friend class MPSolverInterface;
816  friend class CBCInterface;
817  friend class CLPInterface;
818  friend class GLPKInterface;
819  friend class SCIPInterface;
820  friend class SLMInterface;
821  friend class GurobiInterface;
822  friend class CplexInterface;
823  friend class GLOPInterface;
824  friend class BopInterface;
825  friend class SatInterface;
826  friend class KnapsackInterface;
827 
828  // Constructor. An objective points to a single MPSolverInterface
829  // that is specified in the constructor. An objective cannot belong
830  // to several models.
831  // At construction, an MPObjective has no terms (which is equivalent
832  // on having a coefficient of 0 for all variables), and an offset of 0.
833  explicit MPObjective(MPSolverInterface* const interface_in)
834  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
835 
836  MPSolverInterface* const interface_;
837 
838  // Mapping var -> coefficient.
839  absl::flat_hash_map<const MPVariable*, double> coefficients_;
840  // Constant term.
841  double offset_;
842 
843  DISALLOW_COPY_AND_ASSIGN(MPObjective);
844 };
845 
846 // The class for variables of a Mathematical Programming (MP) model.
847 class MPVariable {
848  public:
849  // Returns the name of the variable.
850  const std::string& name() const { return name_; }
851 
852  // Sets the integrality requirement of the variable.
853  void SetInteger(bool integer);
854  // Returns the integrality requirement of the variable.
855  bool integer() const { return integer_; }
856 
857  // Returns the value of the variable in the current solution.
858  // If the variable is integer, then the value will always be an integer
859  // (the underlying solver handles floating-point values only, but this
860  // function automatically rounds it to the nearest integer; see: man 3 round).
861  double solution_value() const;
862 
863  // Returns the index of the variable in the MPSolver::variables_.
864  int index() const { return index_; }
865 
866  // Returns the lower bound.
867  double lb() const { return lb_; }
868  // Returns the upper bound.
869  double ub() const { return ub_; }
870  // Sets the lower bound.
871  void SetLB(double lb) { SetBounds(lb, ub_); }
872  // Sets the upper bound.
873  void SetUB(double ub) { SetBounds(lb_, ub); }
874  // Sets both the lower and upper bounds.
875  void SetBounds(double lb, double ub);
876 
877  // Advanced usage: unrounded solution value, i.e. it won't be rounded to the
878  // nearest integer even if the variable is integer.
879  double unrounded_solution_value() const;
880  // Advanced usage: returns the reduced cost of the variable in the
881  // current solution (only available for continuous problems).
882  double reduced_cost() const;
883  // Advanced usage: returns the basis status of the variable in the
884  // current solution (only available for continuous problems).
885  // @see MPSolver::BasisStatus.
886  MPSolver::BasisStatus basis_status() const;
887 
888  // Advanced usage: Certain MIP solvers (e.g. Gurobi or SCIP) allow you to set
889  // a per-variable priority for determining which variable to branch on. A
890  // value of 0 is treated as default, and is equivalent to not setting the
891  // branching priority. The solver looks first to branch on fractional
892  // variables in higher priority levels. As of 2019-05, only Gurobi and SCIP
893  // support setting branching priority; all other solvers will simply ignore
894  // this annotation.
895  int branching_priority() const { return branching_priority_; }
896  void SetBranchingPriority(int priority);
897 
898  protected:
899  friend class MPSolver;
900  friend class MPSolverInterface;
901  friend class CBCInterface;
902  friend class CLPInterface;
903  friend class GLPKInterface;
904  friend class SCIPInterface;
905  friend class SLMInterface;
906  friend class GurobiInterface;
907  friend class CplexInterface;
908  friend class GLOPInterface;
909  friend class MPVariableSolutionValueTest;
910  friend class BopInterface;
911  friend class SatInterface;
912  friend class KnapsackInterface;
913 
914  // Constructor. A variable points to a single MPSolverInterface that
915  // is specified in the constructor. A variable cannot belong to
916  // several models.
917  MPVariable(int index, double lb, double ub, bool integer,
918  const std::string& name, MPSolverInterface* const interface_in)
919  : index_(index),
920  lb_(lb),
921  ub_(ub),
922  integer_(integer),
923  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
924  solution_value_(0.0),
925  reduced_cost_(0.0),
926  interface_(interface_in) {}
927 
928  void set_solution_value(double value) { solution_value_ = value; }
929  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
930 
931  private:
932  const int index_;
933  double lb_;
934  double ub_;
935  bool integer_;
936  const std::string name_;
937  double solution_value_;
938  double reduced_cost_;
939  int branching_priority_ = 0;
940  MPSolverInterface* const interface_;
941  DISALLOW_COPY_AND_ASSIGN(MPVariable);
942 };
943 
944 // The class for constraints of a Mathematical Programming (MP) model.
945 // A constraint is represented as a linear equation or inequality.
946 class MPConstraint {
947  public:
948  // Returns the name of the constraint.
949  const std::string& name() const { return name_; }
950 
951  // Clears all variables and coefficients. Does not clear the bounds.
952  void Clear();
953 
954  // Sets the coefficient of the variable on the constraint. If the variable
955  // does not belong to the solver, the function just returns, or crashes in
956  // non-opt mode.
957  void SetCoefficient(const MPVariable* const var, double coeff);
958  // Gets the coefficient of a given variable on the constraint (which
959  // is 0 if the variable does not appear in the constraint).
960  double GetCoefficient(const MPVariable* const var) const;
961 
962  // Returns a map from variables to their coefficients in the constraint. If a
963  // variable is not present in the map, then its coefficient is zero.
964  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
965  return coefficients_;
966  }
967 
968  // Returns the lower bound.
969  double lb() const { return lb_; }
970  // Returns the upper bound.
971  double ub() const { return ub_; }
972  // Sets the lower bound.
973  void SetLB(double lb) { SetBounds(lb, ub_); }
974  // Sets the upper bound.
975  void SetUB(double ub) { SetBounds(lb_, ub); }
976  // Sets both the lower and upper bounds.
977  void SetBounds(double lb, double ub);
978 
979  // Advanced usage: returns true if the constraint is "lazy" (see below).
980  bool is_lazy() const { return is_lazy_; }
981  // Advanced usage: sets the constraint "laziness".
982  // *** This is only supported for SCIP and has no effect on other solvers. ***
983  // When 'laziness' is true, the constraint is only considered by the Linear
984  // Programming solver if its current solution violates the constraint.
985  // In this case, the constraint is definitively added to the problem.
986  // This may be useful in some MIP problems, and may have a dramatic impact
987  // on performance.
988  // For more info see: http://tinyurl.com/lazy-constraints.
989  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
990 
991  const MPVariable* indicator_variable() const { return indicator_variable_; }
992  bool indicator_value() const { return indicator_value_; }
993 
994  // Returns the index of the constraint in the MPSolver::constraints_.
995  int index() const { return index_; }
996 
997  // Advanced usage: returns the dual value of the constraint in the
998  // current solution (only available for continuous problems).
999  double dual_value() const;
1000 
1001  // Advanced usage: returns the basis status of the constraint (only available
1002  // for continuous problems). Note that if a constraint "linear_expression in
1003  // [lb, ub]" is transformed into "linear_expression + slack = 0" with slack in
1004  // [-ub, -lb], then this status is the same as the status of the slack
1005  // variable with AT_UPPER_BOUND and AT_LOWER_BOUND swapped.
1006  //
1007  // @see MPSolver::BasisStatus.
1008  MPSolver::BasisStatus basis_status() const;
1009 
1010  protected:
1011  friend class MPSolver;
1012  friend class MPSolverInterface;
1013  friend class CBCInterface;
1014  friend class CLPInterface;
1015  friend class GLPKInterface;
1016  friend class SCIPInterface;
1017  friend class SLMInterface;
1018  friend class GurobiInterface;
1019  friend class CplexInterface;
1020  friend class GLOPInterface;
1021  friend class BopInterface;
1022  friend class SatInterface;
1023  friend class KnapsackInterface;
1024 
1025  // Constructor. A constraint points to a single MPSolverInterface
1026  // that is specified in the constructor. A constraint cannot belong
1027  // to several models.
1028  MPConstraint(int index, double lb, double ub, const std::string& name,
1029  MPSolverInterface* const interface_in)
1030  : coefficients_(1),
1031  index_(index),
1032  lb_(lb),
1033  ub_(ub),
1034  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1035  is_lazy_(false),
1036  indicator_variable_(nullptr),
1037  dual_value_(0.0),
1038  interface_(interface_in) {}
1039 
1040  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1041 
1042  private:
1043  // Returns true if the constraint contains variables that have not
1044  // been extracted yet.
1045  bool ContainsNewVariables();
1046 
1047  // Mapping var -> coefficient.
1048  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1049 
1050  const int index_; // See index().
1051 
1052  // The lower bound for the linear constraint.
1053  double lb_;
1054 
1055  // The upper bound for the linear constraint.
1056  double ub_;
1057 
1058  // Name.
1059  const std::string name_;
1060 
1061  // True if the constraint is "lazy", i.e. the constraint is added to the
1062  // underlying Linear Programming solver only if it is violated.
1063  // By default this parameter is 'false'.
1064  bool is_lazy_;
1065 
1066  // If given, this constraint is only active if `indicator_variable_`'s value
1067  // is equal to `indicator_value_`.
1068  const MPVariable* indicator_variable_;
1069  bool indicator_value_;
1070 
1071  double dual_value_;
1072  MPSolverInterface* const interface_;
1073  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1074 };
1075 
1076 // This class stores parameter settings for LP and MIP solvers.
1077 // Some parameters are marked as advanced: do not change their values
1078 // unless you know what you are doing!
1079 //
1080 // For developers: how to add a new parameter:
1081 // - Add the new Foo parameter in the DoubleParam or IntegerParam enum.
1082 // - If it is a categorical param, add a FooValues enum.
1083 // - Decide if the wrapper should define a default value for it: yes
1084 // if it controls the properties of the solution (example:
1085 // tolerances) or if it consistently improves performance, no
1086 // otherwise. If yes, define kDefaultFoo.
1087 // - Add a foo_value_ member and, if no default value is defined, a
1088 // foo_is_default_ member.
1089 // - Add code to handle Foo in Set...Param, Reset...Param,
1090 // Get...Param, Reset and the constructor.
1091 // - In class MPSolverInterface, add a virtual method SetFoo, add it
1092 // to SetCommonParameters or SetMIPParameters, and implement it for
1093 // each solver. Sometimes, parameters need to be implemented
1094 // differently, see for example the INCREMENTALITY implementation.
1095 // - Add a test in linear_solver_test.cc.
1096 //
1097 // TODO(user): store the parameter values in a protocol buffer
1098 // instead. We need to figure out how to deal with the subtleties of
1099 // the default values.
1100 class MPSolverParameters {
1101  public:
1102  // Enumeration of parameters that take continuous values.
1103  enum DoubleParam {
1104  // Limit for relative MIP gap.
1105  RELATIVE_MIP_GAP = 0,
1106  // Advanced usage: tolerance for primal feasibility of basic
1107  // solutions. This does not control the integer feasibility
1108  // tolerance of integer solutions for MIP or the tolerance used
1109  // during presolve.
1110  PRIMAL_TOLERANCE = 1,
1111  // Advanced usage: tolerance for dual feasibility of basic solutions.
1112  DUAL_TOLERANCE = 2
1113  };
1114 
1115  // Enumeration of parameters that take integer or categorical values.
1116  enum IntegerParam {
1117  // Advanced usage: presolve mode.
1118  PRESOLVE = 1000,
1119  // Algorithm to solve linear programs.
1120  LP_ALGORITHM = 1001,
1121  // Advanced usage: incrementality from one solve to the next.
1122  INCREMENTALITY = 1002,
1123  // Advanced usage: enable or disable matrix scaling.
1124  SCALING = 1003
1125  };
1126 
1127  // For each categorical parameter, enumeration of possible values.
1128  enum PresolveValues {
1129  PRESOLVE_OFF = 0, // Presolve is off.
1130  PRESOLVE_ON = 1 // Presolve is on.
1131  };
1132 
1133  enum LpAlgorithmValues {
1134  DUAL = 10, // Dual simplex.
1135  PRIMAL = 11, // Primal simplex.
1136  BARRIER = 12 // Barrier algorithm.
1137  };
1138 
1139  enum IncrementalityValues {
1140  // Start solve from scratch.
1141  INCREMENTALITY_OFF = 0,
1142  // Reuse results from previous solve as much as the underlying
1143  // solver allows.
1144  INCREMENTALITY_ON = 1
1145  };
1146 
1147  enum ScalingValues {
1148  SCALING_OFF = 0, // Scaling is off.
1149  SCALING_ON = 1 // Scaling is on.
1150  };
1151 
1152  // @{
1153  // Placeholder value to indicate that a parameter is set to
1154  // the default value defined in the wrapper.
1155  static const double kDefaultDoubleParamValue;
1156  static const int kDefaultIntegerParamValue;
1157  // @}
1158 
1159  // @{
1160  // Placeholder value to indicate that a parameter is unknown.
1161  static const double kUnknownDoubleParamValue;
1162  static const int kUnknownIntegerParamValue;
1163  // @}
1164 
1165  // @{
1166  // Default values for parameters. Only parameters that define the
1167  // properties of the solution returned need to have a default value
1168  // (that is the same for all solvers). You can also define a default
1169  // value for performance parameters when you are confident it is a
1170  // good choice (example: always turn presolve on).
1171  static const double kDefaultRelativeMipGap;
1172  static const double kDefaultPrimalTolerance;
1173  static const double kDefaultDualTolerance;
1174  static const PresolveValues kDefaultPresolve;
1175  static const IncrementalityValues kDefaultIncrementality;
1176  // @}
1177 
1178  // The constructor sets all parameters to their default value.
1179  MPSolverParameters();
1180 
1181  // @{
1182  // Sets a parameter to a specific value.
1183  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1184  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1185  // @}
1186 
1187  // @{
1188  // Sets a parameter to its default value (default value defined
1189  // in MPSolverParameters if it exists, otherwise the default value
1190  // defined in the underlying solver).
1191  void ResetDoubleParam(MPSolverParameters::DoubleParam param);
1192  void ResetIntegerParam(MPSolverParameters::IntegerParam param);
1193  // Sets all parameters to their default value.
1194  void Reset();
1195  // @}
1196 
1197  // @{
1198  // Returns the value of a parameter.
1199  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1200  int GetIntegerParam(MPSolverParameters::IntegerParam param) const;
1201  // @}
1202 
1203  private:
1204  // @{
1205  // Parameter value for each parameter.
1206  // @see DoubleParam
1207  // @see IntegerParam
1208  double relative_mip_gap_value_;
1209  double primal_tolerance_value_;
1210  double dual_tolerance_value_;
1211  int presolve_value_;
1212  int scaling_value_;
1213  int lp_algorithm_value_;
1214  int incrementality_value_;
1215  // @}
1216 
1217  // Boolean value indicating whether each parameter is set to the
1218  // solver's default value. Only parameters for which the wrapper
1219  // does not define a default value need such an indicator.
1220  bool lp_algorithm_is_default_;
1221 
1222  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1223 };
1224 
1225 // This class wraps the actual mathematical programming solvers. Each
1226 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1227 // derives from this abstract class. This class is never directly
1228 // accessed by the user.
1229 // @see glop_interface.cc
1230 // @see cbc_interface.cc
1231 // @see clp_interface.cc
1232 // @see glpk_interface.cc
1233 // @see scip_interface.cc
1234 class MPSolverInterface {
1235  public:
1236  enum SynchronizationStatus {
1237  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1238  // sync for the model nor for the solution.
1239  MUST_RELOAD,
1240  // The underlying solver and MPSolver are in sync for the model
1241  // but not for the solution: the model has changed since the
1242  // solution was computed last.
1243  MODEL_SYNCHRONIZED,
1244  // The underlying solver and MPSolver are in sync for the model and
1245  // the solution.
1246  SOLUTION_SYNCHRONIZED
1247  };
1248 
1249  // When the underlying solver does not provide the number of simplex
1250  // iterations.
1251  static const int64 kUnknownNumberOfIterations = -1;
1252  // When the underlying solver does not provide the number of
1253  // branch-and-bound nodes.
1254  static const int64 kUnknownNumberOfNodes = -1;
1255 
1256  // Constructor. The user will access the MPSolverInterface through the
1257  // MPSolver passed as argument.
1258  explicit MPSolverInterface(MPSolver* const solver);
1259  virtual ~MPSolverInterface();
1260 
1261  // ----- Solve -----
1262  // Solves problem with specified parameter values. Returns true if the
1263  // solution is optimal.
1264  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1265 
1266  // Writes the model using the solver internal write function. Currently only
1267  // available for GurobiInterface.
1268  virtual void Write(const std::string& filename);
1269 
1270  // ----- Model modifications and extraction -----
1271  // Resets extracted model.
1272  virtual void Reset() = 0;
1273 
1274  // Sets the optimization direction (min/max).
1275  virtual void SetOptimizationDirection(bool maximize) = 0;
1276 
1277  // Modifies bounds of an extracted variable.
1278  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1279 
1280  // Modifies integrality of an extracted variable.
1281  virtual void SetVariableInteger(int index, bool integer) = 0;
1282 
1283  // Modify bounds of an extracted variable.
1284  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1285 
1286  // Adds a linear constraint.
1287  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1288 
1289  // Adds an indicator constraint. Returns true if the feature is supported by
1290  // the underlying solver.
1291  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1292  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1293  return false;
1294  }
1295 
1296  // Add a variable.
1297  virtual void AddVariable(MPVariable* const var) = 0;
1298 
1299  // Changes a coefficient in a constraint.
1300  virtual void SetCoefficient(MPConstraint* const constraint,
1301  const MPVariable* const variable,
1302  double new_value, double old_value) = 0;
1303 
1304  // Clears a constraint from all its terms.
1305  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1306 
1307  // Changes a coefficient in the linear objective.
1308  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1309  double coefficient) = 0;
1310 
1311  // Changes the constant term in the linear objective.
1312  virtual void SetObjectiveOffset(double value) = 0;
1313 
1314  // Clears the objective from all its terms.
1315  virtual void ClearObjective() = 0;
1316 
1317  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1318  // ------ Query statistics on the solution and the solve ------
1319  // Returns the number of simplex iterations. The problem must be discrete,
1320  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1321  virtual int64 iterations() const = 0;
1322  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1323  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1324  virtual int64 nodes() const = 0;
1325  // Returns the best objective bound. The problem must be discrete, otherwise
1326  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1327  virtual double best_objective_bound() const = 0;
1328  // A trivial objective bound: the worst possible value of the objective,
1329  // which will be +infinity if minimizing and -infinity if maximing.
1330  double trivial_worst_objective_bound() const;
1331  // Returns the objective value of the best solution found so far.
1332  double objective_value() const;
1333 
1334  // Returns the basis status of a row.
1335  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1336  // Returns the basis status of a constraint.
1337  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1338 
1339  // Checks whether the solution is synchronized with the model, i.e. whether
1340  // the model has changed since the solution was computed last.
1341  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1342  bool CheckSolutionIsSynchronized() const;
1343  // Checks whether a feasible solution exists. The behavior is similar to
1344  // CheckSolutionIsSynchronized() above.
1345  virtual bool CheckSolutionExists() const;
1346  // Handy shortcut to do both checks above (it is often used).
1347  bool CheckSolutionIsSynchronizedAndExists() const {
1348  return CheckSolutionIsSynchronized() && CheckSolutionExists();
1349  }
1350  // Checks whether information on the best objective bound exists. The behavior
1351  // is similar to CheckSolutionIsSynchronized() above.
1352  virtual bool CheckBestObjectiveBoundExists() const;
1353 
1354  // ----- Misc -----
1355  // Queries problem type. For simplicity, the distinction between
1356  // continuous and discrete is based on the declaration of the user
1357  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1358  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1359  // the model.
1360  // Returns true if the problem is continuous.
1361  virtual bool IsContinuous() const = 0;
1362  // Returns true if the problem is continuous and linear.
1363  virtual bool IsLP() const = 0;
1364  // Returns true if the problem is discrete and linear.
1365  virtual bool IsMIP() const = 0;
1366 
1367  // Returns the index of the last variable extracted.
1368  int last_variable_index() const { return last_variable_index_; }
1369 
1370  bool variable_is_extracted(int var_index) const {
1371  return solver_->variable_is_extracted_[var_index];
1372  }
1373  void set_variable_as_extracted(int var_index, bool extracted) {
1374  solver_->variable_is_extracted_[var_index] = extracted;
1375  }
1376  bool constraint_is_extracted(int ct_index) const {
1377  return solver_->constraint_is_extracted_[ct_index];
1378  }
1379  void set_constraint_as_extracted(int ct_index, bool extracted) {
1380  solver_->constraint_is_extracted_[ct_index] = extracted;
1381  }
1382 
1383  // Returns the boolean indicating the verbosity of the solver output.
1384  bool quiet() const { return quiet_; }
1385  // Sets the boolean indicating the verbosity of the solver output.
1386  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1387 
1388  // Returns the result status of the last solve.
1389  MPSolver::ResultStatus result_status() const {
1390  CheckSolutionIsSynchronized();
1391  return result_status_;
1392  }
1393 
1394  // Returns a std::string describing the underlying solver and its version.
1395  virtual std::string SolverVersion() const = 0;
1396 
1397  // Returns the underlying solver.
1398  virtual void* underlying_solver() = 0;
1399 
1400  // Computes exact condition number. Only available for continuous
1401  // problems and only implemented in GLPK.
1402  virtual double ComputeExactConditionNumber() const;
1403 
1404  // See MPSolver::SetStartingLpBasis().
1405  virtual void SetStartingLpBasis(
1406  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1407  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1408  LOG(FATAL) << "Not supported by this solver.";
1409  }
1410 
1411  virtual bool InterruptSolve() { return false; }
1412 
1413  // See MPSolver::NextSolution() for contract.
1414  virtual bool NextSolution() { return false; }
1415 
1416  friend class MPSolver;
1417 
1418  // To access the maximize_ bool and the MPSolver.
1419  friend class MPConstraint;
1420  friend class MPObjective;
1421 
1422  protected:
1423  MPSolver* const solver_;
1424  // Indicates whether the model and the solution are synchronized.
1425  SynchronizationStatus sync_status_;
1426  // Indicates whether the solve has reached optimality,
1427  // infeasibility, a limit, etc.
1428  MPSolver::ResultStatus result_status_;
1429  // Optimization direction.
1430  bool maximize_;
1431 
1432  // Index in MPSolver::variables_ of last constraint extracted.
1433  int last_constraint_index_;
1434  // Index in MPSolver::constraints_ of last variable extracted.
1435  int last_variable_index_;
1436 
1437  // The value of the objective function.
1438  double objective_value_;
1439 
1440  // Boolean indicator for the verbosity of the solver output.
1441  bool quiet_;
1442 
1443  // Index of dummy variable created for empty constraints or the
1444  // objective offset.
1445  static const int kDummyVariableIndex;
1446 
1447  // Extracts model stored in MPSolver.
1448  void ExtractModel();
1449  // Extracts the variables that have not been extracted yet.
1450  virtual void ExtractNewVariables() = 0;
1451  // Extracts the constraints that have not been extracted yet.
1452  virtual void ExtractNewConstraints() = 0;
1453  // Extracts the objective.
1454  virtual void ExtractObjective() = 0;
1455  // Resets the extraction information.
1456  void ResetExtractionInformation();
1457  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1458  // MODEL_SYNCHRONIZED. To be used for model changes.
1459  void InvalidateSolutionSynchronization();
1460 
1461  // Sets parameters common to LP and MIP in the underlying solver.
1462  void SetCommonParameters(const MPSolverParameters& param);
1463  // Sets MIP specific parameters in the underlying solver.
1464  void SetMIPParameters(const MPSolverParameters& param);
1465  // Sets all parameters in the underlying solver.
1466  virtual void SetParameters(const MPSolverParameters& param) = 0;
1467  // Sets an unsupported double parameter.
1468  void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param);
1469  // Sets an unsupported integer parameter.
1470  virtual void SetUnsupportedIntegerParam(
1471  MPSolverParameters::IntegerParam param);
1472  // Sets a supported double parameter to an unsupported value.
1473  void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param,
1474  double value);
1475  // Sets a supported integer parameter to an unsupported value.
1476  virtual void SetIntegerParamToUnsupportedValue(
1477  MPSolverParameters::IntegerParam param, int value);
1478  // Sets each parameter in the underlying solver.
1479  virtual void SetRelativeMipGap(double value) = 0;
1480  virtual void SetPrimalTolerance(double value) = 0;
1481  virtual void SetDualTolerance(double value) = 0;
1482  virtual void SetPresolveMode(int value) = 0;
1483 
1484  // Sets the number of threads to be used by the solver.
1485  virtual util::Status SetNumThreads(int num_threads);
1486 
1487  // Pass solver specific parameters in text format. The format is
1488  // solver-specific and is the same as the corresponding solver configuration
1489  // file format. Returns true if the operation was successful.
1490  //
1491  // The default implementation of this method stores the parameters in a
1492  // temporary file and calls ReadParameterFile to import the parameter file
1493  // into the solver. Solvers that support passing the parameters directly can
1494  // override this method to skip the temporary file logic.
1495  virtual bool SetSolverSpecificParametersAsString(
1496  const std::string& parameters);
1497 
1498  // Reads a solver-specific file of parameters and set them.
1499  // Returns true if there was no errors.
1500  virtual bool ReadParameterFile(const std::string& filename);
1501 
1502  // Returns a file extension like ".tmp", this is needed because some solvers
1503  // require a given extension for the ReadParameterFile() filename and we need
1504  // to know it to generate a temporary parameter file.
1505  virtual std::string ValidFileExtensionForParameterFile() const;
1506 
1507  // Sets the scaling mode.
1508  virtual void SetScalingMode(int value) = 0;
1509  virtual void SetLpAlgorithm(int value) = 0;
1510 };
1511 
1512 } // namespace operations_research
1513 
1514 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
util::StatusOr< std::string > ExportModelAsMpsFormat(const MPModelProto &model, const MPModelExportOptions &options=MPModelExportOptions())
Outputs the current model (variables, constraints, objective) as a std::string encoded in MPS file fo...
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in c...
util::StatusOr< std::string > ExportModelAsLpFormat(const MPModelProto &model, const MPModelExportOptions &options=MPModelExportOptions())
Outputs the current model (variables, constraints, objective) as a std::string encoded in the so-call...