Concepts
Features
Reference
The first step in using the Gurobi C optimizer is to create anenvironment, using theGRBloadenv call. The environment actsas a container for all data associated with a set of optimization runs.You will generally only need one environment in your program, even ifyou wish to work with multiple optimization models. Once you are donewith an environment, you should callGRBfreeenv to release theassociated resources.
For more advanced use cases, you can use theGRBemptyenvroutine to create an uninitialized environment and then,programmatically, set all required options for your specificrequirements. For further details see theEnvironment section.
You can create one or more optimization models within an environment. Amodel consists of a set of variables, a linear, quadratic, orpiecewise-linear objective function on those variables, and a set ofconstraints. Each variable has an associated lower bound, upper bound,type (continuous, binary, integer, semi-continuous, or semi-integer),and linear objective coefficient. Each linear constraint has anassociated sense (less-than-or-equal, greater-than-or-equal, or equal),and right-hand side value. Refer tothis section for more informationon variables and constraints.
An optimization model may be specified all at once, through theGRBloadmodel routine, or built incrementally, by first callingGRBnewmodel and then callingGRBaddvars to addvariables andGRBaddconstr,GRBaddqconstr,GRBaddsos, or any of theGRBaddgenconstr* methods to addconstraints. Models are dynamic entities; you can always add or deletevariables or constraints.SeeBuild a modelfor general guidance ormip1_c.cfor a specific example.
Specific variables and constraints are referred to throughout the GurobiC interface using their indices. Variable indices are assigned asvariables are added to the model, in a contiguous fashion. The same istrue for constraints. In adherence to C language conventions, indicesall start at 0.
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.
Once you have built a model, you can callGRBoptimize tocompute a solution. By default,GRBoptimize 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 as a set ofattributes of the model.The C interface contains an extensive set of routines for querying theseattributes.
The Gurobi algorithms keep careful track of the state of the model, socalls toGRBoptimize will only perform further optimization ifrelevant data has changed since the model was last optimized. If youwould like to discard previously computed solution information andrestart the optimization from scratch without changing the model, youcan callGRBreset.
After a MIP model has been solved, you can callGRBfixmodel tocompute the associatedfixed model. This model is identical to theoriginal, except that the integer variables are fixed to their values inthe MIP solution. If your model contains SOS constraints, somecontinuous variables that appear in these constraints may be fixed aswell. In some applications, it can be useful to compute information onthis fixed model (e.g., dual variables, sensitivity information, etc.),although you should be careful in how you interpret this information.
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:
Solution Pool: Allows you to find moresolutions (refer to examplepoolsearch_c.c).
Multiple Scenarios: Allows you to findsolutions to multiple, related models(refer to examplemultiscenario_c.c).
Multiple Objectives: Allows you tospecify multiple objective functions and control the trade-offbetween them(refer to examplemultiobj_c.c).
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, callGRBcomputeIISto compute an Irreducible Inconsistent Subsystem (IIS). This routine canbe used for both continuous and MIP models, but you should be aware thatthe MIP version can be quite expensive. This routine populates a set ofIIS attributes.
To attempt to repair an infeasibility, callGRBfeasrelax tocompute a feasibility relaxation for the model. This relaxation allowsyou to find a solution that minimizes the magnitude of the constraintviolation.You will find more information about this feature in sectionRelaxing for Feasibility. Examples are discussed inDiagnose and cope with infeasibility.
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 boundarray (theLB attribute) can.
The Gurobi C interface contains an extensive set of routines forquerying or modifying attribute values. The exact routine to use for aparticular attribute depends on the type of the attribute. As mentionedearlier, attributes can be either variable attributes, constraintattributes, or model attributes. Variable and constraint attributes arearrays, and use a set of array attribute routines. Model attributes arescalars, and use a set of scalar routines. Attribute values canadditionally be of typechar,int,double, orstring (reallychar *).
Scalar model attributes are accessed through a set ofGRBget*attr()routines (e.g.,GRBgetintattr). In addition, those modelattributes that can be set directly by the user (e.g., the objectivesense) may be modified through theGRBset*attr() routines (e.g.,GRBsetdblattr).
Array attributes are accessed through three sets of routines. The firstset, theGRBget*attrarray() routines (e.g.,GRBgetcharattrarray) return a contiguous sub-array of theattribute array, specified using the index of the first member and thelength of the desired sub-array. The second set, theGRBget*attrelement() routines (e.g.,GRBgetcharattrelement) return a single entry from theattribute array. Finally, theGRBget*attrlist() routines (e.g.,GRBgetdblattrlist) retrieve attribute values for a list ofindices.
Array attributes that can be set by the user are modified through theGRBset*attrarray(),GRBset*attrelement(), andGRBset*attrlist() routines.
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.
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 constraintsthemselves, and to the quadratic and piecewise-linear portions of theobjective function.
The constraint matrix can be modified in a few ways. The first is tocallGRBchgcoeffs to change individual matrix coefficients.This routine 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 constraints (throughGRBdelconstrs) or variables (throughGRBdelvars).The non-zero values associated with the deleted constraints or variablesare removed along with the constraints or variables themselves.
Quadratic objective terms are added to the objective function using theGRBaddqpterms routine. You can add a list of quadratic termsin one call, or you can add terms incrementally through multiple calls.TheGRBdelq routine allows you to delete all quadratic termsfrom the model. Note that quadratic models will typically have bothquadratic and linear terms. Linear terms are entered and modifiedthrough theObj attribute, in the same way that they are handledfor models with purely linear objective functions.
If your variables have piecewise-linear objectives, you can specify themusing theGRBsetpwlobj routine. Call this routine once foreach relevant variable. The Gurobi simplex solver includes algorithmicsupport for convex piecewise-linear objective functions, so forcontinuous models you should see a substantial performance benefit fromusing this feature. To clear a previously specified piecewise-linearobjective function, simply set theObj attribute on thecorresponding variable to 0.
Some examples are discussed inModify a model.
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 toGRBupdatemodel. The second isby a call toGRBoptimize. The third is by a call toGRBwrite to write out the model. The first case gives youfine-grained control over when modifications are applied. The second andthird make the assumption that you want all pending modifications to beapplied before you optimize your model or write it to 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 then, you’ll getanINDEX_OUT_OF_RANGE error instead.
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.
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 are setusing theGRBset*param() routines (e.g.,GRBsetintparam).Current values can be retrieved with theGRBget*param() routines(e.g.,GRBgetdblparam). Parameters can be of typeint,double, orchar * (string). You can also read a set of parametersettings from a file usingGRBreadparams, or write the set ofchanged parameters usingGRBwriteparams.Refer to the exampleparams_c.c 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 callGRBtunemodel to invoke the tuningtool on a model. Refer to theparameter tuning toolsection for more information.
Note that a model gets its own copy of theenvironment when it is created. Changes to the original environment haveno effect on the copy, and vice versa. UseGRBgetenv toretrieve the environment associated with a model if you would like tochange the parameter value for that model.
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 inGRBloadenv when you create your environment.You can modify theLogFile parameter if you wish toredirect the log to a different file after creating the environment. Thefrequency of logging 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 the Gurobicallback function. TheGRBsetcallbackfunc routine allows youto install a function that the Gurobi Optimizer will call regularlyduring the optimization process. You can callGRBcbget fromwithin the callback to obtain additional information about the state ofthe optimization.Refer to the examplecallback_c.cwhich is discussed inCallbacks.
Callbacks can also be used to modify the behavior of the Gurobioptimizer. If you call routineGRBterminate from within acallback, for example, the optimizer will terminate at the earliestconvenient point. RoutineGRBcbsolution allows you to inject afeasible solution (or partial solution) during the solution of a MIPmodel. RoutinesGRBcbcut andGRBcblazy allow you toaddcutting planes andlazy constraints during a MIP optimization,respectively (refer to the exampletsp_c.c).RoutineGRBcbstoponemultiobj allows you tointerrupt the optimization process of one of theoptimization steps in a multi-objective MIP problem without stopping thehierarchical optimization process.
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.
Most of the Gurobi C library routines return an integer error code. Azero return value indicates that the routine completed successfully,while a non-zero value indicates that an error occurred. The list ofpossible error return codes can be found in theError Codes table.
When an error occurs, additional information on the error can beobtained by callingGRBgeterrormsg.
Help and Feedback