Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark mode
Gurobi Optimizer Reference Manual
Light LogoDark Logo

Concepts

Features

Reference

Gurobi
Back to top

C++ API Overview#

Environments#

The first step in using the Gurobi C++ interface is to create anenvironment object. Environments are represented using theGRBEnv class. An environment acts as the container for alldata associated with a set of optimization runs. You will generally onlyneed one environment object in your program.

For more advanced use cases, you can use an empty environment to createan uninitialized environment and then, programmatically, set allrequired options for your specific requirements. For further details seetheEnvironment section.

Models#

You can create one or more optimization models within an environment.Each model is represented as an object of classGRBModel. Amodel consists of a set of decision variables (objects of classGRBVar), a linear or quadratic objective function on thosevariables (specified usingGRBModel::setObjective), and aset of constraints on these variables (objects of classGRBConstr,GRBQConstr,GRBSOS, orGRBGenConstr). Each variable has an associated lower bound,upper bound, and type (continuous, binary, etc.). Each linear orquadratic constraint has an associated sense (less-than-or-equal,greater-than-or-equal, or equal), and right-hand side value. Refer tothis section for more informationon variables, constraints, and objectives.

Linear constraints are specified by building linear expressions (objectsof classGRBLinExpr), and then specifying relationshipsbetween these expressions (for example, requiring that one expression beequal to another). Quadratic constraints are built in a similar fashion,but using quadratic expressions (objects of classGRBQuadExpr) instead.

An optimization model may be specified all at once, by loading the modelfrom a file (using the appropriateGRBModel constructor),or built incrementally, by first constructing an empty object of classGRBModel and then subsequently callingGRBModel::addVar orGRBModel::addVars to addadditional variables, andGRBModel::addConstr,GRBModel::addQConstr,GRBModel::addSOS, or anyof theGRBModel::addGenConstr*methods to add constraints. Models are dynamic entities; you can alwaysadd or remove variables or constraints.SeeBuild a modelfor general guidance ormip1_c++.cppfor a specific example.

We often refer to theclass of an optimization model. At the highestlevel, a model can be continuous or discrete, depending on whether themodeling elements present in the model require discrete decisions to bemade. Among continuous models…

  • A model with a linear objective function, linear constraints, andcontinuous variables is aLinear Program (LP).

  • If the objective is quadratic, the model is aQuadratic Program(QP).

  • If any of the constraints are quadratic, the model is aQuadratically-Constrained Program (QCP). We sometimes refer to afew special cases of QCP: QCPs with convex constraints, QCPs withnon-convex constraints,bilinear programs, andSecond-Order ConePrograms (SOCP).

  • If any of the constraints are non-linear (chosen from among theavailable general constraints), the model is aNon-Linear Program(NLP).

A model that contains any integer variables, semi-continuous variables,semi-integer variables, Special Ordered Set (SOS) constraints, orgeneral constraints, is discrete, and is referred to as aMixed IntegerProgram (MIP). The special cases of MIP, which are the discreteversions of the continuous models types we’ve already described, are…

  • Mixed Integer Linear Programs (MILP)

  • Mixed Integer Quadratic Programs (MIQP)

  • Mixed Integer Quadratically-Constrained Programs (MIQCP)

  • Mixed Integer Second-Order Cone Programs (MISOCP)

  • Mixed Integer Non-Linear Programs (MINLP)

The Gurobi Optimizer handles all of these model classes. Note that theboundaries between them aren’t as clear as one might like, because weare often able to transform a model from one class to a simpler class.

Solving a Model#

Once you have built a model, you can callGRBModel::optimizeto compute a solution. By default,optimize will use theconcurrent optimizer to solve LP models, thebarrier algorithm to solve QP models with convex objectives and QCPmodels with convex constraints, and the branch-and-cut algorithmotherwise. The solution is stored in a set ofattributes of the model.These attributes can be queried using a set of attribute query methodson theGRBModel,GRBVar,GRBConstr,GRBQConstr,GRBSOS,andGRBGenConstr classes.

The Gurobi algorithms keep careful track of the state of the model, socalls toGRBModel::optimize will only perform furtheroptimization if relevant data has changed since the model was lastoptimized. If you would like to discard previously computed solutioninformation and restart the optimization from scratch without changingthe model, you can callGRBModel::reset.

After a MIP model has been solved, you can callGRBModel::fixedModel to compute the associatedfixedmodel. This model is identical to the original, except that the integervariables are fixed to their values in the MIP solution. If your modelcontains SOS constraints, some continuous variables that appear in theseconstraints may be fixed as well. In some applications, it can be usefulto compute information on this fixed model (e.g., dual variables,sensitivity information, etc.), although you should be careful in howyou interpret this information.

Multiple Solutions, Objectives, and Scenarios#

By default, the Gurobi Optimizer assumes that your goal is to find oneproven optimal solution to a single model with a single objectivefunction. Gurobi provides the following features that allow you to relaxthese assumptions:

Infeasible Models#

You have a few options if a model is found to be infeasible. You can tryto diagnose the cause of the infeasibility, attempt to repair theinfeasibility, or both. To obtain information that can be useful fordiagnosing the cause of an infeasibility, callGRBModel::computeIIS to compute an Irreducible InconsistentSubsystem (IIS). This method can be used for both continuous and MIPmodels, but you should be aware that the MIP version can be quiteexpensive. This method populates a set of IIS attributes.

To attempt to repair an infeasibility, callGRBModel::feasRelax to compute a feasibility relaxation forthe model. This relaxation allows you to find a solution that minimizesthe magnitude of the constraint violation.You will find more information about this feature in sectionRelaxing for Feasibility. Examples are discussed inDiagnose and cope with infeasibility.

Querying and Modifying Attributes#

Most of the information associated with a Gurobi model is stored in aset of attributes. Some attributes are associated with the variables ofthe model, some with the constraints of the model, and some with themodel itself. To give a simple example, solving an optimization modelcauses theX variable attribute to be populated. Attributes such asX that are computed by the Gurobi optimizer cannot be modifieddirectly by the user, while others, such as the variable lower bound(theLB attribute) can.

Attributes are queried usingGRBVar::get,GRBConstr::get,GRBQConstr::get,GRBSOS::get,GRBGenConstr::get, orGRBModel::get, and modified usingGRBVar::set,GRBConstr::set,GRBQConstr::set,GRBGenConstr::set, orGRBModel::set. Attributesare grouped into a set of enums by type (GRB_CharAttr,GRB_DoubleAttr,GRB_IntAttr,GRB_StringAttr). Theget() andset() methods areoverloaded, so the type of the attribute determines the type of thereturned value. Thus,constr.get(GRB.DoubleAttr.RHS) returns adouble, whileconstr.get(GRB.CharAttr.Sense) returns a char.

If you wish to retrieve attribute values for a set of variables orconstraints, it is usually more efficient to use the array methods onthe associatedGRBModel object. MethodGRBModel::get includes signatures that allow you to query ormodify attribute values for arrays of variables or constraints.

The full list of attributescan be found in theAttributes section of thisdocument. Examples of how to query and set attributes can also be foundinthis section.

Additional Model Modification Information#

Most modifications to an existing model are done through the attributeinterface (e.g., changes to variable bounds, constraint right-handsides, etc.). The main exceptions are modifications to the constraintmatrix and the objective function.

The constraint matrix can be modified in a few ways. The first is tocall thechgCoeffs method on aGRBModel object to change individual matrix coefficients.This method can be used to modify the value of an existing non-zero, toset an existing non-zero to zero, or to create a new non-zero. Theconstraint matrix is also modified when you remove a variable orconstraint from the model (through theGRBModel::removemethod). The non-zero values associated with the deleted constraint orvariable are removed along with the constraint or variable itself.

The model objective function can also be modified in a few ways. Theeasiest is to build an expression that captures the objective function(aGRBLinExpr orGRBQuadExpr object), and thenpass that expression to methodGRBModel::setObjective. Ifyou wish to modify the objective, you can simply callGRBModel::setObjectiveagain with a newGRBLinExpr orGRBQuadExpr object.

For linear objective functions, an alternative toGRBModel::setObjective is to usetheObj variable attribute to modify individual linear objectivecoefficients.

If your variables have piecewise-linear objectives, you can specify them usingtheGRBModel::setPWLObj method. Call this method once for eachrelevant variable. The Gurobi simplex solver includes algorithmic support forconvex piecewise-linear objective functions, so for continuous models youshould see a substantial performance benefit from using this feature. To cleara previously specified piecewise-linear objective function, simply set theObj attribute on the corresponding variable to 0.

Some examples are discussed inModify a model.

Lazy Updates#

One important item to note about model modification in the Gurobioptimizer is that it is performed in alazy fashion, meaning thatmodifications don’t affect the model immediately. Rather, they arequeued and applied later. If your program simply creates a model andsolves it, you will probably never notice this behavior. However, if youask for information about the model before your modifications have beenapplied, the details of the lazy update approach may be relevant to you.

As we just noted, model modifications (bound changes, right-hand sidechanges, objective changes, etc.) are placed in a queue. These queuedmodifications can be applied to the model in three different ways. Thefirst is by an explicit call toGRBModel::update. The secondis by a call toGRBModel::optimize. The third is by a calltoGRBModel::write to write out the model. The first casegives you fine-grained control over when modifications are applied. Thesecond and third make the assumption that you want all pendingmodifications to be applied before you optimize your model or write itto disk.

Why does the Gurobi interface behave in this manner? There are a fewreasons. The first is that this approach makes it much easier to performmultiple modifications to a model, since the model remains unchangedbetween modifications. The second is that processing model modificationscan be expensive, particularly in a Compute Server environment, wheremodifications require communication between machines. Thus, it is usefulto have visibility into exactly when these modifications are applied. Ingeneral, if your program needs to make multiple modifications to themodel, you should aim to make them in phases, where you make a set ofmodifications, then update, then make more modifications, then updateagain, etc. Updating after each individual modification can be extremelyexpensive.

If you forget to call update, your program won’t crash. Your query willsimply return the value of the requested data from the point of the lastupdate. If the object you tried to query didn’t exist, Gurobi will throwan exception with error codeNOT_IN_MODEL.

The semantics of lazy updates have changed since earlier Gurobiversions. While the vast majority of programs are unaffected by thischange, you can use theUpdateMode parameter to revertto the earlier behavior if you run into an issue.

Managing Parameters#

The Gurobi Optimizer provides a set of parameters that allow you tocontrol many of the details of the optimization process. Factors likefeasibility and optimality tolerances, choices of algorithms, strategiesfor exploring the MIP search tree, etc., can be controlled by modifyingGurobi parameters before beginning the optimization. Parameters can beof typeint,double, orstring.

The simplest way to set parameters is through theGRBModel::set method on the model object. Similarly,parameter values can be queried withGRBModel::get.

Parameters can also be set on the Gurobi environment object, usingGRBEnv::set. Note that each model gets its own copy of theenvironment when it is created, so parameter changes to the originalenvironment have no effect on existing models.

You can read a set of parameter settings from a file usingGRBEnv::readParams, or write the set of changed parametersusingGRBEnv::writeParams.

Refer to the exampleparams_c++.cpp whichis considered inChange parameters.

We also include an automated parameter tuning tool that explores manydifferent sets of parameter changes in order to find a set that improvesperformance. You can callGRBModel::tune to invoke thetuning tool on a model. Refer to theparameter tuning tool section for more information.

The full list of Gurobi parameters can be found in theParameters section.

