Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

.NET API Overview#

Environments#

The first step in using the Gurobi .NET interface is to create anenvironment object. Environments are represented using theGRBEnv class. An environment acts as the container forall data associated with a set of optimization runs. You will generallyonly need 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. A model consists of a set of decisionvariables (objects of classGRBVar), a linear orquadratic objective function on those variables (specified usingGRBModel.SetObjective), and a set of constraints on thesevariables (objects of classGRBConstr,GRBQConstr,GRBSOS, orGRBGenConstr). Each variable has an associated lowerbound, 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 appropriateGRBModelconstructor), or built incrementally, by first constructing an emptyobject of classGRBModel and then subsequently callingGRBModel.AddVar orGRBModel.AddVars to addadditional variables, andGRBModel.AddConstr,GRBModel.AddQConstr,GRBModel.AddSOS, orany of theGRBModel.AddGenConstr*methods to add additional constraints. Models are dynamic entities; youcan always add or remove variables or constraints.SeeBuild a modelfor general guidance ormip1_cs.csfor 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.Optimize to 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 IrreducibleInconsistent Subsystem (IIS). This method can be used for bothcontinuous and MIP models, but you should be aware that the MIP versioncan be quite expensive. This method populates a set of IIS attributes.

To attempt to repair an infeasibility, callGRBModel.FeasRelax to compute a feasibility relaxationfor the model. This relaxation allows you to find a solution thatminimizes the 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 can be accessed in two ways in the .NET interface. Theeasiest is through .NET properties. To query or modify theLBattribute on variablev, you would usev.LB orv.LB=0,respectively. Attributes can also be queried usingGRBVar.Get,GRBConstr.Get,GRBQConstr.Get,GRBSOS.Get,GRBGenConstr.Get, orGRBModel.Get, andmodified usingGRBVar.Set,GRBConstr.Set,GRBQConstr.Set,GRBGenConstr.Set, orGRBModel.Set. Attributes are grouped into a set of enumsby type (GRB.CharAttr,GRB.DoubleAttr,GRB.IntAttr,GRB.StringAttr). TheGet() andSet() methods are overloaded, so the type of theattribute determines the type of the returned value. Thus,constr.Get(GRB.DoubleAttr.RHS) returns a double, 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 queryor modify attribute values for one-, two-, and three-dimensional arraysof 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 to the objective function.

The constraint matrix can be modified in a few ways. The first is tocall theChgCoeff method on aGRBModel object to change individual matrixcoefficients. This method can be used to modify the value of an existingnon-zero, to set an existing non-zero to zero, or to create a newnon-zero. The constraint matrix is also modified when you remove avariable or constraint from the model (through theGRBModel.Remove method). The non-zero values associatedwith the deleted constraint or variable are removed along with theconstraint 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 then pass that expression to methodGRBModel.SetObjective. If you wish to modify theobjective, you can simply callGRBModel.SetObjective again with a newGRBLinExpr orGRBQuadExpr object.

For linear objective functions, an alternative toGRBModel.SetObjective is touse theObj variable attribute to modify individual linear objectivecoefficients.

If your variables have piecewise-linear objectives, you can specify themusing theGRBModel.SetPWLObj method. Call this methodonce for each relevant variable. The Gurobi simplex solver includesalgorithmic support for convex piecewise-linear objective functions, sofor continuous models you should see a substantial performance benefitfrom using this feature. To clear a previously specifiedpiecewise-linear objective function, simply set theObj attribute onthe 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. Thesecond is by a call toGRBModel.Optimize. The third is bya call toGRBModel.Write to write out the model. Thefirst case gives you fine-grained control over when modifications areapplied. The second and third make the assumption that you want allpending modifications to be applied before you optimize your model orwrite 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, 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 theModel.Parametersclass and its associated .NET properties. To set theMIPGap parameter to 0.0 for modelm, for example,you would dom.Parameters.MIPGap=0.

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_cs.cs 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#

Users typically do not need to concern themselves with memory managementin .NET, since it is handled automatically by the garbage collector. TheGurobi .NET interface utilizes the same garbage collection mechanism asother .NET programs, but there are a few specifics of our memorymanagement that users should be aware of.

In general, Gurobi objects live in the same .NET heap as other .NETobjects. When they are no longer referenced, they become candidates forgarbage collection, and are returned to the pool of free space at thenext invocation of the garbage collector. Two important exceptions aretheGRBEnv andGRBModel objects. AGRBModel object has a small amount of memory associated with it inthe .NET heap, but the majority of the space associated with a modellives in the heap of the Gurobi native code DLL. The .NET heap manageris unaware of the memory associated with the model in the native codelibrary, so it does not consider this memory usage when deciding whetherto invoke the garbage collector. When the garbage collector eventuallycollects the .NETGRBModel object, the memory associated with themodel in the Gurobi native code library will be freed, but thiscollection may come later than you might want. Similar considerationsapply to theGRBEnv object.

If you are writing a .NET program that makes use of multiple Gurobimodels or environments, we recommend that you callGRBModel.Dispose when you are done using the associatedGRBModel object, andGRBEnv.Dispose when you are doneusing the associatedGRBEnv object and after you have calledGRBModel.Dispose on all of the models created using thatGRBEnv object.

Native Code#

As noted earlier, the Gurobi .NET interface is a thin layer that sits ontop of our native code library. Thus, an application that uses the Gurobi.NET library will load the Gurobi native library at runtime. In order for thishappen, you need to make sure that two things are true. First, you needto make sure that the native code library is available in the search pathof the target machine (PATH on Windows,LD_LIBRARY_PATH on Linux,orDYLD_LIBRARY_PATH on Mac). This environment variable is set up as partof the installation of the Gurobi Optimizer, but it may not be configuredappropriately on a machine where the full Gurobi Optimizer has not beeninstalled. Second, you need to be sure that the selected .NET PlatformTarget (as selected in Visual Studio) is compatible with the Gurobi native librarythat is available through your search path. In particular, you need to usethe 64-bit Gurobi native library when you’ve selected thex64Platform Target. If you use the defaultAnyCPU target, then your.NET application will look for the 64-bit Gurobi native library on a 64-bitmachine.

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 modifytheLogFile parameter if you wish to redirect the log toa different 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.SetCallback method allows you to receive aperiodic callback from the Gurobi Optimizer. You do this by sub-classingtheGRBCallback abstract class, and writing your ownCallback() method on this class. You can callGRBCallback.GetDoubleInfo,GRBCallback.GetIntInfo,GRBCallback.GetStringInfo, orGRBCallback.GetSolution from within the callback toobtain additional information about the state of the optimization.Refer to the examplecallback_cs.cswhich 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 terminateat the 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_cs.cs). 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 .NET library can throw an exception oftypeGRBException. When an exception occurs, additionalinformation on the error can be obtained by retrieving the error code(using propertyGRBException.ErrorCode), or by retrievingthe exception message (using propertyGRBException.Message from theparent class). The list of possible error return codes can be found intheError Codes table.

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp