Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

Python API Overview#

Global Functions#

For convenience when using Gurobi interactively through the Pythoninterpreter, we provide a set ofGlobal Functions. The most important of these functions is probably theread function, which allows you toread and solve a model from file.Another useful global function isdisposeDefaultEnv, whichdisposes of the default environment. Other global functions allow you toread, modify, or write Gurobi parameters (readParams,setParam, andwriteParams).

Models#

Most actions in the Gurobi Python interface are performed by callingmethods on Gurobi objects. The most commonly used object is theModel. A model consists of a set of decision variables(objects of classVar orMVar), a linear orquadratic objective function on these variables (specified usingModel.setObjective), and a set of constraints on thesevariables (objects of classConstr,MConstr,QConstr,MQConstr,SOS,GenConstr, orMGenConstr). Each variable has anassociated lower bound, upper bound, and type (continuous, binary,etc.). Each linear or quadratic constraint has an associated sense(less-than-or-equal, greater-than-or-equal, or equal), and right-handside value. Refer tothis sectionfor more information on variables, constraints, and objectives.

An optimization model may be specified all at once, by loading the modelfrom a file (using the previously mentionedread function),or it may be built incrementally, by first constructing an empty objectof classModel and then subsequently callingModel.addVar,Model.addVars, orModel.addMVar to add additional variables, andModel.addConstr,Model.addConstrs,Model.addLConstr,Model.addQConstr,Model.addSOS, or any of theModel.addGenConstr* methods to addadditional constraints.SeeBuild a modelfor general guidance ormip1_remote.pyfor a specific example.

Linear constraints are specified by building linear expressions (objectsof classLinExpr orMLinExpr), and thenspecifying relationships between these expressions (for example,requiring that one expression be equal to another). Quadraticconstraints are built in a similar fashion, but using quadraticexpressions (objects of classQuadExpr orMQuadExpr) instead. General constraints are built using aset ofdedicated methods, or a set ofgeneral constraint helper functions plusoverloaded operators.

Nonlinear constraints are specified by buildingnonlinear expressions (objectsof classNLExpr orMNLExpr) and specifying a chosenresultant variable which takes the value of the expression. That resultantvariable can then participate in other constraints. In the Python API, nonlinearexpressions are built using operator overloading. In general, calling anynonlinear function, or creating any expression which isnot strictly linearor quadratic (in terms of the model variables) results in a nonlinear expression.

Models are dynamic entities; you can always add or remove variables orconstraints.

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.

Environments#

Environments play a much smaller role in the Gurobi Python interfacethan they do in our other language APIs, mainly because the Pythoninterface has a default environment. Unless you explicitly pass your ownenvironment to routines that require an environment, the defaultenvironment will be used.

The main situation where you may want to create your own environment iswhen you want precise control over when the resources associated with anenvironment (specifically, a licensing token or a Compute Server) arereleased. If you use your own environment to create models (usingread or theModel constructor), then theresources associated with the environment will be released as soon as yourprogram no longer references your environment or any models created withthat environment.

Note that you can manually remove the reference to the defaultenvironment, thus making it available for garbage collection, by callingdisposeDefaultEnv. After calling this, and after all modelsbuilt within the default environment are garbage collected, the defaultenvironment will be garbage collected as well. A new default environmentwill be created automatically if you call a routine that needs one.

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.

Solving a Model#

Once you have built a model, you can callModel.optimize tocompute a solution. By default,optimizewill use theconcurrent optimizer to solve LPmodels, the barrier algorithm to solve QP models with convex objectivesand QCP models with convex constraints, and the branch-and-cut algorithmotherwise. The solution is stored in a set ofattributes of the model,which can be subsequently queried (we will return to this topicshortly).

The Gurobi algorithms keep careful track of the state of the model, socalls toModel.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 callModel.reset.

After a MIP model has been solved, you can callModel.fixedto compute 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.

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, callModel.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, callModel.feasRelaxSorModel.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 can be accessed in two ways in the Python interface. Thefirst is to use thegetAttr() andsetAttr() methods, which areavailable on variables (Var.getAttr/Var.setAttr),matrix variables (MVar.getAttr/MVar.setAttr),linear constraints (Constr.getAttr/Constr.setAttr), matrix constraints(MConstr.getAttr/MConstr.setAttr), quadraticconstraints (QConstr.getAttr/QConstr.setAttr),matrix constraints (MQConstr.getAttr/MQConstr.setAttr), SOSs (SOS.getAttr), generalconstraints (GenConstr.getAttr/GenConstr.setAttr), and models (Model.getAttr/Model.setAttr). These are called with the attribute name asthe first argument (e.g.,var.getAttr("x") orconstr.setAttr("rhs",0.0)). The full list of available attributescan be found in theAttributes section of thismanual.