Memory Management#

Memory management must always be considered in C++ programs. Inparticular, the Gurobi library and the user program share the same C++heap, so the user must be aware of certain aspects of how the Gurobilibrary uses this heap. The basic rules for managing memory when usingthe Gurobi Optimizer are as follows:

  • As with other dynamically allocated C++ objects,GRBEnvorGRBModel objects should be freed using the associateddestructors. In other words, given aGRBModel objectm, youshould calldeletem when you are no longer usingm.

  • Objects that are associated with a model (e.g.,GRBConstr,GRBQConstr,GRBSOS,GRBGenConstr, andGRBVar objects) aremanaged by the model. In particular, deleting a model will delete allof the associated objects. Similarly, removing an object from a model(usingGRBModel::remove) will also delete the object.

  • Some Gurobi methods return an array of objects or values. Forexample,GRBModel::addVars returns an array ofGRBVarobjects. It is the user’s responsibility to free the returned array(usingdelete[]). The reference manual indicates when a methodreturns a heap-allocated result.

One consequence of these rules is that you must be careful not to use anobject once it has been freed. This is no doubt quite clear forenvironments and models, where you call the destructors explicitly, butmay be less clear for constraints and variables, which are implicitlydeleted when the associated model is deleted.

Monitoring Progress - Logging and Callbacks#

Progress of the optimization can be monitored through Gurobi logging. Bydefault, Gurobi will send output to the screen. A few simple controlsare available for modifying the default logging behavior. If you wouldlike to direct output to a file as well as to the screen, specify thelog file name in theGRBEnv constructor. You can modify theLogFile parameter if you wish to redirect the log to adifferent file after creating the environment object. The frequency oflogging output can be controlled with theDisplayInterval parameter, and logging can be turned offentirely with theOutputFlag parameter. A detaileddescription of the Gurobi log file can be found in theLogging section.

More detailed progress monitoring can be done through theGRBCallback class. TheGRBModel::setCallbackmethod allows you to receive a periodic callback from the GurobiOptimizer. You do this by sub-classing theGRBCallbackabstract class, and writing your owncallback() method on thisclass. You can callGRBCallback::getDoubleInfo,GRBCallback::getIntInfo,GRBCallback::getStringInfo, orGRBCallback::getSolution from within the callback to obtainadditional information about the state of the optimization.Refer to the examplecallback_c++.cppwhich is discussed inCallbacks.

Modifying Solver Behavior - Callbacks#

Callbacks can also be used to modify the behavior of the Gurobioptimizer. The simplest control callback isGRBCallback::abort, which asks the optimizer to terminate atthe earliest convenient point. MethodGRBCallback::setSolution allows you to inject a feasiblesolution (or partial solution) during the solution of a MIP model.MethodsGRBCallback::addCut andGRBCallback::addLazy allow you to addcutting planes andlazy constraints during a MIP optimization, respectively (refer tothe exampletsp_c++.cpp). MethodGRBCallback::stopOneMultiObj allows you to interruptthe optimization process of one of theoptimization steps in a multi-objective MIP problem without stopping thehierarchical optimization process.

Batch Optimization#

Gurobi Compute Server enables programs to offload optimizationcomputations onto dedicated servers. The Gurobi Cluster Manager adds anumber of additional capabilities on top of this. One important one,batch optimization, allows you to build an optimization model withyour client program, submit it to a Compute Server cluster (through theCluster Manager), and later check on the status of the model andretrieve its solution. You can use aBatchobject tomake it easier to work with batches. For details on batches, pleaserefer to theBatch Optimization section.

Error Handling#

All of the methods in the Gurobi C++ library can throw an exception oftypeGRBException. When an exception occurs, additionalinformation on the error can be obtained by retrieving the error code(using methodGRBException::getErrorCode), or by retrieving theexception message (using methodGRBException::getMessage). The listof possible error return codes can be found in theError Codes table.

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp