Gurobi Python License

0 views
Skip to first unread message

Cherie Trojak

unread,
Aug 5, 2024, 1:24:45 PM8/5/24
to skomrepatli
Thissection documents the Gurobi Python interface. It begins with anoverview of the global functions, which can be called withoutreferencing any Python objects. It then discusses the different typesof objects that are available in the interface, and the most importantmethods on those objects. Finally, it gives acomprehensivepresentation of all of the available classes and methods.If you are new to the Gurobi Optimizer, we suggest that you start withtheGetting Started Knowledge Base articleor theExample Tour.These documents provide concrete examples of how to use the classesand methods described here.Important note for AIX users: due to limited Python support onAIX, our AIX port does not include the Python interface.Global FunctionsThe Gurobi shell contains a set of Global Functions that can be called withoutreferring to any Gurobi objects. The most important of thesefunctions is probably the readfunction, which allows you to read a model from a file. Anotheruseful global function isdisposeDefaultEnv,which disposes of the default environment. Other global functionsallow you to read, modify, or write Gurobi parameters(readParams,setParam, andwriteParams).ModelsMost actions in the Gurobi Python interface are performed by callingmethods on Gurobi objects. The most commonly used object isthe Model. A model consists of aset of decision variables (objects of classVar orMVar), a linear or quadraticobjective function on these variables (specified usingModel.setObjective),and a set of constraints on these variables (objects of classConstr,MConstr,QConstr,MQConstr,SOS,GenConstr,or MGenConstr).Each variable has anassociated lower bound, upper bound, and type(continuous, binary, etc.). Each linear orquadratic constraint has an associatedsense (less-than-or-equal, greater-than-or-equal, or equal), andright-hand side value. Refer tothis sectionfor more information on variables, constraints, and objectives.An optimization model may be specified all at once, by loading themodel from a file (using the previously mentionedread function), or it may be builtincrementally, by first constructing an empty object of classModel and then subsequentlycallingModel.addVar,Model.addVars, orModel.addMVar to addadditional variables,andModel.addConstr,Model.addConstrs,Model.addLConstr,Model.addQConstr,Model.addSOS, or any of theModel.addGenConstrXxx methodsto add additional constraints.Linear constraints are specified by building linear expressions(objects of class LinExpr orMLinExpr), and then specifyingrelationships between these expressions (for example, requiring thatone expression be equal to another). Quadratic constraints are builtin a similar fashion, but using quadratic expressions (objects ofclass QuadExpr orMQuadExpr) instead. Generalconstraints are built using a set of dedicated methods, or a set ofgeneral constraint helper functions plus overloaded operators.Models are dynamic entities; you can always add or remove variables orconstraints.We often refer to the class of an optimization model. At thehighest level, a model can be continuous or discrete, depending on whetherthe modeling elements present in the model require discrete decisionsto be made. Among continuous models...A model with a linear objective function, linear constraints, andcontinuous variables is a Linear Program (LP).If the objective is quadratic, the model is a Quadratic Program(QP).If any of the constraints are quadratic, the model is aQuadratically-Constrained Program (QCP). We sometimesrefer to a few special cases of QCP: QCPs with convex constraints,QCPs with non-convex constraints, bilinear programs, andSecond-Order Cone Programs (SOCP).If any of the constraints are non-linear (chosenfrom among the available general constraints),the model is a Non-Linear Program (NLP).A model that contains any integer variables, semi-continuousvariables, semi-integer variables, Special Ordered Set (SOS)constraints, or general constraints, is discrete, and is referred toas a Mixed Integer Program (MIP). The specialcases of MIP, which are the discrete versions of the continuous modelstypes 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 thatthe boundaries between them aren't as clear as one might like, becausewe are often able to transform a model from one class to a simplerclass.EnvironmentsEnvironments 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 yourown environment to routines that require an environment, the defaultenvironment will be used.The main situation where you may want to create your own environmentis when you want precise control over when the resources associatedwith an environment (specifically, a licensing token or a ComputeServer) are released. If you use your own environment to createmodels (using read or theModel constructor), then theresources associated with the environment will be released as soonyour program no longer references your environment or any modelscreated with that environment.Note that you can manually remove the reference to the defaultenvironment, thus making it available for garbage collection, bycallingdisposeDefaultEnv.After calling this, and after all models built within the defaultenvironment are garbage collected, the default environment will begarbage collected as well. A new default environment will becreated 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 detailssee the Environment section.Solving a ModelOnce you have built a model, you can callModel.optimize tocompute a solution. By default,optimizewill use theconcurrent optimizerto solve LP models, the barrier algorithm to solve QP modelswith convex objectives andQCP models with convex constraints,and the branch-and-cut algorithm otherwise.The solution is stored in a set of attributes of the model, whichcan be subsequently queried (we will return to this topic shortly).The Gurobi algorithms keep careful track of the state of the model, socalls toModel.optimizewill only perform further optimization if relevant data has changedsince the model was last optimized. If you would like to discardpreviously computed solution information and restart the optimizationfrom scratch without changing the model, you can callModel.reset.After a MIP model has been solved, you can callModel.fixedto compute the associated fixed model. This model isidentical to the original, except that the integer variables are fixedto their values in the MIP solution. If your model contains SOSconstraints, some continuous variables that appear in theseconstraints may be fixed as well. In some applications, it can beuseful to compute information on this fixed model (e.g., dualvariables, sensitivity information, etc.), although you should becareful in how you interpret this information.Multiple Solutions, Objectives, and ScenariosBy 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 torelax these assumptions:Solution Pool: Allows you to find more solutions.Multiple Scenarios: Allows you to find solutions to multiple, related models.Multiple Objectives: Allows you to specify multiple objective functions and control the trade-off between them.Infeasible ModelsYou have a few options if a model is found to be infeasible. You cantry to 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.computeIISto compute anIrreducible Inconsistent Subsystem (IIS). This method can be usedfor both continuous and MIP models, but you should be aware that theMIP version can be quite expensive. This method populates a set ofIIS attributes.To attempt to repair an infeasibility, callModel.feasRelaxS orModel.feasRelaxto compute afeasibility relaxation for the model. This relaxation allows you tofind a solution that minimizes the magnitude of the constraintviolation.Querying and Modifying AttributesMost of the information associated with a Gurobi model is stored in aset of attributes. Some attributes are associated with the variablesof the model, some with the constraints of the model, and some withthe model itself. To give a simple example, solving an optimizationmodel causes the x variable attribute to be populated.Attributes such as x that are computed by the Gurobi Optimizercannot be modified directly by the user, while others, such as thevariable lower bound (the lb attribute) can.Attributes can be accessed in two ways in the Python interface. Thefirst is to use the getAttr() and setAttr() methods,which are available on variables(Var.getAttr/Var.setAttr),matrix variables(MVar.getAttr/MVar.setAttr),linear constraints(Constr.getAttr/Constr.setAttr),matrix constraints(MConstr.getAttr/MConstr.setAttr),quadratic constraints(QConstr.getAttr/QConstr.setAttr),matrix constraints(MQConstr.getAttr/MQConstr.setAttr),SOSs (SOS.getAttr),general constraints(GenConstr.getAttr/ GenConstr.setAttr), andmodels (Model.getAttr/Model.setAttr).These are called with the attribute name as the first argument (e.g.,var.getAttr("x") or constr.setAttr("rhs", 0.0)). Thefull list of available attributes can be found in theAttributes section of this manual.Attributes can also be accessed more directly: you can follow anobject name by a period, followed by the name of an attribute of thatobject. Note that upper/lower case is ignored when referring toattributes. Thus, b = constr.rhs is equivalent tob = constr.getAttr("rhs"), and constr.rhs = 0.0 is equivalentto constr.setAttr("rhs", 0.0).Additional Model Modification InformationMost 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 to modify the value of an existing non-zero,to set 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 theModel.remove method).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(a LinExpr,MLinExpr,QuadExpr, orMQuadExpr object),and then pass that expression to methodModel.setObjective.If you wish to modify the objective, you can simply callsetObjective again with a new LinExpr orQuadExpr object.For linear objective functions, an alternative to setObjectiveis to use the Obj variable attribute to modifyindividual linear objective coefficients.If your variables have piecewise-linear objectives, you can specifythem using the Model.setPWLObjmethod. Call this method once for each relevant variable. The Gurobisimplex solver includes algorithmic support for convexpiecewise-linear objective functions, so for continuous models youshould see a substantial performance benefit from using this feature.To clear a previously specified piecewise-linear objective function,simply set the Obj attribute on the corresponding variable to0.Lazy UpdatesOne important item to note about model modification in the Gurobioptimizer is that it is performed in a lazy fashion, meaningthat modifications don't affect the model immediately. Rather, theyare queued and applied later. If your program simply creates a modeland solves it, you will probably never notice this behavior. However,if you ask for information about the model before your modificationshave been applied, the details of the lazy update approach may berelevant 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.The first is by an explicit call toModel.update. The second isby a call to Model.optimize. Thethird is by a call to Model.write towrite out the model. The first case gives you fine-grained controlover when modifications are applied. The second and third make theassumption that you want all pending modifications to be appliedbefore 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 toperform multiple modifications to a model, since the model remainsunchanged between modifications. The second is that processing modelmodifications can be expensive, particularly in a Compute Serverenvironment, where modifications require communication betweenmachines. Thus, it is useful to have visibility into exactly whenthese modifications are applied. In general, if your program needs tomake multiple modifications to the model, you should aim to make themin phases, where you make a set of modifications, then update, thenmake more modifications, then update again, etc. Updating after eachindividual modification can be extremely expensive.If you forget to call update, your program won't crash. Your querywill simply return the value of the requested data from the point ofthe last update. If the object you tried to query didn't exist then,you'll get a NOT_IN_MODEL exception instead.The semantics of lazy updates have changed since earlier Gurobiversions. While the vast majority of programs are unaffected by thischange, you can use the UpdateModeparameter to revert to the earlier behavior if you run into an issue.Managing ParametersThe 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,strategies for exploring the MIP search tree, etc., can be controlledby modifying Gurobi parameters before beginning the optimization.Parameters are set using methodModel.setParam.Current values may also be retrieved withModel.getParamInfo.You can also access parameters more directly through theModel.Params class. To set theMIPGap parameter to 0.0 formodel m, for example, you can do eitherm.setParam('MIPGap', 0) orm.Params.MIPGap = 0.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 thatimproves performance. You can callModel.tuneto invoke the tuning tool on a model.Refer to theparameter tuning toolsection for more information.One thing we should note is that changing a parameter for one modelhas no effect on the parameter value for other models. Use theglobal setParam method to set aparameter for all loaded models.The full list of Gurobi parameters can be found in theParameters section.Monitoring Progress - Logging and CallbacksProgress of the optimization can be monitored through Gurobi logging.By default, Gurobi will send output to the screen. A few simplecontrols are available for modifying the default logging behavior.You can set theLogFileparameter if you wish to alsodirect the Gurobi log to a file. The frequency of logging output canbe controlled with theDisplayIntervalparameter, and loggingcan be turned off entirely with theOutputFlagparameter.Log output is also sent to a Python logger named gurobipy, atlevel INFO. You can use the Python logging module toconnect to this log.More detailed progress monitoring can be done through a callbackfunction. If you pass a function taking two arguments, modeland where, toModel.optimize, your functionwill be called periodically from within the optimization. Yourcallback can thencall Model.cbGet toretrieve additional information on the state of the optimization. Youcan refer to the Callback classfor additional information.Modifying Solver Behavior - CallbacksCallbacks 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 convenientpoint. MethodModel.cbSetSolutionallows you to inject a feasible solution (or partial solution) duringthe solution of a MIP model. MethodsModel.cbCutandModel.cbLazyallow you to add cutting planes and lazy constraintsduring a MIP optimization, respectively.Method Model.cbStopOneMultiObj allows you to interrupt the optimization process of one of the optimization steps ina multi-objective MIP problem without stopping the hierarchicaloptimization process.Batch OptimizationGurobi Compute Server enables programs to offload optimization computations onto dedicated servers. The Gurobi Cluster Manager adds a number of additional capabilities on top of this. One important one, batch optimization, allows you to build an optimization model with your client program, submit it to a Compute Server cluster (through the Cluster Manager), and later check on the status of the model and retrieve its solution. You can use a Batch object to make it easier to work with batches. For details on batches, please refer to the Batch Optimization section.Error HandlingAll of the methods in the Gurobi Python library can throw an exceptionof type GurobiError. When anexception occurs, additional information on the error can be obtainedby retrieving the errno or message members of theGurobiError object. A list of possible values for theerrno field can be found in the ErrorCode section.

Next: Python API Details Up: Gurobi Optimizer Reference Manual Previous: GRB.StringParam

3a8082e126
Reply all
Reply to author
Forward
0 new messages