Attributes can also be accessed more directly: you can follow an objectname by a period, followed by the name of an attribute of that object.Note that upper/lower case is ignored when referring to attributes.Thus,b=constr.rhs is equivalent tob=constr.getAttr("rhs"),andconstr.rhs=0.0 is equivalent toconstr.setAttr("rhs",0.0).

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 theModel.chgCoeff method. This method can be used tomodify the value of an existing non-zero, to set an existing non-zero tozero, or to create a new non-zero. The constraint matrix is alsomodified when you remove a variable or constraint from the model(through theModel.remove method). The non-zero valuesassociated with the deleted constraint or variable are removed alongwith 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(aLinExpr,MLinExpr,QuadExpr, orMQuadExpr object), and then pass that expression to methodModel.setObjective. If you wish to modify the objective, youcan simply callModel.setObjective again with a newLinExpr orQuadExpr object.

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

If your variables have piecewise-linear objectives, you can specify themusing theModel.setPWLObj method. Call this method 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.

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 toModel.update. The second isby a call toModel.optimize. The third is by a call toModel.write 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, 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 are setusing methodModel.setParam. Current values may also beretrieved withModel.getParamInfo. You can also accessparameters more directly through theModel.Params class. To set theMIPGap parameter to 0.0 for modelm, for example,you can do eitherm.setParam('MIPGap',0) orm.Params.MIPGap=0.Refer to the exampleparams.py whichis considered inChange parameters.

You can read a set of parameter settings from a file usingModel.read, or write the set of changed parameters usingModel.write.

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 callModel.tune to invoke the tuningtool on a model. Refer to theparameter tuning toolsection for more information.

One thing we should note is that changing a parameter for one model hasno effect on the parameter value for other models. Use the globalsetParam method to set a parameter for all loaded models.

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.

Monitoring Progress - Logging#

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. You can settheLogFile parameter if you wish to also direct theGurobi log to a file. Printing of log messages to the screen (standardoutput) can be suppressed using theLogToConsoleparameter. The frequency of logging output can be controlledwith theDisplayInterval parameter, and logging can beturned off entirely with theOutputFlag parameter.

Log output is also sent to a Python logger namedgurobipy, at levelINFO. You can use the Pythonlogging module to connect tothis log. Messages are always sent to the logger, unlessOutputFlag is set to 0.

If you want log messages to be sent to the Python logger butnot printed tostandard output, you should leaveOutputFlag at its defaultvalue and setLogToConsole to 0. To suppress all Gurobi logmessages on standard output, you must set this parameter when starting theenvironment. The following example demonstrates proper usage, along with a calltologging.basicConfig to emit Gurobi log messages through the Pythonlogger:

importloggingimportgurobipyasgplogging.basicConfig(level=logging.INFO,format="%(asctime)s -%(name)s -%(levelname)s -%(message)s",)env=gp.Env(params={"LogToConsole":0})model=gp.Model(env=env)...model.optimize()

Monitoring Progress - Callbacks#

More detailed progress monitoring can be done through a callbackfunction. If you pass a function taking two arguments,model andwhere, toModel.optimize, your function will be calledperiodically from within the optimization. Your callback can then callModel.cbGet to retrieve additional information on the stateof the optimization. You can refer to theCallbacks section for additional information.Refer to the examplecallback.pywhich is discussed inCallbacks.

Modifying Solver Behavior - Callbacks#

Callbacks can also be used to modify the behavior of the Gurobioptimizer. The simplest control callback isModel.terminate,which asks the optimizer to terminate at the earliest convenient point.MethodModel.cbSetSolution allows you to inject a feasiblesolution (or partial solution) during the solution of a MIP model.MethodsModel.cbCut andModel.cbLazy allow you toaddcutting planes andlazy constraints during a MIP optimization,respectively (refer to the exampletsp.py).MethodModel.cbStopOneMultiObj allows you tointerrupt the 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 Python library can throw an exceptionof typeGurobiError. When an exception occurs, additionalinformation on the error can be obtained by retrieving theerrno ormessage members of theGurobiError object. A list of possiblevalues for theerrno field can be found in theError Code table.

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp