Generated on: Thu Mar 29 07:46:58 PDT 2012 for custom file set | ||
|
||
// doxy/ or-tools/ src/ linear_solver/ |
00001 // Copyright 2010-2012 Google 00002 // Licensed under the Apache License, Version 2.0 (the "License"); 00003 // you may not use this file except in compliance with the License. 00004 // You may obtain a copy of the License at 00005 // 00006 // http://www.apache.org/licenses/LICENSE-2.0 00007 // 00008 // Unless required by applicable law or agreed to in writing, software 00009 // distributed under the License is distributed on an "AS IS" BASIS, 00010 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00011 // See the License for the specific language governing permissions and 00012 // limitations under the License. 00013 // 00014 // (Laurent Perron). 00015 // 00016 // A C++ wrapper that provides a simple and unified interface to 00017 // several linear programming and mixed integer programming solvers: 00018 // GLPK, CLP, CBC and SCIP. The wrapper can also be used in Java and 00019 // Python via SWIG. 00020 // 00021 // 00022 // ----------------------------------- 00023 // What is Linear Programming? 00024 // 00025 // In mathematics, linear programming (LP) is a technique for optimization of 00026 // a linear objective function, subject to linear equality and linear 00027 // inequality constraints. Informally, linear programming determines the way 00028 // to achieve the best outcome (such as maximum profit or lowest cost) in a 00029 // given mathematical model and given some list of requirements represented 00030 // as linear equations. 00031 // 00032 // The most widely used technique for solving a linear program is the Simplex 00033 // algorithm, devised by George Dantzig in 1947. It performs very well on 00034 // most instances, for which its running time is polynomial. A lot of effort 00035 // has been put into improving the algorithm and its implementation. As a 00036 // byproduct, it has however been shown that one can always construct 00037 // problems that take exponential time for the Simplex algorithm to solve. 00038 // Research has thus focused on trying to find a polynomial algorithm for 00039 // linear programming, or to prove that linear programming is indeed 00040 // polynomial. 00041 // 00042 // Leonid Khachiyan first exhibited in 1979 a weakly polynomial algorithm for 00043 // linear programming. "Weakly polynomial" means that the running time of the 00044 // algorithm is in O(P(n) * 2^p) where P(n) is a polynomial of the size of the 00045 // problem, and p is the precision of computations expressed in number of 00046 // bits. With a fixed-precision, floating-point-based implementation, a weakly 00047 // polynomial algorithm will thus run in polynomial time. No implementation 00048 // of Khachiyan's algorithm has proved efficient, but a larger breakthrough in 00049 // the field came in 1984 when Narendra Karmarkar introduced a new interior 00050 // point method for solving linear programming problems. Interior point 00051 // algorithms have proved efficient on very large linear programs. 00052 // 00053 // Check Wikipedia for more detail: 00054 // http://en.wikipedia.org/wiki/Linear_programming 00055 // 00056 // ----------------------------------- 00057 // Example of a Linear Program 00058 // 00059 // maximize: 00060 // 3x + y 00061 // subject to: 00062 // 1.5 x + 2 y <= 12 00063 // 0 <= x <= 3 00064 // 0 <= y <= 5 00065 // 00066 // A linear program has: 00067 // 1) a linear objective function 00068 // 2) linear constraints that can be equalities or inequalities 00069 // 3) bounds on variables that can be positive, negative, finite or 00070 // infinite. 00071 // 00072 // ----------------------------------- 00073 // What is Mixed Integer Programming? 00074 // 00075 // Here, the constraints and the objective are still linear but 00076 // there are additional integrality requirements for variables. If 00077 // all variables are required to take integer values, then the 00078 // problem is called an integer program (IP). In most cases, only 00079 // some variables are required to be integer and the rest of the 00080 // variables are continuous: this is called a mixed integer program 00081 // (MIP). IPs and MIPs are generally NP-hard. 00082 // 00083 // Integer variables can be used to model discrete decisions (build a 00084 // datacenter in city A or city B), logical relationships (only 00085 // place machines in datacenter A if we have decided to build 00086 // datacenter A) and approximate non-linear functions with piecewise 00087 // linear functions (for example, the cost of machines as a function 00088 // of how many machines are bought, or the latency of a server as a 00089 // function of its load). 00090 // 00091 // ----------------------------------- 00092 // How to use the wrapper? 00093 // 00094 // The user builds the model and solves it through the MPSolver class, 00095 // then queries the solution through the MPSolver, MPVariable and 00096 // MPConstraint classes. To be able to query a solution, you need the 00097 // following: 00098 // - A solution exists: MPSolver::Solve has been called and a solution 00099 // has been found. 00100 // - The model has not been modified since the last time 00101 // MPSolver::Solve was called. Otherwise, the solution obtained 00102 // before the model modification may not longer be feasible or 00103 // optimal. 00104 // 00105 // @see ../examples/linear_programming.cc for a simple LP example 00106 // @see ../examples/integer_programming.cc for a simple MIP example 00107 // 00108 // All methods cannot be called successfully in all cases. For 00109 // example: you cannot query a solution when no solution exists, you 00110 // cannot query a reduced cost value (which makes sense only on 00111 // continuous problems) on a discrete problem. When a method is 00112 // called in an unsuitable context, it aborts with a 00113 // LOG(FATAL). 00114 // TODO(user): handle failures gracefully. 00115 // 00116 // ----------------------------------- 00117 // For developers: How the does the wrapper work? 00118 // 00119 // MPSolver stores a representation of the model (variables, 00120 // constraints and objective) in its own data structures and a 00121 // pointer to a MPSolverInterface that wraps the underlying solver 00122 // (CBC, CLP, GLPK or SCIP) that does the actual work. The 00123 // underlying solver also keeps a representation of the model in its 00124 // own data structures. The model representations in MPSolver and in 00125 // the underlying solver are kept in sync by the 'extraction' 00126 // mechanism: synchronously for some changes and asynchronously 00127 // (when MPSolver::Solve is called) for others. Synchronicity 00128 // depends on the modification applied and on the underlying solver. 00129 00130 #ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_ 00131 #define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_ 00132 00133 #include "base/hash.h" 00134 #include "base/hash.h" 00135 #include <limits> 00136 #include <string> 00137 #include <vector> 00138 00139 #include "base/commandlineflags.h" 00140 #include "base/integral_types.h" 00141 #include "base/logging.h" 00142 #include "base/macros.h" 00143 #include "base/scoped_ptr.h" 00144 #include "base/timer.h" 00145 #include "base/strutil.h" 00146 #include "base/sparsetable.h" 00147 #include "base/hash.h" 00148 00149 using std::string; 00150 00151 namespace operations_research { 00152 00153 class MPConstraint; 00154 class MPModelProto; 00155 class MPModelRequest; 00156 class MPObjective; 00157 class MPSolutionResponse; 00158 class MPSolverInterface; 00159 class MPSolverParameters; 00160 class MPVariable; 00161 00162 // This mathematical programming (MP) solver class is the main class 00163 // though which users build and solve problems. 00164 class MPSolver { 00165 public: 00166 // The type of problems (LP or MIP) that will be solved and the 00167 // underlying solver (GLPK, CLP, CBC or SCIP) that will solve them. 00168 enum OptimizationProblemType { 00169 #if defined(USE_GLPK) 00170 GLPK_LINEAR_PROGRAMMING, 00171 GLPK_MIXED_INTEGER_PROGRAMMING, 00172 #endif 00173 #if defined(USE_CLP) 00174 CLP_LINEAR_PROGRAMMING, 00175 #endif 00176 #if defined(USE_CBC) 00177 CBC_MIXED_INTEGER_PROGRAMMING, 00178 #endif 00179 #if defined(USE_SCIP) 00180 SCIP_MIXED_INTEGER_PROGRAMMING, 00181 #endif 00182 }; 00183 00184 MPSolver(const string& name, OptimizationProblemType problem_type); 00185 virtual ~MPSolver(); 00186 00187 string Name() const { 00188 return name_; // Set at construction. 00189 } 00190 00191 // Clears the objective (including the optimization direction), all 00192 // variables and constraints. All the other properties of the MPSolver 00193 // (like the time limit) are kept untouched. 00194 void Clear(); 00195 00196 // ----- Variables ------ 00197 // Returns the number of variables. 00198 int NumVariables() const { return variables_.size(); } 00199 // Look up a variable by name, and return NULL if it does not exist. 00200 MPVariable* LookupVariableOrNull(const string& var_name) const; 00201 00202 // Creates a variable with the given bounds, integrality requirement 00203 // and name. Bounds can be finite or +/- MPSolver::infinity(). 00204 // The MPSolver owns the variable (i.e. the returned pointer is borrowed). 00205 // Variable names must be unique (it may crash otherwise). Empty variable 00206 // names are allowed, an automated variable name will then be assigned. 00207 MPVariable* MakeVar(double lb, double ub, bool integer, const string& name); 00208 // Creates a continuous variable. 00209 MPVariable* MakeNumVar(double lb, double ub, const string& name); 00210 // Creates an integer variable. 00211 MPVariable* MakeIntVar(double lb, double ub, const string& name); 00212 // Creates a boolean variable. 00213 MPVariable* MakeBoolVar(const string& name); 00214 00215 // Creates an array of variables. All variables created have the 00216 // same bounds and integrality requirement. 00217 // @param name the prefix of the variable names. Variables are named 00218 // name0, name1, ... 00219 void MakeVarArray(int nb, 00220 double lb, 00221 double ub, 00222 bool integer, 00223 const string& name_prefix, 00224 std::vector<MPVariable*>* vars); 00225 // Creates an array of continuous variables. 00226 void MakeNumVarArray(int nb, 00227 double lb, 00228 double ub, 00229 const string& name, 00230 std::vector<MPVariable*>* vars); 00231 // Creates an array of integer variables. 00232 void MakeIntVarArray(int nb, 00233 double lb, 00234 double ub, 00235 const string& name, 00236 std::vector<MPVariable*>* vars); 00237 // Creates an array of boolean variables. 00238 void MakeBoolVarArray(int nb, 00239 const string& name, 00240 std::vector<MPVariable*>* vars); 00241 00242 // ----- Constraints ----- 00243 // Returns the number of constraints. 00244 int NumConstraints() const { return constraints_.size(); } 00245 // Look up a constraint by name, and return NULL if it does not exist. 00246 MPConstraint* LookupConstraintOrNull(const string& constraint_name) const; 00247 00248 // Creates a linear constraint with given bounds. Bounds can be 00249 // finite or +/- MPSolver::infinity(). The MPSolver class assumes 00250 // ownership of the constraint. 00251 // @return a pointer to the newly created constraint. 00252 MPConstraint* MakeRowConstraint(double lb, double ub); 00253 // Creates a constraint with -infinity and +infinity bounds. 00254 MPConstraint* MakeRowConstraint(); 00255 // Creates a named constraint with given bounds. 00256 MPConstraint* MakeRowConstraint(double lb, double ub, const string& name); 00257 // Creates a named constraint with -infinity and +infinity bounds. 00258 MPConstraint* MakeRowConstraint(const string& name); 00259 00260 // ----- Objective ----- 00261 // Note that the objective is owned by the solver, and is initialized to 00262 // its default value (see the MPObjective class below) at construction. 00263 const MPObjective& Objective() const { return *objective_.get(); } 00264 MPObjective* MutableObjective() { return objective_.get(); } 00265 00266 // ----- Solve ----- 00267 00268 // The status of solving the problem. 00269 // TODO(user): Figure out once and for all what the status of 00270 // underlying solvers exactly mean, especially for feasible and 00271 // infeasible. 00272 enum ResultStatus { 00273 OPTIMAL, // optimal. 00274 FEASIBLE, // feasible, or stopped by limit. 00275 INFEASIBLE, // proven infeasible. 00276 UNBOUNDED, // proven unbounded. 00277 ABNORMAL, // abnormal, i.e., error of some kind. 00278 NOT_SOLVED // not been solved yet. 00279 }; 00280 00281 // Solves the problem using default parameter values. 00282 ResultStatus Solve(); 00283 // Solves the problem using the specified parameter values. 00284 ResultStatus Solve(const MPSolverParameters& param); 00285 00286 // Advanced usage: resets extracted model to solve from scratch. 00287 void Reset(); 00288 00289 // ----- Methods using protocol buffers ----- 00290 00291 // The status of loading the problem from a protocol buffer. 00292 enum LoadStatus { 00293 NO_ERROR = 0, // no error has been encountered. 00294 // Skip value '1' to stay consistent with the .proto. 00295 DUPLICATE_VARIABLE_ID = 2, // error: two variables have the same id. 00296 UNKNOWN_VARIABLE_ID = 3, // error: a variable has an unknown id. 00297 }; 00298 00299 // Loads model from protocol buffer. 00300 LoadStatus LoadModel(const MPModelProto& input_model); 00301 00302 // Exports model to protocol buffer. 00303 void ExportModel(MPModelProto* output_model) const; 00304 00305 // Encodes the current solution in a solution response protocol buffer. 00306 // Only nonzero variable values are stored in order to reduce the 00307 // size of the MPSolutionResponse protocol buffer. 00308 void FillSolutionResponse(MPSolutionResponse* response) const; 00309 00310 // Solves the model encoded by a MPModelRequest protocol buffer and 00311 // fills the solution encoded as a MPSolutionResponse. 00312 // Note(user): This creates a temporary MPSolver and destroys it at the 00313 // end. If you want to keep the MPSolver alive (for debugging, or for 00314 // incremental solving), you should write another version of this function 00315 // that creates the MPSolver object on the heap and returns it. 00316 static void SolveWithProtocolBuffers(const MPModelRequest& model_request, 00317 MPSolutionResponse* response); 00318 00319 // ----- Misc ----- 00320 00321 // Advanced usage: possible basis status values for a variable and the 00322 // slack variable of a linear constraint. 00323 enum BasisStatus { 00324 FREE = 0, 00325 AT_LOWER_BOUND, 00326 AT_UPPER_BOUND, 00327 FIXED_VALUE, 00328 BASIC 00329 }; 00330 00331 // Infinity. You can use -MPSolver::infinity() for negative infinity. 00332 static double infinity() { 00333 return std::numeric_limits<double>::infinity(); 00334 } 00335 00336 // Suppresses all output from the underlying solver. 00337 void SuppressOutput(); 00338 00339 // Enables a reasonably verbose output from the underlying 00340 // solver. The level of verbosity and the location of this output 00341 // depends on the underlying solver. In most cases, it is sent to 00342 // stdout. 00343 void EnableOutput(); 00344 00345 void set_write_model_filename(const string &filename) { 00346 write_model_filename_ = filename; 00347 } 00348 00349 string write_model_filename() const { 00350 return write_model_filename_; 00351 } 00352 00353 void set_time_limit(int64 time_limit) { 00354 DCHECK_GE(time_limit, 0); 00355 time_limit_ = time_limit; 00356 } 00357 00358 int64 time_limit() const { 00359 return time_limit_; 00360 } 00361 00362 // Returns wall_time() in milliseconds since the creation of the solver. 00363 int64 wall_time() const { 00364 return timer_.GetInMs(); 00365 } 00366 00367 // Returns the number of simplex iterations. 00368 int64 iterations() const; 00369 00370 // Returns the number of branch-and-bound nodes. Only available for 00371 // discrete problems. 00372 int64 nodes() const; 00373 00374 // Checks the validity of a variable or constraint name. 00375 bool CheckNameValidity(const string& name); 00376 // Checks the validity of all variables and constraints names. 00377 bool CheckAllNamesValidity(); 00378 00379 // Returns a string describing the underlying solver and its version. 00380 string SolverVersion() const; 00381 00382 // Advanced usage: returns the underlying solver so that the user 00383 // can use solver-specific features or features that are not exposed 00384 // in the simple API of MPSolver. This method is for advanced users, 00385 // use at your own risk! In particular, if you modify the model or 00386 // the solution by accessing the underlying solver directly, then 00387 // the underlying solver will be out of sync with the information 00388 // kept in the wrapper (MPSolver, MPVariable, MPConstraint, 00389 // MPObjective). You need to cast the void* returned back to its 00390 // original type that depends on the interface (CBC: 00391 // OsiClpSolverInterface*, CLP: ClpSimplex*, GLPK: glp_prob*, SCIP: 00392 // SCIP*). 00393 void* underlying_solver(); 00394 00395 // Advanced usage: computes the exact condition number of the 00396 // current scaled basis: L1norm(B) * L1norm(inverse(B)), where B is 00397 // the scaled basis. 00398 // This method requires that a basis exists: it should be called 00399 // after Solve. It is only available for continuous problems. It is 00400 // implemented for GLPK but not CLP because CLP does not provide the 00401 // API for doing it. 00402 // The condition number measures how well the constraint matrix is 00403 // conditioned and can be used to predict whether numerical issues 00404 // will arise during the solve: the model is declared infeasible 00405 // whereas it is feasible (or vice-versa), the solution obtained is 00406 // not optimal or violates some constraints, the resolution is slow 00407 // because of repeated singularities. 00408 // The rule of thumb to interpret the condition number kappa is: 00409 // o kappa <= 1e7: virtually no chance of numerical issues 00410 // o 1e7 < kappa <= 1e10: small chance of numerical issues 00411 // o 1e10 < kappa <= 1e13: medium chance of numerical issues 00412 // o kappa > 1e13: high chance of numerical issues 00413 // The computation of the condition number depends on the quality of 00414 // the LU decomposition, so it is not very accurate when the matrix 00415 // is ill conditioned. 00416 double ComputeExactConditionNumber() const; 00417 00418 friend class GLPKInterface; 00419 friend class CLPInterface; 00420 friend class CBCInterface; 00421 friend class SCIPInterface; 00422 friend class MPSolverInterface; 00423 00424 // *** DEPRECATED *** 00425 // Setters and getters for the objective. Please call 00426 // Objective().Getter() and MutableObjective()->Setter() instead. 00427 // TODO(user): remove when they are no longer used. 00428 double objective_value() const; 00429 double best_objective_bound() const; 00430 void ClearObjective(); 00431 void SetObjectiveCoefficient(const MPVariable* const var, double coeff); 00432 void SetObjectiveOffset(double value); 00433 void AddObjectiveOffset(double value); 00434 void SetOptimizationDirection(bool maximize); 00435 void SetMinimization() { SetOptimizationDirection(false); } 00436 void SetMaximization() { SetOptimizationDirection(true); } 00437 bool Maximization() const; 00438 bool Minimization() const; 00439 00440 private: 00441 // Computes the size of the constraint with the largest number of 00442 // coefficients with index in [min_constraint_index, 00443 // max_constraint_index) 00444 int ComputeMaxConstraintSize(int min_constraint_index, 00445 int max_constraint_index) const; 00446 00447 // Returns true if the model has constraints with lower bound > upper bound. 00448 bool HasInfeasibleConstraints() const; 00449 00450 // The name of the linear programming problem. 00451 const string name_; 00452 00453 // The solver interface. 00454 scoped_ptr<MPSolverInterface> interface_; 00455 00456 // The vector of variables in the problem. 00457 std::vector<MPVariable*> variables_; 00458 // A map from a variable's name to its index in variables_. 00459 hash_map<string, int> variable_name_to_index_; 00460 00461 // The vector of constraints in the problem. 00462 std::vector<MPConstraint*> constraints_; 00463 // A map from a constraint's name to its index in constraints_. 00464 hash_map<string, int> constraint_name_to_index_; 00465 00466 // The linear objective function. 00467 scoped_ptr<MPObjective> objective_; 00468 00469 // Time limit in milliseconds (0 = no limit). 00470 int64 time_limit_; 00471 00472 // Name of the file where the solver writes out the model when Solve 00473 // is called. If empty, no file is written. 00474 string write_model_filename_; 00475 00476 WallTimer timer_; 00477 00478 DISALLOW_COPY_AND_ASSIGN(MPSolver); 00479 }; 00480 00481 // A class to express a linear objective. 00482 class MPObjective { 00483 public: 00484 // Clears the offset, all variables and coefficients, and the optimization 00485 // direction. 00486 void Clear(); 00487 00488 // Sets the coefficient of the variable in the objective. 00489 void SetCoefficient(const MPVariable* const var, double coeff); 00490 // Gets the coefficient of a given variable in the objective (which 00491 // is 0 if the variable does not appear in the objective). 00492 double GetCoefficient(const MPVariable* const var) const; 00493 00494 // Sets the constant term in the objective. 00495 void SetOffset(double value); 00496 // Gets the constant term in the objective. 00497 double offset() const { return offset_; } 00498 00499 // Adds a constant term to the objective. 00500 // Note: please use the less ambiguous SetOffest() if possible! 00501 // TODO(user): remove this. 00502 void AddOffset(double value) { SetOffset(offset() + value); } 00503 00504 // Sets the optimization direction (maximize: true or minimize: false). 00505 void SetOptimizationDirection(bool maximize); 00506 // Sets the optimization direction to minimize. 00507 void SetMinimization() { SetOptimizationDirection(false); } 00508 // Sets the optimization direction to maximize. 00509 void SetMaximization() { SetOptimizationDirection(true); } 00510 // Is the optimization direction set to maximize? 00511 bool maximization() const; 00512 // Is the optimization direction set to minimize? 00513 bool minimization() const; 00514 00515 // Returns the objective value of the best solution found so far. It 00516 // is the optimal objective value if the problem has been solved to 00517 // optimality. 00518 double Value() const; 00519 00520 // Returns the best objective bound. In case of minimization, it is 00521 // a lower bound on the objective value of the optimal integer 00522 // solution. Only available for discrete problems. 00523 double BestBound() const; 00524 00525 private: 00526 friend class MPSolver; 00527 friend class MPSolverInterface; 00528 friend class CBCInterface; 00529 friend class CLPInterface; 00530 friend class GLPKInterface; 00531 friend class SCIPInterface; 00532 00533 // Constructor. An objective points to a single MPSolverInterface 00534 // that is specified in the constructor. An objective cannot belong 00535 // to several models. 00536 // At construction, an MPObjective has no terms (which is equivalent 00537 // on having a coefficient of 0 for all variables), and an offset of 0. 00538 explicit MPObjective(MPSolverInterface* const interface) 00539 : interface_(interface), offset_(0.0), value_(0.0) {} 00540 00541 MPSolverInterface* const interface_; 00542 00543 // Mapping var -> coefficient. 00544 hash_map<const MPVariable*, double> coefficients_; 00545 // Constant term. 00546 double offset_; 00547 // The value of the objective function. 00548 double value_; 00549 00550 DISALLOW_COPY_AND_ASSIGN(MPObjective); 00551 }; 00552 00553 // The class for variables of a Mathematical Programming (MP) model. 00554 class MPVariable { 00555 public: 00556 // Returns the name of the variable. 00557 const string& name() const { return name_; } 00558 00559 // Sets the integrality requirement of the variable. 00560 void SetInteger(bool integer); 00561 // Returns the integrality requirement of the variable. 00562 bool integer() const { return integer_; } 00563 00564 // Returns the value of the variable in the current solution. 00565 double solution_value() const; 00566 00567 // Returns the index of the variable in the MPSolver::variables_. 00568 int index() const { return index_; } 00569 00570 // Returns the lower bound. 00571 double lb() const { return lb_; } 00572 // Returns the upper bound. 00573 double ub() const { return ub_; } 00574 // Sets the lower bound. 00575 void SetLB(double lb) { SetBounds(lb, ub_); } 00576 // Sets the upper bound. 00577 void SetUB(double ub) { SetBounds(lb_, ub); } 00578 // Sets both the lower and upper bounds. 00579 void SetBounds(double lb, double ub); 00580 00581 // Advanced usage: returns the reduced cost of the variable in the 00582 // current solution (only available for continuous problems). 00583 double reduced_cost() const; 00584 // Advanced usage: returns the basis status of the variable in the 00585 // current solution (only available for continuous problems). 00586 // @see MPSolver::BasisStatus. 00587 MPSolver::BasisStatus basis_status() const; 00588 00589 protected: 00590 friend class MPSolver; 00591 friend class MPSolverInterface; 00592 friend class CBCInterface; 00593 friend class CLPInterface; 00594 friend class GLPKInterface; 00595 friend class SCIPInterface; 00596 00597 // Constructor. A variable points to a single MPSolverInterface that 00598 // is specified in the constructor. A variable cannot belong to 00599 // several models. 00600 MPVariable(double lb, double ub, bool integer, const string& name, 00601 MPSolverInterface* const interface) 00602 : lb_(lb), ub_(ub), integer_(integer), name_(name), index_(-1), 00603 solution_value_(0.0), reduced_cost_(0.0), interface_(interface) {} 00604 00605 void set_index(int index) { index_ = index; } 00606 void set_solution_value(double value) { solution_value_ = value; } 00607 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; } 00608 00609 private: 00610 double lb_; 00611 double ub_; 00612 bool integer_; 00613 const string name_; 00614 int index_; 00615 double solution_value_; 00616 double reduced_cost_; 00617 MPSolverInterface* const interface_; 00618 DISALLOW_COPY_AND_ASSIGN(MPVariable); 00619 }; 00620 00621 // The class for constraints of a Mathematical Programming (MP) model. 00622 // A constraint is represented as a linear equation or inequality. 00623 class MPConstraint { 00624 public: 00625 // Returns the name of the constraint. 00626 const string& name() const { return name_; } 00627 00628 // Clears all variables and coefficients. Does not clear the bounds. 00629 void Clear(); 00630 00631 // Sets the coefficient of the variable on the constraint. 00632 void SetCoefficient(const MPVariable* const var, double coeff); 00633 // Gets the coefficient of a given variable on the constraint (which 00634 // is 0 if the variable does not appear in the constraint). 00635 double GetCoefficient(const MPVariable* const var) const; 00636 00637 // Returns the lower bound. 00638 double lb() const { return lb_; } 00639 // Returns the upper bound. 00640 double ub() const { return ub_; } 00641 // Sets the lower bound. 00642 void SetLB(double lb) { SetBounds(lb, ub_); } 00643 // Sets the upper bound. 00644 void SetUB(double ub) { SetBounds(lb_, ub); } 00645 // Sets both the lower and upper bounds. 00646 void SetBounds(double lb, double ub); 00647 00648 // Returns the constraint's activity in the current solution: 00649 // sum over all terms of (coefficient * variable value) 00650 double activity() const; 00651 00652 // Returns the index of the constraint in the MPSolver::constraints_. 00653 // TODO(user): move to protected. 00654 int index() const { return index_; } 00655 00656 // Advanced usage: returns the dual value of the constraint in the 00657 // current solution (only available for continuous problems). 00658 double dual_value() const; 00659 // Advanced usage: returns the basis status of the slack variable 00660 // associated with the constraint (only available for continuous 00661 // problems). 00662 // @see MPSolver::BasisStatus. 00663 MPSolver::BasisStatus basis_status() const; 00664 00665 protected: 00666 friend class MPSolver; 00667 friend class MPSolverInterface; 00668 friend class CBCInterface; 00669 friend class CLPInterface; 00670 friend class GLPKInterface; 00671 friend class SCIPInterface; 00672 00673 // Constructor. A constraint points to a single MPSolverInterface 00674 // that is specified in the constructor. A constraint cannot belong 00675 // to several models. 00676 MPConstraint(double lb, 00677 double ub, 00678 const string& name, 00679 MPSolverInterface* const interface) 00680 : lb_(lb), ub_(ub), name_(name), index_(-1), dual_value_(0.0), 00681 activity_(0.0), interface_(interface) {} 00682 00683 void set_index(int index) { index_ = index; } 00684 void set_activity(double activity) { activity_ = activity; } 00685 void set_dual_value(double dual_value) { dual_value_ = dual_value; } 00686 00687 private: 00688 // Returns true if the constraint contains variables that have not 00689 // been extracted yet. 00690 bool ContainsNewVariables(); 00691 00692 // Mapping var -> coefficient. 00693 hash_map<const MPVariable*, double> coefficients_; 00694 00695 // The lower bound for the linear constraint. 00696 double lb_; 00697 // The upper bound for the linear constraint. 00698 double ub_; 00699 // Name. 00700 const string name_; 00701 int index_; 00702 double dual_value_; 00703 double activity_; 00704 MPSolverInterface* const interface_; 00705 DISALLOW_COPY_AND_ASSIGN(MPConstraint); 00706 }; 00707 00708 00709 // This class stores parameter settings for LP and MIP solvers. 00710 // Some parameters are marked as advanced: do not change their values 00711 // unless you know what you are doing! 00712 // 00713 // For developers: how to add a new parameter: 00714 // - Add the new Foo parameter in the DoubleParam or IntegerParam enum. 00715 // - If it is a categorical param, add a FooValues enum. 00716 // - Decide if the wrapper should define a default value for it: yes 00717 // if it controls the properties of the solution (example: 00718 // tolerances) or if it consistently improves performance, no 00719 // otherwise. If yes, define kDefaultFoo. 00720 // - Add a foo_value_ member and, if no default value is defined, a 00721 // foo_is_default_ member. 00722 // - Add code to handle Foo in Set...Param, Reset...Param, 00723 // Get...Param, Reset and the constructor. 00724 // - In class MPSolverInterface, add a virtual method SetFoo, add it 00725 // to SetCommonParameters or SetMIPParameters, and implement it for 00726 // each solver. Sometimes, parameters need to be implemented 00727 // differently, see for example the INCREMENTALITY implementation. 00728 // - Add a test in linear_solver_test.cc. 00729 // 00730 // TODO(user): store the parameter values in a protocol buffer 00731 // instead. We need to figure out how to deal with the subtleties of 00732 // the default values. 00733 class MPSolverParameters { 00734 public: 00735 // Enumeration of parameters that take continuous values. 00736 enum DoubleParam { 00737 // Limit for relative MIP gap. 00738 RELATIVE_MIP_GAP = 0, 00739 // Advanced usage: tolerance for primal feasibility of basic 00740 // solutions. This does not control the integer feasibility 00741 // tolerance of integer solutions for MIP or the tolerance used 00742 // during presolve. 00743 PRIMAL_TOLERANCE = 1, 00744 // Advanced usage: tolerance for dual feasibility of basic solutions. 00745 DUAL_TOLERANCE = 2 00746 }; 00747 00748 // Enumeration of parameters that take integer or categorical values. 00749 enum IntegerParam { 00750 // Advanced usage: presolve mode. 00751 PRESOLVE = 1000, 00752 // Algorithm to solve linear programs. 00753 LP_ALGORITHM = 1001, 00754 // Advanced usage: incrementality from one solve to the next. 00755 INCREMENTALITY = 1002 00756 }; 00757 00758 // For each categorical parameter, enumeration of possible values. 00759 enum PresolveValues { 00760 PRESOLVE_OFF = 0, // Presolve is off. 00761 PRESOLVE_ON = 1 // Presolve is on. 00762 }; 00763 00764 enum LpAlgorithmValues { 00765 DUAL = 10, // Dual simplex. 00766 PRIMAL = 11, // Primal simplex. 00767 BARRIER = 12 // Barrier algorithm. 00768 }; 00769 00770 enum IncrementalityValues { 00771 // Start solve from scratch. 00772 INCREMENTALITY_OFF = 0, 00773 // Reuse results from previous solve as much as the underlying 00774 // solver allows. 00775 INCREMENTALITY_ON = 1 00776 }; 00777 00778 // @{ 00779 // Placeholder value to indicate that a parameter is set to 00780 // the default value defined in the wrapper. 00781 static const double kDefaultDoubleParamValue; 00782 static const int kDefaultIntegerParamValue; 00783 // @} 00784 00785 // @{ 00786 // Placeholder value to indicate that a parameter is unknown. 00787 static const double kUnknownDoubleParamValue; 00788 static const int kUnknownIntegerParamValue; 00789 // @} 00790 00791 // @{ 00792 // Default values for parameters. Only parameters that define the 00793 // properties of the solution returned need to have a default value 00794 // (that is the same for all solvers). You can also define a default 00795 // value for performance parameters when you are confident it is a 00796 // good choice (example: always turn presolve on). 00797 static const double kDefaultRelativeMipGap; 00798 static const double kDefaultPrimalTolerance; 00799 static const double kDefaultDualTolerance; 00800 static const PresolveValues kDefaultPresolve; 00801 static const IncrementalityValues kDefaultIncrementality; 00802 // @} 00803 00804 // The constructor sets all parameters to their default value. 00805 MPSolverParameters(); 00806 00807 // @{ 00808 // Sets a parameter to a specific value. 00809 void SetDoubleParam(MPSolverParameters::DoubleParam param, double value); 00810 void SetIntegerParam(MPSolverParameters::IntegerParam param, int value); 00811 // @} 00812 00813 // @{ 00814 // Sets a parameter to its default value (default value defined 00815 // in MPSolverParameters if it exists, otherwise the default value 00816 // defined in the underlying solver). 00817 void ResetDoubleParam(MPSolverParameters::DoubleParam param); 00818 void ResetIntegerParam(MPSolverParameters::IntegerParam param); 00819 // Sets all parameters to their default value. 00820 void Reset(); 00821 // @} 00822 00823 // @{ 00824 // Returns the value of a parameter. 00825 double GetDoubleParam(MPSolverParameters::DoubleParam param) const; 00826 int GetIntegerParam(MPSolverParameters::IntegerParam param) const; 00827 // @} 00828 00829 private: 00830 // @{ 00831 // Parameter value for each parameter. 00832 // @see DoubleParam 00833 // @see IntegerParam 00834 double relative_mip_gap_value_; 00835 double primal_tolerance_value_; 00836 double dual_tolerance_value_; 00837 int presolve_value_; 00838 int lp_algorithm_value_; 00839 int incrementality_value_; 00840 // @} 00841 00842 // Boolean value indicating whether each parameter is set to the 00843 // solver's default value. Only parameters for which the wrapper 00844 // does not define a default value need such an indicator. 00845 bool lp_algorithm_is_default_; 00846 00847 DISALLOW_COPY_AND_ASSIGN(MPSolverParameters); 00848 }; 00849 00850 00851 // This class wraps the actual mathematical programming solvers. Each 00852 // solver (CLP, CBC, GLPK, SCIP) has its own interface class that 00853 // derives from this abstract class. This class is never directly 00854 // accessed by the user. 00855 // @see cbc_interface.cc 00856 // @see clp_interface.cc 00857 // @see glpk_interface.cc 00858 // @see scip_interface.cc 00859 class MPSolverInterface { 00860 public: 00861 enum SynchronizationStatus { 00862 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in 00863 // sync for the model nor for the solution. 00864 MUST_RELOAD, 00865 // The underlying solver and MPSolver are in sync for the model 00866 // but not for the solution: the model has changed since the 00867 // solution was computed last. 00868 MODEL_SYNCHRONIZED, 00869 // The underlying solver and MPSolver are in sync for the model and 00870 // the solution. 00871 SOLUTION_SYNCHRONIZED 00872 }; 00873 00874 // When the underlying solver does not provide the number of simplex 00875 // iterations. 00876 static const int64 kUnknownNumberOfIterations = -1; 00877 // When the underlying solver does not provide the number of 00878 // branch-and-bound nodes. 00879 static const int64 kUnknownNumberOfNodes = -1; 00880 // When the index of a variable or constraint has not been assigned yet. 00881 static const int kNoIndex = -1; 00882 00883 // Constructor. The user will access the MPSolverInterface through the 00884 // MPSolver passed as argument. 00885 explicit MPSolverInterface(MPSolver* const solver); 00886 virtual ~MPSolverInterface(); 00887 00888 // ----- Solve ----- 00889 // Solves problem with specified parameter values. Returns true if the 00890 // solution is optimal. Calls WriteModelToPredefinedFiles 00891 // to allow the user to write the model to a file. 00892 virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0; 00893 00894 // ----- Model modifications and extraction ----- 00895 // Resets extracted model. 00896 virtual void Reset() = 0; 00897 00898 // Sets the optimization direction (min/max). 00899 virtual void SetOptimizationDirection(bool maximize) = 0; 00900 00901 // Modifies bounds of an extracted variable. 00902 virtual void SetVariableBounds(int index, double lb, double ub) = 0; 00903 00904 // Modifies integrality of an extracted variable. 00905 virtual void SetVariableInteger(int index, bool integer) = 0; 00906 00907 // Modify bounds of an extracted variable. 00908 virtual void SetConstraintBounds(int index, double lb, double ub) = 0; 00909 00910 // Adds a linear constraint. 00911 virtual void AddRowConstraint(MPConstraint* const ct) = 0; 00912 00913 // Add a variable. 00914 virtual void AddVariable(MPVariable* const var) = 0; 00915 00916 // Changes a coefficient in a constraint. 00917 virtual void SetCoefficient(MPConstraint* const constraint, 00918 const MPVariable* const variable, 00919 double new_value, 00920 double old_value) = 0; 00921 00922 // Clears a constraint from all its terms. 00923 virtual void ClearConstraint(MPConstraint* const constraint) = 0; 00924 00925 // Changes a coefficient in the linear objective. 00926 virtual void SetObjectiveCoefficient(const MPVariable* const variable, 00927 double coefficient) = 0; 00928 00929 // Changes the constant term in the linear objective. 00930 virtual void SetObjectiveOffset(double value) = 0; 00931 00932 // Clears the objective from all its terms. 00933 virtual void ClearObjective() = 0; 00934 00935 // ------ Query statistics on the solution and the solve ------ 00936 // Returns the number of simplex iterations. 00937 virtual int64 iterations() const = 0; 00938 // Returns the number of branch-and-bound nodes 00939 virtual int64 nodes() const = 0; 00940 // Returns the best objective bound. Only available for discrete problems. 00941 virtual double best_objective_bound() const = 0; 00942 // Returns the objective value of the best solution found so far. 00943 double objective_value() const; 00944 00945 // Returns the basis status of a row. 00946 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0; 00947 // Returns the basis status of a constraint. 00948 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0; 00949 00950 // Checks whether the solution is synchronized with the model, 00951 // i.e. whether the model has changed since the solution was 00952 // computed last. 00953 void CheckSolutionIsSynchronized() const; 00954 // Checks whether a feasible solution exists. 00955 virtual void CheckSolutionExists() const; 00956 // Handy shortcut to do both checks above (it is often used). 00957 void CheckSolutionIsSynchronizedAndExists() const { 00958 CheckSolutionIsSynchronized(); 00959 CheckSolutionExists(); 00960 } 00961 // Checks whether information on the best objective bound exists. 00962 virtual void CheckBestObjectiveBoundExists() const; 00963 00964 // ----- Misc ----- 00965 // Writes model to a file. 00966 virtual void WriteModel(const string& filename) = 0; 00967 00968 // Queries problem type. For simplicity, the distinction between 00969 // continuous and discrete is based on the declaration of the user 00970 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING 00971 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of 00972 // the model. 00973 // Returns true if the problem is continuous. 00974 virtual bool IsContinuous() const = 0; 00975 // Returns true if the problem is continuous and linear. 00976 virtual bool IsLP() const = 0; 00977 // Returns true if the problem is discrete and linear. 00978 virtual bool IsMIP() const = 0; 00979 00980 // Returns the index of the last variable extracted. 00981 int last_variable_index() const { 00982 return last_variable_index_; 00983 } 00984 00985 // Returns the boolean indicating the verbosity of the solver output. 00986 bool quiet() const { 00987 return quiet_; 00988 } 00989 // Sets the boolean indicating the verbosity of the solver output. 00990 void set_quiet(bool quiet_value) { 00991 quiet_ = quiet_value; 00992 } 00993 00994 // Returns the result status of the last solve. 00995 MPSolver::ResultStatus result_status() const { 00996 CheckSolutionIsSynchronized(); 00997 return result_status_; 00998 } 00999 01000 // Returns a string describing the underlying solver and its version. 01001 virtual string SolverVersion() const = 0; 01002 01003 // Returns the underlying solver. 01004 virtual void* underlying_solver() = 0; 01005 01006 // Computes exact condition number. Only available for continuous 01007 // problems and only implemented in GLPK. 01008 virtual double ComputeExactConditionNumber() const = 0; 01009 01010 friend class MPSolver; 01011 01012 // To access the maximize_ bool. See MPObjective::SetOptimizationDirection() 01013 // in the .cc. 01014 friend class MPObjective; 01015 01016 protected: 01017 MPSolver* const solver_; 01018 // Indicates whether the model and the solution are synchronized. 01019 SynchronizationStatus sync_status_; 01020 // Indicates whether the solve has reached optimality, 01021 // infeasibility, a limit, etc. 01022 MPSolver::ResultStatus result_status_; 01023 // Optimization direction. 01024 bool maximize_; 01025 01026 // Index in MPSolver::variables_ of last constraint extracted. 01027 int last_constraint_index_; 01028 // Index in MPSolver::constraints_ of last variable extracted. 01029 int last_variable_index_; 01030 01031 // The value of the objective function. 01032 double objective_value_; 01033 01034 // Boolean indicator for the verbosity of the solver output. 01035 bool quiet_; 01036 01037 // Index of dummy variable created for empty constraints or the 01038 // objective offset. 01039 static const int kDummyVariableIndex; 01040 01041 // Writes out the model to a file specified by the 01042 // --solver_write_model command line argument or 01043 // MPSolver::set_write_model_filename. 01044 // The file is written by each solver interface (CBC, CLP, GLPK, SCIP) and 01045 // each behaves a little differently. 01046 // If filename ends in ".lp", then the file is written in the 01047 // LP format (except for the CLP solver that does not support the LP 01048 // format). In all other cases it is written in the MPS format. 01049 void WriteModelToPredefinedFiles(); 01050 01051 // Extracts model stored in MPSolver. 01052 void ExtractModel(); 01053 // Extracts the variables that have not been extracted yet. 01054 virtual void ExtractNewVariables() = 0; 01055 // Extracts the constraints that have not been extracted yet. 01056 virtual void ExtractNewConstraints() = 0; 01057 // Extracts the objective. 01058 virtual void ExtractObjective() = 0; 01059 // Resets the extraction information. 01060 void ResetExtractionInformation(); 01061 // Change synchronization status from SOLUTION_SYNCHRONIZED to 01062 // MODEL_SYNCHRONIZED. To be used for model changes. 01063 void InvalidateSolutionSynchronization(); 01064 01065 // Sets parameters common to LP and MIP in the underlying solver. 01066 void SetCommonParameters(const MPSolverParameters& param); 01067 // Sets MIP specific parameters in the underlying solver. 01068 void SetMIPParameters(const MPSolverParameters& param); 01069 // Sets all parameters in the underlying solver. 01070 virtual void SetParameters(const MPSolverParameters& param) = 0; 01071 // Sets an unsupported double parameter. 01072 void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param) const; 01073 // Sets an unsupported integer parameter. 01074 void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param) const; 01075 // Sets a supported double parameter to an unsupported value. 01076 void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, 01077 int value) const; 01078 // Sets a supported integer parameter to an unsupported value. 01079 void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, 01080 double value) const; 01081 // Sets each parameter in the underlying solver. 01082 virtual void SetRelativeMipGap(double value) = 0; 01083 virtual void SetPrimalTolerance(double value) = 0; 01084 virtual void SetDualTolerance(double value) = 0; 01085 virtual void SetPresolveMode(int value) = 0; 01086 virtual void SetLpAlgorithm(int value) = 0; 01087 }; 01088 01089 } // namespace operations_research 01090 01091 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_