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, populate "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  protected:
889  friend class MPSolver;
890  friend class MPSolverInterface;
891  friend class CBCInterface;
892  friend class CLPInterface;
893  friend class GLPKInterface;
894  friend class SCIPInterface;
895  friend class SLMInterface;
896  friend class GurobiInterface;
897  friend class CplexInterface;
898  friend class GLOPInterface;
899  friend class MPVariableSolutionValueTest;
900  friend class BopInterface;
901  friend class SatInterface;
902  friend class KnapsackInterface;
903 
904  // Constructor. A variable points to a single MPSolverInterface that
905  // is specified in the constructor. A variable cannot belong to
906  // several models.
907  MPVariable(int index, double lb, double ub, bool integer,
908  const std::string& name, MPSolverInterface* const interface_in)
909  : index_(index),
910  lb_(lb),
911  ub_(ub),
912  integer_(integer),
913  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
914  solution_value_(0.0),
915  reduced_cost_(0.0),
916  interface_(interface_in) {}
917 
918  void set_solution_value(double value) { solution_value_ = value; }
919  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
920 
921  private:
922  const int index_;
923  double lb_;
924  double ub_;
925  bool integer_;
926  const std::string name_;
927  double solution_value_;
928  double reduced_cost_;
929  MPSolverInterface* const interface_;
930  DISALLOW_COPY_AND_ASSIGN(MPVariable);
931 };
932 
933 // The class for constraints of a Mathematical Programming (MP) model.
934 // A constraint is represented as a linear equation or inequality.
935 class MPConstraint {
936  public:
937  // Returns the name of the constraint.
938  const std::string& name() const { return name_; }
939 
940  // Clears all variables and coefficients. Does not clear the bounds.
941  void Clear();
942 
943  // Sets the coefficient of the variable on the constraint. If the variable
944  // does not belong to the solver, the function just returns, or crashes in
945  // non-opt mode.
946  void SetCoefficient(const MPVariable* const var, double coeff);
947  // Gets the coefficient of a given variable on the constraint (which
948  // is 0 if the variable does not appear in the constraint).
949  double GetCoefficient(const MPVariable* const var) const;
950 
951  // Returns a map from variables to their coefficients in the constraint. If a
952  // variable is not present in the map, then its coefficient is zero.
953  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
954  return coefficients_;
955  }
956 
957  // Returns the lower bound.
958  double lb() const { return lb_; }
959  // Returns the upper bound.
960  double ub() const { return ub_; }
961  // Sets the lower bound.
962  void SetLB(double lb) { SetBounds(lb, ub_); }
963  // Sets the upper bound.
964  void SetUB(double ub) { SetBounds(lb_, ub); }
965  // Sets both the lower and upper bounds.
966  void SetBounds(double lb, double ub);
967 
968  // Advanced usage: returns true if the constraint is "lazy" (see below).
969  bool is_lazy() const { return is_lazy_; }
970  // Advanced usage: sets the constraint "laziness".
971  // *** This is only supported for SCIP and has no effect on other solvers. ***
972  // When 'laziness' is true, the constraint is only considered by the Linear
973  // Programming solver if its current solution violates the constraint.
974  // In this case, the constraint is definitively added to the problem.
975  // This may be useful in some MIP problems, and may have a dramatic impact
976  // on performance.
977  // For more info see: http://tinyurl.com/lazy-constraints.
978  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
979 
980  const MPVariable* indicator_variable() const { return indicator_variable_; }
981  bool indicator_value() const { return indicator_value_; }
982 
983  // Returns the index of the constraint in the MPSolver::constraints_.
984  int index() const { return index_; }
985 
986  // Advanced usage: returns the dual value of the constraint in the
987  // current solution (only available for continuous problems).
988  double dual_value() const;
989 
990  // Advanced usage: returns the basis status of the constraint (only available
991  // for continuous problems). Note that if a constraint "linear_expression in
992  // [lb, ub]" is transformed into "linear_expression + slack = 0" with slack in
993  // [-ub, -lb], then this status is the same as the status of the slack
994  // variable with AT_UPPER_BOUND and AT_LOWER_BOUND swapped.
995  //
996  // @see MPSolver::BasisStatus.
997  MPSolver::BasisStatus basis_status() const;
998 
999  protected:
1000  friend class MPSolver;
1001  friend class MPSolverInterface;
1002  friend class CBCInterface;
1003  friend class CLPInterface;
1004  friend class GLPKInterface;
1005  friend class SCIPInterface;
1006  friend class SLMInterface;
1007  friend class GurobiInterface;
1008  friend class CplexInterface;
1009  friend class GLOPInterface;
1010  friend class BopInterface;
1011  friend class SatInterface;
1012  friend class KnapsackInterface;
1013 
1014  // Constructor. A constraint points to a single MPSolverInterface
1015  // that is specified in the constructor. A constraint cannot belong
1016  // to several models.
1017  MPConstraint(int index, double lb, double ub, const std::string& name,
1018  MPSolverInterface* const interface_in)
1019  : coefficients_(1),
1020  index_(index),
1021  lb_(lb),
1022  ub_(ub),
1023  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1024  is_lazy_(false),
1025  indicator_variable_(nullptr),
1026  dual_value_(0.0),
1027  interface_(interface_in) {}
1028 
1029  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1030 
1031  private:
1032  // Returns true if the constraint contains variables that have not
1033  // been extracted yet.
1034  bool ContainsNewVariables();
1035 
1036  // Mapping var -> coefficient.
1037  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1038 
1039  const int index_; // See index().
1040 
1041  // The lower bound for the linear constraint.
1042  double lb_;
1043 
1044  // The upper bound for the linear constraint.
1045  double ub_;
1046 
1047  // Name.
1048  const std::string name_;
1049 
1050  // True if the constraint is "lazy", i.e. the constraint is added to the
1051  // underlying Linear Programming solver only if it is violated.
1052  // By default this parameter is 'false'.
1053  bool is_lazy_;
1054 
1055  // If given, this constraint is only active if `indicator_variable_`'s value
1056  // is equal to `indicator_value_`.
1057  const MPVariable* indicator_variable_;
1058  bool indicator_value_;
1059 
1060  double dual_value_;
1061  MPSolverInterface* const interface_;
1062  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1063 };
1064 
1065 // This class stores parameter settings for LP and MIP solvers.
1066 // Some parameters are marked as advanced: do not change their values
1067 // unless you know what you are doing!
1068 //
1069 // For developers: how to add a new parameter:
1070 // - Add the new Foo parameter in the DoubleParam or IntegerParam enum.
1071 // - If it is a categorical param, add a FooValues enum.
1072 // - Decide if the wrapper should define a default value for it: yes
1073 // if it controls the properties of the solution (example:
1074 // tolerances) or if it consistently improves performance, no
1075 // otherwise. If yes, define kDefaultFoo.
1076 // - Add a foo_value_ member and, if no default value is defined, a
1077 // foo_is_default_ member.
1078 // - Add code to handle Foo in Set...Param, Reset...Param,
1079 // Get...Param, Reset and the constructor.
1080 // - In class MPSolverInterface, add a virtual method SetFoo, add it
1081 // to SetCommonParameters or SetMIPParameters, and implement it for
1082 // each solver. Sometimes, parameters need to be implemented
1083 // differently, see for example the INCREMENTALITY implementation.
1084 // - Add a test in linear_solver_test.cc.
1085 //
1086 // TODO(user): store the parameter values in a protocol buffer
1087 // instead. We need to figure out how to deal with the subtleties of
1088 // the default values.
1089 class MPSolverParameters {
1090  public:
1091  // Enumeration of parameters that take continuous values.
1092  enum DoubleParam {
1093  // Limit for relative MIP gap.
1094  RELATIVE_MIP_GAP = 0,
1095  // Advanced usage: tolerance for primal feasibility of basic
1096  // solutions. This does not control the integer feasibility
1097  // tolerance of integer solutions for MIP or the tolerance used
1098  // during presolve.
1099  PRIMAL_TOLERANCE = 1,
1100  // Advanced usage: tolerance for dual feasibility of basic solutions.
1101  DUAL_TOLERANCE = 2
1102  };
1103 
1104  // Enumeration of parameters that take integer or categorical values.
1105  enum IntegerParam {
1106  // Advanced usage: presolve mode.
1107  PRESOLVE = 1000,
1108  // Algorithm to solve linear programs.
1109  LP_ALGORITHM = 1001,
1110  // Advanced usage: incrementality from one solve to the next.
1111  INCREMENTALITY = 1002,
1112  // Advanced usage: enable or disable matrix scaling.
1113  SCALING = 1003
1114  };
1115 
1116  // For each categorical parameter, enumeration of possible values.
1117  enum PresolveValues {
1118  PRESOLVE_OFF = 0, // Presolve is off.
1119  PRESOLVE_ON = 1 // Presolve is on.
1120  };
1121 
1122  enum LpAlgorithmValues {
1123  DUAL = 10, // Dual simplex.
1124  PRIMAL = 11, // Primal simplex.
1125  BARRIER = 12 // Barrier algorithm.
1126  };
1127 
1128  enum IncrementalityValues {
1129  // Start solve from scratch.
1130  INCREMENTALITY_OFF = 0,
1131  // Reuse results from previous solve as much as the underlying
1132  // solver allows.
1133  INCREMENTALITY_ON = 1
1134  };
1135 
1136  enum ScalingValues {
1137  SCALING_OFF = 0, // Scaling is off.
1138  SCALING_ON = 1 // Scaling is on.
1139  };
1140 
1141  // @{
1142  // Placeholder value to indicate that a parameter is set to
1143  // the default value defined in the wrapper.
1144  static const double kDefaultDoubleParamValue;
1145  static const int kDefaultIntegerParamValue;
1146  // @}
1147 
1148  // @{
1149  // Placeholder value to indicate that a parameter is unknown.
1150  static const double kUnknownDoubleParamValue;
1151  static const int kUnknownIntegerParamValue;
1152  // @}
1153 
1154  // @{
1155  // Default values for parameters. Only parameters that define the
1156  // properties of the solution returned need to have a default value
1157  // (that is the same for all solvers). You can also define a default
1158  // value for performance parameters when you are confident it is a
1159  // good choice (example: always turn presolve on).
1160  static const double kDefaultRelativeMipGap;
1161  static const double kDefaultPrimalTolerance;
1162  static const double kDefaultDualTolerance;
1163  static const PresolveValues kDefaultPresolve;
1164  static const IncrementalityValues kDefaultIncrementality;
1165  // @}
1166 
1167  // The constructor sets all parameters to their default value.
1168  MPSolverParameters();
1169 
1170  // @{
1171  // Sets a parameter to a specific value.
1172  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1173  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1174  // @}
1175 
1176  // @{
1177  // Sets a parameter to its default value (default value defined
1178  // in MPSolverParameters if it exists, otherwise the default value
1179  // defined in the underlying solver).
1180  void ResetDoubleParam(MPSolverParameters::DoubleParam param);
1181  void ResetIntegerParam(MPSolverParameters::IntegerParam param);
1182  // Sets all parameters to their default value.
1183  void Reset();
1184  // @}
1185 
1186  // @{
1187  // Returns the value of a parameter.
1188  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1189  int GetIntegerParam(MPSolverParameters::IntegerParam param) const;
1190  // @}
1191 
1192  private:
1193  // @{
1194  // Parameter value for each parameter.
1195  // @see DoubleParam
1196  // @see IntegerParam
1197  double relative_mip_gap_value_;
1198  double primal_tolerance_value_;
1199  double dual_tolerance_value_;
1200  int presolve_value_;
1201  int scaling_value_;
1202  int lp_algorithm_value_;
1203  int incrementality_value_;
1204  // @}
1205 
1206  // Boolean value indicating whether each parameter is set to the
1207  // solver's default value. Only parameters for which the wrapper
1208  // does not define a default value need such an indicator.
1209  bool lp_algorithm_is_default_;
1210 
1211  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1212 };
1213 
1214 // This class wraps the actual mathematical programming solvers. Each
1215 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1216 // derives from this abstract class. This class is never directly
1217 // accessed by the user.
1218 // @see glop_interface.cc
1219 // @see cbc_interface.cc
1220 // @see clp_interface.cc
1221 // @see glpk_interface.cc
1222 // @see scip_interface.cc
1223 class MPSolverInterface {
1224  public:
1225  enum SynchronizationStatus {
1226  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1227  // sync for the model nor for the solution.
1228  MUST_RELOAD,
1229  // The underlying solver and MPSolver are in sync for the model
1230  // but not for the solution: the model has changed since the
1231  // solution was computed last.
1232  MODEL_SYNCHRONIZED,
1233  // The underlying solver and MPSolver are in sync for the model and
1234  // the solution.
1235  SOLUTION_SYNCHRONIZED
1236  };
1237 
1238  // When the underlying solver does not provide the number of simplex
1239  // iterations.
1240  static const int64 kUnknownNumberOfIterations = -1;
1241  // When the underlying solver does not provide the number of
1242  // branch-and-bound nodes.
1243  static const int64 kUnknownNumberOfNodes = -1;
1244 
1245  // Constructor. The user will access the MPSolverInterface through the
1246  // MPSolver passed as argument.
1247  explicit MPSolverInterface(MPSolver* const solver);
1248  virtual ~MPSolverInterface();
1249 
1250  // ----- Solve -----
1251  // Solves problem with specified parameter values. Returns true if the
1252  // solution is optimal.
1253  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1254 
1255  // Writes the model using the solver internal write function. Currently only
1256  // available for GurobiInterface.
1257  virtual void Write(const std::string& filename);
1258 
1259  // ----- Model modifications and extraction -----
1260  // Resets extracted model.
1261  virtual void Reset() = 0;
1262 
1263  // Sets the optimization direction (min/max).
1264  virtual void SetOptimizationDirection(bool maximize) = 0;
1265 
1266  // Modifies bounds of an extracted variable.
1267  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1268 
1269  // Modifies integrality of an extracted variable.
1270  virtual void SetVariableInteger(int index, bool integer) = 0;
1271 
1272  // Modify bounds of an extracted variable.
1273  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1274 
1275  // Adds a linear constraint.
1276  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1277 
1278  // Adds an indicator constraint. Returns true if the feature is supported by
1279  // the underlying solver.
1280  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1281  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1282  return false;
1283  }
1284 
1285  // Add a variable.
1286  virtual void AddVariable(MPVariable* const var) = 0;
1287 
1288  // Changes a coefficient in a constraint.
1289  virtual void SetCoefficient(MPConstraint* const constraint,
1290  const MPVariable* const variable,
1291  double new_value, double old_value) = 0;
1292 
1293  // Clears a constraint from all its terms.
1294  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1295 
1296  // Changes a coefficient in the linear objective.
1297  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1298  double coefficient) = 0;
1299 
1300  // Changes the constant term in the linear objective.
1301  virtual void SetObjectiveOffset(double value) = 0;
1302 
1303  // Clears the objective from all its terms.
1304  virtual void ClearObjective() = 0;
1305 
1306  // ------ Query statistics on the solution and the solve ------
1307  // Returns the number of simplex iterations. The problem must be discrete,
1308  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1309  virtual int64 iterations() const = 0;
1310  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1311  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1312  virtual int64 nodes() const = 0;
1313  // Returns the best objective bound. The problem must be discrete, otherwise
1314  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1315  virtual double best_objective_bound() const = 0;
1316  // A trivial objective bound: the worst possible value of the objective,
1317  // which will be +infinity if minimizing and -infinity if maximing.
1318  double trivial_worst_objective_bound() const;
1319  // Returns the objective value of the best solution found so far.
1320  double objective_value() const;
1321 
1322  // Returns the basis status of a row.
1323  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1324  // Returns the basis status of a constraint.
1325  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1326 
1327  // Checks whether the solution is synchronized with the model, i.e. whether
1328  // the model has changed since the solution was computed last.
1329  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1330  bool CheckSolutionIsSynchronized() const;
1331  // Checks whether a feasible solution exists. The behavior is similar to
1332  // CheckSolutionIsSynchronized() above.
1333  virtual bool CheckSolutionExists() const;
1334  // Handy shortcut to do both checks above (it is often used).
1335  bool CheckSolutionIsSynchronizedAndExists() const {
1336  return CheckSolutionIsSynchronized() && CheckSolutionExists();
1337  }
1338  // Checks whether information on the best objective bound exists. The behavior
1339  // is similar to CheckSolutionIsSynchronized() above.
1340  virtual bool CheckBestObjectiveBoundExists() const;
1341 
1342  // ----- Misc -----
1343  // Queries problem type. For simplicity, the distinction between
1344  // continuous and discrete is based on the declaration of the user
1345  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1346  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1347  // the model.
1348  // Returns true if the problem is continuous.
1349  virtual bool IsContinuous() const = 0;
1350  // Returns true if the problem is continuous and linear.
1351  virtual bool IsLP() const = 0;
1352  // Returns true if the problem is discrete and linear.
1353  virtual bool IsMIP() const = 0;
1354 
1355  // Returns the index of the last variable extracted.
1356  int last_variable_index() const { return last_variable_index_; }
1357 
1358  bool variable_is_extracted(int var_index) const {
1359  return solver_->variable_is_extracted_[var_index];
1360  }
1361  void set_variable_as_extracted(int var_index, bool extracted) {
1362  solver_->variable_is_extracted_[var_index] = extracted;
1363  }
1364  bool constraint_is_extracted(int ct_index) const {
1365  return solver_->constraint_is_extracted_[ct_index];
1366  }
1367  void set_constraint_as_extracted(int ct_index, bool extracted) {
1368  solver_->constraint_is_extracted_[ct_index] = extracted;
1369  }
1370 
1371  // Returns the boolean indicating the verbosity of the solver output.
1372  bool quiet() const { return quiet_; }
1373  // Sets the boolean indicating the verbosity of the solver output.
1374  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1375 
1376  // Returns the result status of the last solve.
1377  MPSolver::ResultStatus result_status() const {
1378  CheckSolutionIsSynchronized();
1379  return result_status_;
1380  }
1381 
1382  // Returns a std::string describing the underlying solver and its version.
1383  virtual std::string SolverVersion() const = 0;
1384 
1385  // Returns the underlying solver.
1386  virtual void* underlying_solver() = 0;
1387 
1388  // Computes exact condition number. Only available for continuous
1389  // problems and only implemented in GLPK.
1390  virtual double ComputeExactConditionNumber() const;
1391 
1392  // See MPSolver::SetStartingLpBasis().
1393  virtual void SetStartingLpBasis(
1394  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1395  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1396  LOG(FATAL) << "Not supported by this solver.";
1397  }
1398 
1399  virtual bool InterruptSolve() { return false; }
1400 
1401  // See MPSolver::NextSolution() for contract.
1402  virtual bool NextSolution() { return false; }
1403 
1404  friend class MPSolver;
1405 
1406  // To access the maximize_ bool and the MPSolver.
1407  friend class MPConstraint;
1408  friend class MPObjective;
1409 
1410  protected:
1411  MPSolver* const solver_;
1412  // Indicates whether the model and the solution are synchronized.
1413  SynchronizationStatus sync_status_;
1414  // Indicates whether the solve has reached optimality,
1415  // infeasibility, a limit, etc.
1416  MPSolver::ResultStatus result_status_;
1417  // Optimization direction.
1418  bool maximize_;
1419 
1420  // Index in MPSolver::variables_ of last constraint extracted.
1421  int last_constraint_index_;
1422  // Index in MPSolver::constraints_ of last variable extracted.
1423  int last_variable_index_;
1424 
1425  // The value of the objective function.
1426  double objective_value_;
1427 
1428  // Boolean indicator for the verbosity of the solver output.
1429  bool quiet_;
1430 
1431  // Index of dummy variable created for empty constraints or the
1432  // objective offset.
1433  static const int kDummyVariableIndex;
1434 
1435  // Extracts model stored in MPSolver.
1436  void ExtractModel();
1437  // Extracts the variables that have not been extracted yet.
1438  virtual void ExtractNewVariables() = 0;
1439  // Extracts the constraints that have not been extracted yet.
1440  virtual void ExtractNewConstraints() = 0;
1441  // Extracts the objective.
1442  virtual void ExtractObjective() = 0;
1443  // Resets the extraction information.
1444  void ResetExtractionInformation();
1445  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1446  // MODEL_SYNCHRONIZED. To be used for model changes.
1447  void InvalidateSolutionSynchronization();
1448 
1449  // Sets parameters common to LP and MIP in the underlying solver.
1450  void SetCommonParameters(const MPSolverParameters& param);
1451  // Sets MIP specific parameters in the underlying solver.
1452  void SetMIPParameters(const MPSolverParameters& param);
1453  // Sets all parameters in the underlying solver.
1454  virtual void SetParameters(const MPSolverParameters& param) = 0;
1455  // Sets an unsupported double parameter.
1456  void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param);
1457  // Sets an unsupported integer parameter.
1458  virtual void SetUnsupportedIntegerParam(
1459  MPSolverParameters::IntegerParam param);
1460  // Sets a supported double parameter to an unsupported value.
1461  void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param,
1462  double value);
1463  // Sets a supported integer parameter to an unsupported value.
1464  virtual void SetIntegerParamToUnsupportedValue(
1465  MPSolverParameters::IntegerParam param, int value);
1466  // Sets each parameter in the underlying solver.
1467  virtual void SetRelativeMipGap(double value) = 0;
1468  virtual void SetPrimalTolerance(double value) = 0;
1469  virtual void SetDualTolerance(double value) = 0;
1470  virtual void SetPresolveMode(int value) = 0;
1471 
1472  // Sets the number of threads to be used by the solver.
1473  virtual util::Status SetNumThreads(int num_threads);
1474 
1475  // Pass solver specific parameters in text format. The format is
1476  // solver-specific and is the same as the corresponding solver configuration
1477  // file format. Returns true if the operation was successful.
1478  //
1479  // The default implementation of this method stores the parameters in a
1480  // temporary file and calls ReadParameterFile to import the parameter file
1481  // into the solver. Solvers that support passing the parameters directly can
1482  // override this method to skip the temporary file logic.
1483  virtual bool SetSolverSpecificParametersAsString(
1484  const std::string& parameters);
1485 
1486  // Reads a solver-specific file of parameters and set them.
1487  // Returns true if there was no errors.
1488  virtual bool ReadParameterFile(const std::string& filename);
1489 
1490  // Returns a file extension like ".tmp", this is needed because some solvers
1491  // require a given extension for the ReadParameterFile() filename and we need
1492  // to know it to generate a temporary parameter file.
1493  virtual std::string ValidFileExtensionForParameterFile() const;
1494 
1495  // Sets the scaling mode.
1496  virtual void SetScalingMode(int value) = 0;
1497  virtual void SetLpAlgorithm(int value) = 0;
1498 };
1499 
1500 } // namespace operations_research
1501 
1502 #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...