Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

gurobipy.Model#

classModel#

Gurobi model object. Commonly used methods on the model objectincludeoptimize (optimizes the model),printStats (prints statistics about the model),printAttr (prints the values of an attribute), andwrite (writes information about the model to a file).Commonly used methods when building a model includeaddVar(adds a new variable),addVars (adds multiple new variables),addMVar (adds an a NumPy ndarray of Gurobi variables),addConstr (adds a new constraint), andaddConstrs(adds multiple new constraints).

Model(name='',env=None)#

Model constructor.

Parameters:
  • name – Name of new model. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

  • env – Environment in which to create the model. Creating your ownenvironment (using theEnvconstructor) gives you morecontrol (for example, to solve your model on a specific Compute Server).If you do not provide an environment, the default environment will bestarted if necessary and used to create the model.

Returns:

New model object. The model initially contains no variables orconstraints.

Example:
# Create a model using the default environmentmodel1=gp.Model("NewModel1")x0=model1.addVar()...# Create a model within your own environmentenv=gp.Env()model2=gp.Model("NewModel2",env=env)...# Use a context manager to ensure that the model is always# cleaned up at the end of the contextwithgp.Model("NewModel3",env=env)asmodel3:...model3.optimize()...
addConstr(constr,name='')#

Add a constraint to a model.

This method accepts aTempConstr as its first argument, andthe constraint name as its optional second argument. You use operatoroverloading to create the argument (seethissection for details). This one methodallows you to add linear constraints, matrix constraints, quadraticconstraints, and general constraints.

Parameters:
  • constrTempConstr argument.

  • name – Name for new constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New constraint object. This can be aConstr, anMConstr, aQConstr, or anMQConstr,depending on the type of the argument.

Example:
model.addConstr(x+y<=2.0,"c1")model.addConstr(x*x+y*y<=4.0,"qc0")model.addConstr(x+y+z==[1,2],"rgc0")model.addConstr(A@t>=b)model.addConstr(z==and_(x,y,w),"gc0")model.addConstr(z==min_(x,y),"gc1")model.addConstr((w==1)>>(x+y<=1),"ic0")

Warning

A constraint can only have a single comparison operator. While1<=x+y<=2 may look like a valid constraint,addConstrwon’t accept it.

addConstrs(generator,name='')#

Add multiple constraints to a model using a Python generator expression.Returns a Gurobitupledict that contains the newly createdconstraints, indexed by the values generated by the generatorexpression.

The first argument toaddConstrs is a Python generator expression, aspecial feature of the Python language that allows you to iterate over aPython expression. In this case, the Python expression will be a Gurobiconstraint and the generator expression provides values to plug intothat constraint. A new Gurobi constraint is added to the model for eachiteration of the generator expression.

To give an example, ifx is a Gurobi variable, then

m.addConstr(x<=1,name='c0')

would add a single linear constraint involving this variable. Incontrast, ifx is a list of Gurobi variables, then

m.addConstrs((x[i]<=1foriinrange(4)),name='c')

would add four constraints to the model. The entire first argument is agenerator expression, where the indexing is controlled by the statementforiinrange(4), The first constraint that results from thisexpression would be namedc[0], and would involve variablex[0].The second would be namedc[1], and would involve variablex[1].

Generator expressions can be much more complex than this. They caninvolve multiple variables and conditional tests. For example, you coulddo:

m.addConstrs((x[i,j]==0foriinrange(4)forjinrange(4)ifi!=j),name='c')

One restriction thataddConstrs places on the generator expressionis that each variable must always take a scalar value (int,float,string, …). Thus,foriin[1,2.0,'a','bc'] isfine, butforiin[(1,2),[1,2,3]] isn’t.

This method can be used to add linear constraints, quadraticconstraints, or general constraints to the model. Refer to theTempConstr documentation for more information on all of thedifferent constraint types that can be added.

Note that if you supply a name argument, the generator expression mustbe enclosed in parenthesis. This requirement comes from the Pythonlanguage interpreter.

Parameters:
  • generator – A generator expression, where each iteration produces aconstraint.

  • name – Name pattern for new constraints. The given name will be subscripted by the indexof the generator expression, so if the index is an integer,c wouldbecomec[0],c[1], etc. Note that the generated names will bestored as ASCII strings, so you should avoid using names that containnon-ASCII characters. In addition, names that contain spaces arestrongly discouraged, because they can’t be written to LP format files.

Returns:

A dictionary ofConstr objects, indexed by thevalues specified by the generator expression.

Example:
model.addConstrs(x.sum(i,'*')<=capacity[i]foriinrange(5))model.addConstrs(x[i]+x[j]<=1foriinrange(5)forjinrange(5))model.addConstrs(x[i]*x[i]+y[i]*y[i]<=1foriinrange(5))model.addConstrs(x.sum(i,'*')==[0,2]foriin[1,2,4])model.addConstrs(z[i]==max_(x[i],y[i])foriinrange(5))model.addConstrs((x[i]==1)>>(y[i]+z[i]<=5)foriinrange(5))

Warning

A constraint can only have a single comparison operator. While1<=x+y<=2 may look like a valid constraint,addConstrswon’t accept it.

addGenConstrMax(resvar,vars,constant=None,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_MAX to a model.

A MAX constraint\(r = \max\{x_1,\ldots,x_n,c\}\) states that theresultant variable\(r\) should be equal to the maximum of theoperand variables\(x_1,\ldots,x_n\) and the constant\(c\).

You can also add a MAX constraint using themax_ function.

Parameters:
  • resvar – (Var) The variable whose value will be equal to themaximum of the other variables.

  • vars – (list or iterable of Var) The variables over which theMAX will be taken.

  • constant – (float, optional) The constant to include among thearguments of the MAX operation.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = max(x1, x3, x4, 2.0)model.addGenConstrMax(x5,[x1,x3,x4],2.0,"maxconstr")# overloaded formsmodel.addConstr(x5==max_([x1,x3,x4],constant=2.0),name="maxconstr")model.addConstr(x5==max_(x1,x3,x4,constant=2.0),name="maxconstr")

Deprecated since version 12.0:Passing atupledict as thevars argument is deprecated.To take the MAX over all variables in a tupledicttd, passtd.values().

addGenConstrMin(resvar,vars,constant=None,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_MIN to a model.

A MIN constraint\(r = \min\{x_1,\ldots,x_n,c\}\) states that theresultant variable\(r\) should be equal to the minimum of theoperand variables\(x_1,\ldots,x_n\) and the constant\(c\).

You can also add a MIN constraint using themin_ function.

Parameters:
  • resvar – (Var) The variable whose value will be equal to theminimum of the other variables.

  • vars – (list or iterable of Var) The variables over which theMIN will be taken.

  • constant – (float, optional) The constant to include among thearguments of the MIN operation.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = min(x1, x3, x4, 2.0)model.addGenConstrMin(x5,[x1,x3,x4],2.0,"minconstr")# overloaded formsmodel.addConstr(x5==min_([x1,x3,x4],constant=2.0),name="minconstr")model.addConstr(x5==min_(x1,x3,x4,constant=2.0),name="minconstr")

Deprecated since version 12.0:Passing atupledict as thevars argument is deprecated.To take the MIN over all variables in a tupledicttd, passtd.values().

addGenConstrAbs(resvar,argvar,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_ABS to a model.

An ABS constraint\(r = \mbox{abs}\{x\}\) states that the resultantvariable\(r\) should be equal to the absolute value of the argumentvariable\(x\).

You can also add an ABS constraint using theabs_ function.

Parameters:
  • resvar – (Var) The variable whose value will be to equal theabsolute value of the argument variable.

  • argvar – (Var) The variable for which the absolute value will betaken.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = abs(x1)model.addGenConstrAbs(x5,x1,"absconstr")# overloaded formmodel.addConstr(x5==abs_(x1),name="absconstr")
addGenConstrAnd(resvar,vars,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_AND to a model.

An AND constraint\(r = \mbox{and}\{x_1,\ldots,x_n\}\) states thatthe binary resultant variable\(r\) should be\(1\) if and onlyif all of the operand variables\(x_1,\ldots,x_n\) are equal to\(1\). If any of the operand variables is\(0\), then theresultant should be\(0\) as well.

Note that all variables participating in such a constraint will beforced to be binary, independent of how they were created.

You can also add an AND constraint using theand_ function.

Parameters:
  • resvar – (Var) The variable whose value will be equal to the ANDconcatenation of the other variables.

  • vars – (list or iterable of Var) The variables over which the ANDconcatenation will be taken.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = and(x1, x3, x4)model.addGenConstrAnd(x5,[x1,x3,x4],"andconstr")# overloaded formsmodel.addConstr(x5==and_([x1,x3,x4]),"andconstr")model.addConstr(x5==and_(x1,x3,x4),"andconstr")

Deprecated since version 12.0:Passing atupledict as thevars argument is deprecated.To take the AND concatenation over all variables in a tupledicttd,passtd.values().

addGenConstrOr(resvar,vars,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_OR to a model.

An OR constraint\(r = \mbox{or}\{x_1,\ldots,x_n\}\) states that thebinary resultant variable\(r\) should be\(1\) if and only ifany of the operand variables\(x_1,\ldots,x_n\) is equal to\(1\). If all operand variables are\(0\), then the resultantshould be\(0\) as well.

Note that all variables participating in such a constraint will beforced to be binary, independent of how they were created.

You can also add an OR constraint using theor_ function.

Parameters:
  • resvar – (Var) The variable whose value will be equal to the ORconcatenation of the other variables.

  • vars – (list or iterable of Var) The variables over which the ORconcatenation will be taken.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = or(x1, x3, x4)model.addGenConstrOr(x5,[x1,x3,x4],"orconstr")# overloaded formsmodel.addConstr(x5==or_([x1,x3,x4]),"orconstr")model.addConstr(x5==or_(x1,x3,x4),"orconstr")

Deprecated since version 12.0:Passing atupledict as thevars argument is deprecated.To take the OR concatenation over all variables in a tupledicttd,passtd.values().

addGenConstrNorm(resvar,vars,which,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_NORM to a model.

A NORM constraint\(r = \mbox{norm}\{x_1,\ldots,x_n\}\) states thatthe resultant variable\(r\) should be equal to the vector norm ofthe argument vector\(x_1,\ldots,x_n\).

Parameters:
  • resvar – (Var) The variable whose value will be equal to the vectornorm of the other variables.

  • vars – (list or iterable Var, or 1-dim MVar) The variables over whichthe vector norm will be taken. Note that this may not contain duplicates.

  • which – (float) Which norm to use. Options are 0, 1, 2, and anyvalue greater than or equal to GRB.INFINITY.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# x5 = 2-norm(x1, x3, x4)model.addGenConstrNorm(x5,[x1,x3,x4],2.0,"normconstr")

Deprecated since version 12.0:Passing atupledict as thevars argument is deprecated.To take the NORM over all variables in a tupledicttd, passtd.values().

addGenConstrIndicator(binvar,binval,lhs,sense=None,rhs=None,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_INDICATOR to amodel.

An INDICATOR constraint\(z = f \rightarrow a^Tx \leq b\) statesthat if the binary indicator variable\(z\) is equal to\(f\),where\(f \in \{0,1\}\), then the linear constraint\(a^Tx \leq b\) should hold. On the other hand, if\(z = 1-f\),the linear constraint may be violated. The sense of the linearconstraint can also be specified to be\(=\) or\(\geq\).

Note that the indicator variable\(z\) of a constraint will beforced to be binary, independent of how it was created.

You can also add an INDICATOR constraint using a special overloadedsyntax. See the examples below for details.

Multiple INDICATOR constraints can be added in a singleaddGenConstrIndicator call by using matrix-friendly modelingobjects. In this case, anMGenConstr object will bereturned. The input arguments follow NumPy’s broadcasting rules, withsome restrictions:

  • binvar cannot be broadcasted overbinval, and

  • the linear constraints defined by(lhs,sense,rhs) cannot bebroadcasted over the indicator variable.

This means that via broadcasting, you can use a single indicatorvariable to control whether multiple linear constraints should hold. Werefer you to the NumPy documentation for further information regardingbroadcasting behaviour.

Parameters:
  • binvar – (Var or MVar) The binary indicator variable or matrixvariable.

  • binval – (Boolean or ndarray) The value for the binary indicatorvariable that would force the linear constraint to be satisfied. Can beprovided as anndarray of distinct values ifbinvar is anMVar.

  • lhs – (float, Var, LinExpr, MVar, MLinExpr, or TempConstr)Left-hand side expression for the linear constraint triggered by theindicator. Can be a constant, aVar, aLinExpr,anMVar, or anMLinExpr. Alternatively, atemporary constraint object can be used to define the linear constraintthat is triggered by the indicator. The temporary constraint object iscreated using an overloaded comparison operator. SeeTempConstr for more information. In this case, the “sense”and “rhs” parameters must stay at their default valuesNone.

  • sense – (char) Sense for the linear constraint. Options areGRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL.

  • rhs – (float or ndarray) Right-hand side value for the linearconstraint. Can be provided as anndarray of distinct values iflhs is anMVar or anMLinExpr.

  • name – (string, optional) Name for the new general constraint.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New general constraint object. This can be aGenConstr or anMGenConstr depending on thetypes of the input arguments.

Example:
# x7 = 1 -> x1 + 2 x3 + x4 = 1model.addGenConstrIndicator(x7,True,x1+2*x3+x4,GRB.EQUAL,1.0)# alternative formmodel.addGenConstrIndicator(x7,True,x1+2*x3+x4==1.0)# overloaded formmodel.addConstr((x7==1)>>(x1+2*x3+x4==1.0))# Matrix-friendly form where Z is an MVar. Creates multiple# indicator constraints, each specifying#   z_i = 1 -> sum a_ij x_j = b_i.model.addGenConstrIndicator(z,1.0,A@x==b)# Matrix-friendly form where z is an Var. Creates multiple# indicator constraints, each specifying#   z = 1 -> sum a_ij x_j = b_i# (the indicator variable is broadcasted).model.addGenConstrIndicator(z,1.0,A@x==b)
addGenConstrPWL(xvar,yvar,xpts,ypts,name='')#

Add a newgeneral constraintof typeGRB.GENCONSTR_PWL to a model.

A piecewise-linear (PWL) constraint states that the relationship\(y =f(x)\) must hold between variables\(x\) and\(y\), where\(f\) is a piecewise-linear function. The breakpoints for\(f\)are provided as arguments. Refer to the description ofpiecewise-linear objectives fordetails of how piecewise-linear functions are defined.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • xpts – (list of float) The\(x\) values for the points thatdefine the piecewise-linear function. Must be in non-decreasing order.

  • ypts – (list of float) The\(y\) values for the points thatdefine the piecewise-linear function.

  • name – (string, optional) Name for the new general constraint.

Returns:

New general constraint.

Example:
gc=model.addGenConstrPWL(x,y,[0,1,2],[1.5,0,3],"myPWLConstr")
addGenConstrPoly(xvar,yvar,p,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_POLY to a model.

A polynomial function constraint states that the relationship\(y = p_0 x^d + p_1 x^{d-1} + ... + p_{d-1} x + p_{d}\) should holdbetween variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • p – The coefficients for the polynomial function (starting with thecoefficient for the highest power).

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = 2 x^3 + 1.5 x^2 + 1gc=model.addGenConstrPoly(x,y,[2,1.5,0,1])
addGenConstrExp(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_EXP to a model.

A natural exponential function constraint states that the relationship\(y = \exp(x)\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = exp(x)gc=model.addGenConstrExp(x,y)
addGenConstrExpA(xvar,yvar,a,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_EXPA to a model.

An exponential function constraint states that the relationship\(y = a^x\) should hold for variables\(x\) and\(y\), where\(a > 0\) is the (constant) base.

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The base of the function,\(a > 0\).

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = 3^xgc=model.addGenConstrExpA(x,y,3.0,"expa")
addGenConstrLog(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_LOG to a model.

A natural logarithmic function constraint states that the relationship\(y = log(x)\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = ln(x)gc=model.addGenConstrLog(x,y)
addGenConstrLogA(xvar,yvar,a,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_LOGA to a model.

A logarithmic function constraint states that the relationship\(y = log_a(x)\) should hold for variables\(x\) and\(y\),where\(a > 0\) is the (constant) base.

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The base of the function,\(a > 0\).

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = log10(x)gc=model.addGenConstrLogA(x,y,10.0,"log10","FuncPieces=-1 FuncPieceError=1e-5")
addGenConstrLogistic(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_LOGISTIC to amodel.

A logistic function constraint states that the relationship\(y = \frac{1}{1 + e^{-x}}\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = 1 / (1 + exp(-x))gc=model.addGenConstrLogistic(x,y)
addGenConstrPow(xvar,yvar,a,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_POW to a model.

A power function constraint states that the relationship\(y = x^a\)should hold for variables\(x\) and\(y\), where\(a\) isthe (constant) exponent.

If the exponent\(a\) is negative, the lower bound on\(x\) mustbe strictly positive. If the exponent isn’t an integer, the lower boundon\(x\) must be non-negative.

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The exponent of the function.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = x^3.5gc=model.addGenConstrPow(x,y,3.5,"gf","FuncPieces=1000")
addGenConstrSin(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_SIN to a model.

A sine function constraint states that the relationship\(y = sin(x)\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = sin(x)gc=model.addGenConstrSin(x,y)
addGenConstrCos(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_COS to a model.

A cosine function constraint states that the relationship\(y = cos(x)\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = cos(x)gc=model.addGenConstrCos(x,y)
addGenConstrTan(xvar,yvar,name='',options='')#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Add a newgeneral constraintof typeGRB.GENCONSTR_TAN to a model.

A tangent function constraint states that the relationship\(y = tan(x)\) should hold for variables\(x\) and\(y\).

A piecewise-linear approximation of the functionis added to the model. The details of the approximation are controlledusing the following four attributes (or using the parameters with thesame names):FuncPieces,FuncPieceError,FuncPieceLength, andFuncPieceRatio.Alternatively, the function can be treated as a nonlinear constraint bysetting the attributeFuncNonlinear. For details, consult theGeneral Constraintdiscussion.

Parameters:
  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • name – (string, optional) Name for the new general constraint.

  • options – (string, optional) A string that can be used to set theattributes that control the piecewise-linear approximation of thisfunction constraint. To assign a value to an attribute, follow theattribute name with an equal sign and the desired value (with nospaces). Assignments for different attributes should be separated byspaces (e.g. “FuncPieces=-1 FuncPieceError=0.001”).

Returns:

New general constraint.

Example:
# y = tan(x)gc=model.addGenConstrTan(x,y)
addGenConstrNL(resvar,expr,name='')#

Add a new general constraint of typeGRB.GENCONSTR_NL to amodel. The nonlinear constraint is of the form\(y = f(x)\),where the multivariate expression\(f(x)\) is given by anNLExpr object. In this form,\(y\) is called theresultant variable of the constraint.

Parameters:
  • resvar (Var) – The resultant variable of the constraint.

  • expr – An expression object. A nonlinear constraint will beadded to the model specifying thatresvar is equal to thevalue ofexpr.

  • name – (string, optional) Name for the new constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New general constraint

Return type:

GenConstr

Example:
fromgurobipyimportnlfunc...x1=model.addVar()x2=model.addVar()y=model.addVar()z=model.addVar()genconstr_sin=model.addGenConstrNL(y,nlfunc.sin(x1+x2),name="nl_constraint_sin",)genconstr_div=model.addGenConstrNL(z,x1/x2,name="nl_constraint_div")
addGenConstrNLAdv(resvar,opcode,data,parent,name='')#

Add a new general constraint of typeGRB.GENCONSTR_NL to amodel. The nonlinear constraint is of the form\(y = f(x)\),where the multivariate expression\(f(x)\) is given by anNLExpr object. In this form,\(y\) is called theresultant variable of the constraint.

This is an advanced method which requires the expression\(f(x)\) to be encoded as an expression tree specified in thethree listsopcode,data, andparent. Most usersshould useaddGenConstrNL oraddConstr toadd nonlinear constraints to a model.

Parameters:
  • resvar (Var) – The resultant variable of the NL constraint

  • opcode (list ofint) – List ofnonlinear opcodes

  • data (list offloat orVar) – A list of the same length asopcode. Entriescorresponding toOPCODE_CONSTANT should contain the value ofthe constant. Entries corresponding toOPCODE_VARIABLEshould contain aVar object. Entries correspondingto any other opcode should contain-1.0.

  • parent (list ofint) – Parent indices specifying the expression treetopology.

  • name – (string, optional) Name for the new general constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New general constraint

Return type:

GenConstr

Example:
x=model.addVar()y=model.addVar()# This models y = log(x + 1)genconstr=model.addGenConstrNLAdv(y,[GRB.OPCODE_LOG,GRB.OPCODE_PLUS,GRB.OPCODE_VARIABLE,GRB.OPCODE_CONSTANT],[-1,-1,x,1],[-1,0,1,1],name="nl_constraint",)
addLConstr(lhs,sense=None,rhs=None,name='')#

Add a linear constraint to a model. This method is faster thanaddConstr() (as much as 50% faster for very sparse constraints), but canonly be used to add linear constraints.

Note that this method also accepts aTempConstr as its firstargument (with the name as its second argument). This allows you to useoperator overloading to create constraints. SeeTempConstrfor more information.

Parameters:
  • lhs – Left-hand side for the new constraint. Can be a constant, aVar, aLinExpr, or aTempConstr(while the TempConstr can only be of linear form).

  • sense – Sense for the new constraint (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhs – Right-hand side for the new constraint. Can be a constant, aVar, or aLinExpr.

  • name – Name for new constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New constraint object.

Example:
model.addLConstr(x+2*y,GRB.EQUAL,3*z,"c0")model.addLConstr(x+y<=2.0,"c1")model.addLConstr(LinExpr([1.0,1.0],[x,y]),GRB.LESS_EQUAL,1)
addMConstr(A,x,sense,b,name='')#

Add a set of linear constraints to the model using matrix semantics. Theadded constraints are\(A x = b\) (except that the constraint senseis determined by thesense argument). TheA argument must be aNumPy dense ndarray or a SciPy sparse matrix with no more than 2 billionnon-zero values. Matrices that contain more than 2 billion non-zerosshould be split row-wise over multiple calls to this method.

Note that you will typically use overloaded operators to build and addconstraints using matrix semantics. The overloaded@ operator can beused to build alinearmatrixexpression, whichcan then be used with an overloaded comparison operator to build aTempConstr object. This can then be passed toaddConstr.

Parameters:
  • A – The constraint matrix - a NumPy 2-D dense ndarray or a SciPysparse matrix containing no more than 2 billion non-zero values.

  • x – Decision variables. Argument can be anMVar object,a list ofVar objects, orNone (None uses allvariables in the model). The length of the argument must match the sizeof the second dimension ofA.

  • sense – Constraint senses, provided as a NumPy 1-D ndarray or as asingle character. Valid values are'<','>', or'='.The length of the array must be equal the size of the first dimension ofA. A character will be promoted to an ndarray of the appropriatelength.

  • b – Right-hand side vector, stored as a NumPy 1-D ndarray. Thelength of the array must be equal the size of the first dimension ofA.

  • name – Name(s) for the new constraints. If a single string isprovided, it will be subscripted by the index of each constraint in thematrix. If a list or NumPy 1-D ndarray of strings is provided, it musthave a length equal to the size of the first dimension ofA, and thename for the\(i^{th}\) constraint will be given byname[i].

Returns:

MConstr object.

Example:
A=np.full((5,10),1)x=model.addMVar(10)b=np.full(5,1)model.addMConstr(A,x,'=',b)
addMQConstr(Q,c,sense,rhs,xQ_L=None,xQ_R=None,xc=None,name='')#

Add a quadratic constraint to the model using matrix semantics. Theadded constraint is\(x_{Q_L}' Q x_{Q_R} + c' x_c = \mbox{rhs}\)(except that the constraint sense is determined by thesenseargument). TheQ argument must be a NumPy ndarray or a SciPy sparsematrix.

Note that you will typically use overloaded operators to build and addconstraints using matrix semantics. The overloaded@ operator can beused to build alinearmatrixexpression orquadraticmatrixexpression. An overloadedcomparison operator can then be used to build aTempConstrobject, which is then passed toaddConstr.

Parameters:
  • Q – The quadratic constraint matrix - a NumPy 2-D ndarray or aSciPy sparse matrix.

  • c – The linear constraint vector - a NumPy 1-D ndarray. This can beNone if there are no linear terms.

  • sense – Constraint sense. Valid values are'<','>', or'='.

  • rhs – Right-hand-side value.

  • xQ_L – Decision variables for quadratic terms; left multiplier forQ. Argument can be anMVar object, a list ofVarobjects, orNone (None uses all variables in the model). Thelength of the argument must match the size of the first dimension ofQ.

  • xQ_R – Decision variables for quadratic terms; right multiplier forQ. The length of the argument must match the size of the seconddimension ofQ.

  • xc – Decision variables for linear terms. Argument can be anMVar object, a list ofVar objects, orNone(None uses all variables in the model). The length of the argumentmust match the length ofc.

  • name – Name for new constraint.

Returns:

TheQConstr object.

Example:
Q=np.full((2,3),1)xL=model.addMVar(2)xR=model.addMVar(3)model.addMQConstr(Q,None,'<',1.0,xL,xR)
addMVar(shape,lb=0.0,ub=float('inf'),obj=0.0,vtype=GRB.CONTINUOUS,name='')#

Add anMVar object to a model. AnMVar acts like a NumPyndarray of Gurobi decision variables. AnMVar can have an arbitrarynumber of dimensions, defined by theshape argument.

You can use arithmetic operations withMVar objects to createlinearmatrixexpressions orquadraticmatrixexpressions, which can then beused to build linear or quadratic objectives or constraints.

The returnedMVar object supports standard NumPy indexingand slicing. An MVar of size\(1\) can be passed in all places wheregurobipy accepts aVar object.

Parameters:
  • shape – An int, or tuple of int. Theshape of the array.

  • lb – (optional) Lower bound(s) for new variables.

  • ub – (optional) Upper bound(s) for new variables.

  • obj – (optional) Objective coefficient(s) for new variables.

  • vtype – (optional) Variable type(s) for new variables.

  • name – (optional) Names for new variables. The given name will be subscripted by the indexof the generator expression, so if the index is an integer,c wouldbecomec[0],c[1], etc. Note that the generated names will bestored as ASCII strings, so you should avoid using names that containnon-ASCII characters. In addition, names that contain spaces arestrongly discouraged, because they can’t be written to LP format files.

The values of thelb,ub,obj, andvtype arguments caneither be scalars, lists, or ndarrays. Their shapes should match theshape of the newMVar object, or they should be broadcastable to thegiven shape.

Thename argument can either be a single string, used as a commonbase name that will be suffixed for each variable by its indices, or anndarray of strings matching the shape of the newMVar object.

Returns:

NewMVar object.

Example:
# Add a 4-by-2 matrix binary variablex=model.addMVar((4,2),vtype=GRB.BINARY)# Add a vector of three variables with non-default lower boundsy=model.addMVar((3,),lb=[-1,-2,-1])
addQConstr(lhs,sense=None,rhs=None,name='')#

Add a quadratic constraint to a model.

Important

Gurobi can handle both convex and non-convex quadraticconstraints. The differences between them can be both important andsubtle. Refer tothis discussion foradditional information.

Parameters:
  • lhs – Left-hand side for new quadratic constraint. Can be aconstant, aVar, aLinExpr, or aQuadExpr.

  • sense – Sense for new quadratic constraint (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhs – Right-hand side for new quadratic constraint. Can be aconstant, aVar, aLinExpr, or aQuadExpr.

  • name – Name for new constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New quadratic constraint object.

Example:
model.addQConstr(x*x+y*y,GRB.LESS_EQUAL,z*z,"c0")model.addQConstr(x*x+y*y<=2.0,"c1")
addRange(expr,lower,upper,name='')#

Add a range constraint to a model. A range constraint states that thevalue of the input expression must be between the specifiedlowerandupper bounds in any solution.

Note that range constraints are stored internally as equalityconstraints. We add an extra variable to the model to capture the rangeinformation. Thus, theSense attribute on a range constraintwill always beGRB.EQUAL. In particular introducing a rangeconstraint

\[L \leq a^T x \leq U\]

is equivalent to adding a slack variable\(s\) and the followingconstraints

\[\begin{split}\begin{array}{rl} a^T x + s & = U \\ 0 \leq s & \leq U - L.\end{array}\end{split}\]
Parameters:
  • expr – Linear expression for new range constraint. Can be aVar or aLinExpr.

  • lower – Lower bound for linear expression.

  • upper – Upper bound for linear expression.

  • name – Name for new constraint. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Returns:

New constraint object.

Example:
# 1 <= x + y <= 2model.addRange(x+y,1.0,2.0,"range0")# overloaded formsmodel.addConstr(x+y==[1.0,2.0],name="range0")
addSOS(type,vars,wts=None)#

Add an SOS constraint to the model. Please refer tothis section for details on SOSconstraints.

Parameters:
  • type – SOS type (can beGRB.SOS_TYPE1 orGRB.SOS_TYPE2).

  • vars – List of variables that participate in the SOS constraint.

  • weights – (optional) Weights for the variables in the SOSconstraint. Default weights are 1, 2, …

Returns:

NewSOS object.

Example:
model.addSOS(GRB.SOS_TYPE1,[x,y,z],[1,2,4])
addVar(lb=0.0,ub=float('inf'),obj=0.0,vtype=GRB.CONTINUOUS,name='',column=None)#

Add a decision variable to a model.

Parameters:
  • lb – (optional) Lower bound for new variable.

  • ub – (optional) Upper bound for new variable.

  • obj – (optional) Objective coefficient for new variable.

  • vtype – (optional) Variable type for new variable(GRB.CONTINUOUS,GRB.BINARY,GRB.INTEGER,GRB.SEMICONT,orGRB.SEMIINT).

  • name – (optional) Name for new variable. Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

  • column – (optional) Column object that indicates the set ofconstraints in which the new variable participates, and the associatedcoefficients.

Returns:

New variable object.

Example:
x=model.addVar()# all default argumentsy=model.addVar(vtype=GRB.INTEGER,obj=1.0,name="y")# arguments by namez=model.addVar(0.0,1.0,1.0,GRB.BINARY,"z")# arguments by position
addVars(*indices,lb=0.0,ub=float('inf'),obj=0.0,vtype=GRB.CONTINUOUS,name='')#

Add multiple decision variables to a model.

Returns a Gurobitupledict object that contains the newlycreated variables. The keys for thetupledict are derived from theindices argument(s). The arguments for this method can take severaldifferent forms, which will be described now.

The first arguments provide the indices that will be used as keys toaccess the variables in the returnedtupledict. In its simplestversion, you would specify one or more integer values, and this methodwould create the equivalent of a multi-dimensional array of variables.For example,x=model.addVars(2,3) would create six variables,accessed asx[0,0],x[0,1],x[0,2],x[1,0],x[1,1],andx[1,2].

In a more complex version, you can specify arbitrary lists of immutableobjects, and this method will create variables for each member of thecross product of these lists. For example,x=model.addVars([3,7],['a','b','c']) would create sixvariables, accessed asx[3,'a'],x[7,'c'], etc.

You can also provide your own list of tuples as indices. For example,x=model.addVars([(3,'a'),(3,'b'),(7,'b'),(7,'c')]) would beaccessed in the same way as the previous example (x[3,'a'],x[7,'c'], etc.), except that not all combinations will be present.This is typically how sparse indexing is handled.

Note that while the indices can be provided as multiple lists ofobjects, or as a list of tuples, the member values for a specific indexmust always be scalars (int,float,string, …). Forexample,x=model.addVars([(1,3),7],['a']) is not allowed, sincethe first argument for the first member would be(1,3). Similarly,x=model.addVars([((1,3),'a'),(7,'a')]) is also not allowed.

The named arguments (lb,obj, etc.) can take several forms. Ifyou provide a scalar value (or use the default), then every variablewill use that value. Thus, for example,lb=1.0 will give everycreated variable a lower bound of 1.0. Note that a scalar value for thename argument has a special meaning, which will be discussed separately.

You can also provide a Pythondict as the argument. In that case,the value for each variable will be pulled from the dict, using theindices argument to build the keys. For example, if the variablescreated by this method are indexed asx[i,j], then thedictprovided for the argument should have an entry for each possible(i,j) value.

Finally, if yourindices argument is a single list, you can providea Pythonlist of the same length for the named arguments. For eachvariable, it will pull the value from the corresponding position in thelist.

As noted earlier, thename argument is special. If you provide ascalar argument for the name, that argument will be transformed to havea subscript that corresponds to the index of the associated variable.For example, if you dox=model.addVars(2,3,name="x"), thevariables will get namesx[0,0],x[0,1], etc.

Parameters:
  • indices – Indices for accessing the new variables.

  • lb – (optional) Lower bound(s) for new variables.

  • ub – (optional) Upper bound(s) for new variables.

  • obj – (optional) Objective coefficient(s) for new variables.

  • vtype – (optional) Variable type(s) for new variables(GRB.CONTINUOUS,GRB.BINARY,GRB.INTEGER,GRB.SEMICONT, orGRB.SEMIINT).

  • name – (optional) Names for new variables. The given name will be subscripted by the indexof the generator expression, so if the index is an integer,c wouldbecomec[0],c[1], etc. Note that the generated names will bestored as ASCII strings, so you should avoid using names that containnon-ASCII characters. In addition, names that contain spaces arestrongly discouraged, because they can’t be written to LP format files.

Returns:

Newtupledict object that contains the new variablesas values, using the provided indices as keys.

Example:
# 3-D array of binary variablesx=model.addVars(3,4,5,vtype=GRB.BINARY)# variables index by tuplelistl=tuplelist([(1,2),(1,3),(2,3)])y=model.addVars(l,ub=[1,2,3])# variables with predetermined namesz=model.addVars(3,name=["a","b","c"])
cbCut(lhs,sense,rhs)#

Add a new cutting plane to a MIP model from within a callback function.Note that this method can only be invoked when thewhere value onthe callback function is equal toGRB.Callback.MIPNODE (see theCallback Codes section for more information).

Cutting planes can be added at any node of the branch-and-cut tree.However, they should be added sparingly, since they increase the size ofthe relaxation model that is solved at each node and can significantlydegrade node processing speed.

Cutting planes are typically used to cut off the current relaxationsolution. To retrieve the relaxation solution at the current node, youshould first callcbGetNodeRel.

You should consider setting parameterPreCrush to value1 when adding your own cuts. This setting shuts off a few presolvereductions that can sometimes prevent your cut from being applied to thepresolved model (which would result in your cut being silently ignored).

One very important note: you should only add cuts that are implied bythe constraints in your model. If you cut off an integer solution thatis feasible according to the original model constraints,you are likelyto obtain an incorrect solution to your MIP problem.

Note that this method also accepts aTempConstr as its firstargument. This allows you to use operator overloading to createconstraints. SeeTempConstr for more information.

Parameters:
  • lhs – Left-hand side for new cut. Can be a constant, aVar, or aLinExpr.

  • sense – Sense for new cut (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhs – Right-hand side for new cut. Can be a constant, aVar, or aLinExpr.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:status=model.cbGet(GRB.Callback.MIPNODE_STATUS)ifstatus==GRB.OPTIMAL:rel=model.cbGetNodeRel(x)ifrel[0]+rel[1]>1.1:model.cbCut(x[0]+x[1]<=1)model.optimize(mycallback)
cbGet(what)#

Query the optimizer from within the user callback.

Parameters:

what – Integer code that indicates what type of information isbeing requested by the callback. The set of valid codes depends on thewhere value that is passed into the user callback function. Pleaserefer to theCallback Codes section for a listof possiblewhere andwhat values.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.SIMPLEX:print(model.cbGet(GRB.Callback.SPX_OBJVAL))model.optimize(mycallback)
cbGetNodeRel(vars)#

Retrieve values from the node relaxation solution at the current node.Only available when thewhere value on the callback function is equal toGRB.Callback.MIPNODE, andGRB.Callback.MIPNODE_STATUS is equal toGRB.OPTIMAL (see theCallback Codessection for more information).

Note that the relaxation solutionretrieved at a node is not necessarily feasible for the user model.

Parameters:

vars – The variables whose relaxation values are desired. Can be avariable, a matrix variable, a list of variables or matrix variables, ora dict of variables.

Returns:

Values for the specified variables in the node relaxation forthe current node. The format will depend on the input argument (ascalar, an ndarray, a list of values or ndarrays, or a dict).

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:status=model.cbGet(GRB.Callback.MIPNODE_STATUS)ifstatus==GRB.OPTIMAL:print(model.cbGetNodeRel(x))model.optimize(mycallback)
cbGetSolution(vars)#

Retrieve values from the new MIP solution. Note that this method canonly be invoked when thewhere value on the callback function isequal toGRB.Callback.MIPSOL orGRB.Callback.MULTIOBJ (see theCallback Codes section for more information).

Parameters:

vars – The variables whose solution values are desired. Can be avariable, a matrix variable, a list of variables or matrix variables, ora dict of variables.

Returns:

Values for the specified variables in the solution. The formatwill depend on the input argument (a scalar, an ndarray, a list ofvalues or ndarrays, or a dict).

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPSOL:print(model.cbGetSolution(x))model.optimize(mycallback)
cbLazy(lhs,sense,rhs)#

Add a new lazy constraint to a MIP model from within a callbackfunction. Note that this method can only be invoked when thewherevalue on the callback function isGRB.Callback.MIPNODE orGRB.Callback.MIPSOL (see theCallback Codes section for more information).

Lazy constraints are typically used when the full set of constraints fora MIP model is too large to represent explicitly. By only including theconstraints that are actually violated by solutions found during thebranch-and-cut search, it is sometimes possible to find a proven optimalsolution while only adding a fraction of the full set of constraints.

You would typically add a lazy constraint by first querying the currentnode solution (by callingcbGetSolution from aGRB.Callback.MIPSOL callback, orcbGetNodeRel from aGRB.Callback.MIPNODE callback), and then callingcbLazy() to adda constraint that cuts off the solution. Gurobi guarantees that you willhave the opportunity to cut off any solutions that would otherwise beconsidered feasible.

MIP solutions may be generated outside of a MIP node. Thus, generatinglazy constraints is optional when thewhere value in the callbackfunction equalsGRB.Callback.MIPNODE. To avoid this, we recommend toalways check when thewhere value equalsGRB.Callback.MIPSOL.

Your callback should be prepared to cut off solutions that violate anyof your lazy constraints, including those that have already been added.Node solutions will usually respect previously added lazy constraints,but not always.

Note that you must set theLazyConstraints parameter ifyou want to use lazy constraints.

Note that this method also accepts aTempConstr as its firstargument. This allows you to use operator overloading to createconstraints. SeeTempConstr for more information.

Parameters:
  • lhs – Left-hand side for new lazy constraint. Can be a constant, aVar, or aLinExpr.

  • sense – Sense for new lazy constraint (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhs – Right-hand side for new lazy constraint. Can be a constant, aVar, or aLinExpr.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPSOL:sol=model.cbGetSolution([x[0],x[1]])ifsol[0]+sol[1]>1:model.cbLazy(x[0]+x[1]<=1)model.Params.LazyConstraints=1model.optimize(mycallback)
cbProceed()#

Generate a request to proceed to the next phase of the computation. Thisroutine can be called from any callback. Note that the request is onlyaccepted in a few phases of the algorithm, and it won’t be acted uponimmediately.

In the current Gurobi version, this callback allows you to proceed fromthe NoRel heuristic to the standard MIP search. You can determine thecurrent algorithm phase usingMIP_PHASE,MIPNODE_PHASE, orMIPSOL_PHASE queries from a callback.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPSOL:phase=model.cbGet(GRB.Callback.MIPSOL_PHASE)obj=model.cbGet(GRB.Callback.MIPSOL_OBJ)ifphase==GRB.PHASE_MIP_NORELandobj<=target_obj:model.cbProceed()# Terminate NoRel and proceed to standard MIP search after# 60 seconds, or sooner if the target objective is achieved.target_obj=100.0model.Params.NoRelHeurTime=60.0model.optimize(mycallback)
cbSetParam(paramname,newvalue)#

Allows to modifycallback settable parameters during a deterministic callback.

That is, when thewhere value isGRB.Callback.PRESOLVED,GRB.Callback.SIMPLEX,GRB.Callback.MIP,GRB.Callback.MIPSOL,GRB.Callback.MIPNODE,GRB.Callback.BARRIER, orGRB.Callback.MULTIOBJ (see theCallback Codes section for more information)

In case of a remote server, the change of a parameter from within acallback may not be taken into account immediately.

Parameters:
  • paramname – String containing the name of parameter that you wouldlike to modify.

  • newvalue – Desired new value for the parameter.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:model.cbSetParam("TimeLimit",10)model.optimize(mycallback)
cbSetSolution(vars,solution)#

Import solution values for a heuristic solution. Only available when thewhere value on the callback function is equal toGRB.Callback.MIP,GRB.Callback.MIPNODE, orGRB.Callback.MIPSOL (see theCallback Codes section for more information).

When you specify a heuristic solution from a callback, variablesinitially take undefined values. You should use this method to specifyvariable values. You can make multiple calls tocbSetSolution fromone callback invocation to specify values for multiple sets ofvariables. After the callback, if values have been specified for anyvariables, the Gurobi Optimizer will try to compute a feasible solutionfrom the specified values, possibly filling in values for variableswhose values were left undefined. You can also optionally callcbUseSolution within your callback function to try toimmediately compute a feasible solution from the specified values.

In the context of a Compute Server environment, for performance reasons,the solutions sent throughcbSetSolution are not necessarily processed bythe Compute Server immediately. They may show up in the solving processa bit later after the client callback has sent them. In extreme cases,it could even be that the Compute Server optimization job terminatesbefore it processes the user solution.

Parameters:
  • vars – The variables whose values are being set. This can be a listof variables or a single variable.

  • solution – The desired values of the specified variables in the newsolution.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:model.cbSetSolution(x,x_values)model.cbSetSolution(y,y_values)model.optimize(mycallback)
cbStopOneMultiObj(objcnt)#

Interrupt the optimization process of one of theoptimization steps in a multi-objective MIP problem without stopping thehierarchical optimization process. Only available for multi-objective MIPmodels and when the where member variable is not equal to GRB.Callback.MULTIOBJ(see theCallback Codes section for moreinformation).

You would typically stop amulti-objective optimization step by querying the last finished numberof multi-objectives steps, and using that number to stop the currentstep and move on to the next hierarchical objective (if any) as shown inthe following example:

importtimeclassCallback:def__init__(self,max_seconds_per_objective):self.max_seconds=max_seconds_per_objectiveself.obj_count=0self.start_time=time.time()def__call__(self,model,where):ifwhere==GRB.Callback.MULTIOBJ:# Update current objective numberself.obj_count=model.cbGet(GRB.Callback.MULTIOBJ_OBJCNT)# Reset start time to current timeself.start_time=time.time()# Stop current multi-objective pass if too much time# has elapsedeliftime.time()-self.start_time>self.max_seconds:model.cbStopOneMultiObj(self.obj_count)mycallback=Callback(max_seconds_per_objective=1000.0)model.optimize(mycallback)

You should refer to the section onMultiple Objectives for information onhow to specify multiple objective functions and control the trade-offbetween them.

Parameters:

objnum – The number of the multi-objective optimizationstep to interrupt. For processes running locally, this argument can have the specialvalue -1, meaning to stop the current step.

cbUseSolution()#

Once you have imported solution values usingcbSetSolution,you can optionally callcbUseSolution in aGRB.Callback.MIPNODEcallback to immediately use these values to try to compute a heuristicsolution. Alternatively, you can callcbUseSolution in aGRB.Callback.MIP orGRB.Callback.MIPSOL callback, which willstore the solution until it can be processed internally.

Returns:

The objective value for the solution obtained from your solutionvalues. It equalsGRB.INFINITY if no improved solution is found orthe method has been called from a callback other thanGRB.Callback.MIPNODE as, in these contexts, the solution is storedinstead of being processed immediately.

Example:
defmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:model.cbSetSolution(vars,newsolution)objval=model.cbUseSolution()model.optimize(mycallback)
chgCoeff(constr,var,newvalue)#

Change one coefficient in the model. The desired change is capturedusing aVar object, aConstr object, and a desired coefficientfor the specified variable in the specified constraint. If you makemultiple changes to the same coefficient, the last one will be applied.

Note that, due to our lazy update approach,the change won’t actually take effect until you update the model (usingModel.update), optimize the model (usingModel.optimize), or write the model to disk (usingModel.write).

Parameters:
  • constr – Constraint for coefficient to be changed.

  • var – Variable for coefficient to be changed.

  • newvalue – Desired new value for coefficient.

Example:
model.chgCoeff(c0,x,2.0)
close()#

Free all resources associated with this Model object. This method is asynonym fordispose.

After this method is called, this Model object must no longer be used.

Example:
env=Env()model=read("misc07.mps",env)model.optimize()model.close()env.close()
computeIIS(callback=None,wheres=None)#

Compute an Irreducible Inconsistent Subsystem (IIS).

An IIS is a subset of the constraints and variable bounds with thefollowing properties:

  • It is still infeasible, and

  • If a single constraint or bound is removed, the subsystem becomesfeasible.

Note that an infeasible model may have multiple IISs. The one returnedby Gurobi is not necessarily the smallest one; there may exist otherswith fewer constraints or bounds.

IIS results are returned in a number of attributes:IISConstr,IISLB,IISUB,IISSOS,IISQConstr, andIISGenConstr.Each indicates whether the corresponding model element is a member ofthe computed IIS.

Note that for models with general function constraints, piecewise-linearapproximation of the constraints may cause unreliable IIS results.

TheIIS log provides information about theprogress of the algorithm, including a guess at the eventual IIS size.

Termination parameters such asTimeLimit,WorkLimit,MemLimit, andSoftMemLimit are considered when computing an IIS. If an IIScomputation is interrupted before completion or stops due to a terminationparameter, Gurobi will return the smallest infeasible subsystem found to thatpoint. The model attributeIISMinimal can be used to check whetherthe computed IIS is minimal.

TheIISConstrForce,IISLBForce,IISUBForce,IISSOSForce,IISQConstrForce, andIISGenConstrForce attributesallow you mark model elements to either include or exclude from thecomputed IIS. Setting the attribute to 1 forces the correspondingelement into the IIS, setting it to 0 forces it out of the IIS, andsetting it to -1 allows the algorithm to decide.

To give an example of when these attributes might be useful, considerthe case where an initial model is known to be feasible, but it becomesinfeasible after adding constraints or tightening bounds. If you areonly interested in knowing which of the changes caused theinfeasibility, you can force the unmodified bounds and constraints intothe IIS. That allows the IIS algorithm to focus exclusively on the newconstraints, which will often be substantially faster.

Note that setting any of theForce attributes to 0 may make theresulting subsystem feasible, which would then make it impossible toconstruct an IIS. Trying anyway will result in aIIS_NOT_INFEASIBLE error. Similarly, settingthis attribute to 1 may result in an IIS that is not irreducible. Moreprecisely, the system would only be irreducible with respect to themodel elements that have force values of -1 or 0.

This method populates theIISConstr,IISQConstr,andIISGenConstr constraint attributes, theIISSOS, SOS attribute, and theIISLB andIISUB variable attributes. You can also obtain informationabout the results of the IIS computation by writing an.ilp formatfile (seeModel.write). This file contains only theIIS from the original model.

Use theIISMethod parameter to adjust the behavior ofthe IIS algorithm.

Note that this method can be used to compute IISs for both continuousand MIP models.

Parameters:
  • callback – Callback function. The callback function should take twoarguments,model andwhere. While the IIS algorithm is running,the function will be called periodically, withmodel set to themodel being optimized, andwhere indicating where in theoptimization the callback is called from. See theCallbacks section for additional information.

  • wheres – A list ofwhere codes to enable in the callback. Ifthis argument is omitted, then the callback may be called for anywhere code. SeeCallback Codes for a listing of allsuch codes.

Note

Even if thePOLLING bit is not setin thewheres bit vector, the callback may still be invoked withwhere set to that value.

Example:
model.computeIIS()model.write("model.ilp")
convertToFixed()#

Turn the MIP model into a continuousone, in place.A solution (e.g. obtained through a call to theoptimize method) or a MIP start must beavailable in the MIP model. If no solution is available, the MIP startspecified withStartNumber is used.

In the model, each integer variable is fixed to the value that variable takesin the MIP solution or MIP start. In addition, continuous variables may befixed to satisfy SOS or general constraints. The result is that the model hasneither integrality constraints, SOS constraints, nor general constraints anymore.

Note

While the fixed problem is always a continuous model, it may contain anon-convex quadratic objective or non-convex quadratic constraints. As aresult, it may still be solved using the MIP algorithm.

Note

An error is raised if the converted model contains more than oneobjective or scenario, or if the model contains concurrent environmentsor tune environments.

copy(targetenv=None)#

Copy a model.

With no arguments, the copy will live in the same environment as theoriginal model. Provide an argument to copy an existing model to adifferent environment, typically to enable different threads to operateon different versions of the same model, since multiple threads can notsimultaneously work within the same environment.

Note that this method itself is not thread safe, so you should eithercall it from the main thread or protect access to it with a lock.

Note that pending updates will not be applied to the model, so youshould callupdate before copying if you would like those to be includedin the copy.

For Compute Server users, note that you can copy a model from a clientto a Compute Server environment, but it is not possible to copy modelsfrom a Compute Server environment to another (client or Compute Server)environment.

Parameters:

targetenv – (optional) Environment to copy the model into.

Returns:

Copy of model.

Example:
model.update()# If you have unstaged changes in the modelcopy=model.copy()
discardConcurrentEnvs()#

Discard concurrent environments for a model.

The concurrent environments created bygetConcurrentEnv willbe used by every subsequent call to the concurrent optimizer until theconcurrent environments are discarded.

Example:
env0=model.getConcurrentEnv(0)env1=model.getConcurrentEnv(1)env0.setParam('Method',0)env1.setParam('Method',1)model.optimize()model.discardConcurrentEnvs()
discardMultiobjEnvs()#

Discard all multi-objective environments associated with the model, thusrestoring multi objective optimization to its default behavior.

Please refer to the discussion ofMultiple Objectives for information onhow to specify multiple objective functions and control the trade-offbetween them.

UsegetMultiobjEnv to create a multi-objective environment.

Example:
env0=model.getMultiobjEnv(0)env1=model.getMultiobjEnv(1)env0.setParam('Method',2)env1.setParam('Method',1)model.optimize()model.discardMultiobjEnvs()
dispose()#

Free all resources associated with this Model object. This method is asynonym forclose.

After this method is called, this Model object must no longer be used.

Example:
env=gp.Env()model=gp.read("misc07.mps",env)model.optimize()model.dispose()env.dispose()
feasRelaxS(relaxobjtype,minrelax,vrelax,crelax)#

Modifies theModel object to create a feasibility relaxation. Notethat you need to calloptimize on the result to compute theactual relaxed solution. Note also that this is a simplified version ofthis method - usefeasRelax for more control over therelaxation performed.

The feasibility relaxation is a model that, when solved, minimizes theamount by which the solution violates the bounds and linear constraintsof the original model. This method provides a number of options forspecifying the relaxation.

If you specifyrelaxobjtype=0, the objective of the feasibilityrelaxation is to minimize the sum of the magnitudes of the bound andconstraint violations.

If you specifyrelaxobjtype=1, the objective of the feasibilityrelaxation is to minimize the sum of the squares of the bound andconstraint violations.

If you specifyrelaxobjtype=2, the objective of the feasibilityrelaxation is to minimize the total number of bound and constraintviolations.

To give an example, if a constraint is violated by 2.0, it wouldcontribute2.0 to the feasibility relaxation objective forrelaxobjtype=0, it would contribute2.0*2.0 forrelaxobjtype=1, and it would contribute1.0 forrelaxobjtype=2.

Theminrelax argument is a boolean that controls the type offeasibility relaxation that is created. Ifminrelax=False,optimizing the returned model gives a solution that minimizes the costof the violation. Ifminrelax=True, optimizing the returned modelfinds a solution that minimizes the original objective, but only fromamong those solutions that minimize the cost of the violation. Note thatfeasRelaxS must solve an optimization problem to find the minimumpossible relaxation whenminrelax=True, which can be quiteexpensive.

For an example of how this routine transforms a model, and more detailsabout the variables and constraints created, please seethis section.

Note that this is a destructive method: it modifies the model on whichit is invoked. If you don’t want to modify your original model, usecopy to create a copy before invoking this method.

Parameters:
  • relaxobjtype – The cost function used when finding the minimum costrelaxation.

  • minrelax – The type of feasibility relaxation to perform.

  • vrelax – Indicates whether variable bounds can be relaxed.

  • crelax – Indicates whether constraints can be relaxed.

Returns:

Zero ifminrelax is False. Ifminrelax is True, thereturn value is the objective value for the relaxation performed. If thevalue is less than 0, it indicates that the method failed to create thefeasibility relaxation.

Example:
ifmodel.status==GRB.INFEASIBLE:model.feasRelaxS(1,False,False,True)model.optimize()
feasRelax(relaxobjtype,minrelax,vars,lbpen,ubpen,constrs,rhspen)#

Modifies theModel object to create a feasibility relaxation. Notethat you need to calloptimize on the result to compute theactual relaxed solution. Note also that this is a more complex versionof this method - usefeasRelaxS for a simplified version.

The feasibility relaxation is a model that, when solved, minimizes theamount by which the solution violates the bounds and linear constraintsof the original model. This method provides a number of options forspecifying the relaxation.

If you specifyrelaxobjtype=0, the objective of the feasibilityrelaxation is to minimize the sum of the weighted magnitudes of thebound and constraint violations. Thelbpen,ubpen, andrhspen arguments specify the cost per unit violation in the lowerbounds, upper bounds, and linear constraints, respectively.

If you specifyrelaxobjtype=1, the objective of the feasibilityrelaxation is to minimize the weighted sum of the squares of the boundand constraint violations. Thelbpen,ubpen, andrhspenarguments specify the coefficients on the squares of the lower bound,upper bound, and linear constraint violations, respectively.

If you specifyrelaxobjtype=2, the objective of the feasibilityrelaxation is to minimize the weighted count of bound and constraintviolations. Thelbpen,ubpen, andrhspen arguments specifythe cost of violating a lower bound, upper bound, and linear constraint,respectively.

To give an example, if a constraint withrhspen valuep isviolated by 2.0, it would contribute2*p to the feasibilityrelaxation objective forrelaxobjtype=0, it would contribute2*2*p forrelaxobjtype=1, and it would contributep forrelaxobjtype=2.

Theminrelax argument is a boolean that controls the type offeasibility relaxation that is created. Ifminrelax=False,optimizing the returned model gives a solution that minimizes the costof the violation. Ifminrelax=True, optimizing the returned modelfinds a solution that minimizes the original objective, but only fromamong those solutions that minimize the cost of the violation. Note thatfeasRelax must solve an optimization problem to find the minimumpossible relaxation whenminrelax=True, which can be quiteexpensive.

For an example of how this routine transforms a model, and more detailsabout the variables and constraints created, please seethis section.

Note that this is a destructive method: it modifies the model on whichit is invoked. If you don’t want to modify your original model, usecopy to create a copy before invoking this method.

Parameters:
  • relaxobjtype – The cost function used when finding the minimum costrelaxation.

  • minrelax – The type of feasibility relaxation to perform.

  • vars – Variables whose bounds are allowed to be violated.

  • lbpen – Penalty for violating a variable lower bound. One entry foreach variable in argumentvars.

  • ubpen – Penalty for violating a variable upper bound. One entry foreach variable in argumentvars.

  • constrs – Linear constraints that are allowed to be violated.

  • rhspen – Penalty for violating a linear constraint. One entry foreach constraint in argumentconstrs.

Returns:

Zero ifminrelax is False. Ifminrelax is True, thereturn value is the objective value for the relaxation performed. If thevalue is less than 0, it indicates that the method failed to create thefeasibility relaxation.

Example:
ifmodel.status==GRB.INFEASIBLE:vars=model.getVars()ubpen=[1.0]*model.numVarsmodel.feasRelax(1,False,vars,None,ubpen,None,None)model.optimize()
fixed()#

Create the fixed model associated witha MIP model.A solution (e.g. obtained through a call to theoptimize method) or a MIP start must beavailable in the MIP model. If no solution is available, the MIP startspecified withStartNumber is used.

In the model, each integer variable is fixed to the value that variable takesin the MIP solution or MIP start. In addition, continuous variables may befixed to satisfy SOS or general constraints. The result is that the model hasneither integrality constraints, SOS constraints, nor general constraints anymore.

Note

While the fixed problem is always a continuous model, it may contain anon-convex quadratic objective or non-convex quadratic constraints. As aresult, it may still be solved using the MIP algorithm.

Note

On a multi-objective model, all but the first objectives are ignored. Allscenarios are ignored as well, if any.

Returns:

Fixed model associated with calling object.

Example:
fixed=model.fixed()
getA()#

Query the linear constraint matrix of the model. You’ll need to havescipy installed for this function to work.

Returns:

The matrix as ascipy.sparse.csr_matrix.

Example:
A=model.getA()sense=numpy.array(model.getAttr("Sense"))# extract sub matrices of (in)equality constraintsAeq=A[sense=='=',:]Ale=A[sense=='<',:]Age=A[sense=='>',:]
getQ()#

Query the quadratic objective matrix of the model. You’ll need to havescipy installed for this function to work.

Returns:

The matrix as ascipy.sparse.coo_matrix in uppertriangular form.

Example:
Q=model.getQ()
getQCMatrices(qc)#

Query the quadratic and linear parts of a quadratic constraint assparse matrices. This method returns\(Q\) and\(c\) definingthe left hand-side of the constraintqc in the form

\[x^T Q x + c^T x\]

where\(x\) is a column vector of all variables in the model.

You’ll need to havescipy installed for this function to work.

Parameters:

qc – AQConstr object whose terms are being queried

Returns:

A tuple(Q,c). For a model withN variables,Q isanNxNscipy.sparse.coo_matrix in upper triangularform storing the quadratic part of the constraint, andc is anNx1scipy.sparse.csc_matrix storing the linear partof the constraint.

Example:
Q,c=model.getQCMatrices(qc)
getAttr(attrname,objs=None)#

Query the value of an attribute. When called with a single argument itreturns the current value(s) of the given attribute. For model attributes,this is a single value. For other attribute types, this is a listcontaining the attribute value for all associated variables or constraints,ordered by their index in the model.

When called with two arguments this methodreturns the value of an attribute for either a list or a dictionarycontaining either variables or constraints. If called with a list, theresult is a list. If called with a dictionary, the result is adictionary that uses the same keys, but is populated with the requestedattribute values. The full list of available attributes can be found intheAttributes section.

Raises anAttributeError if the requested attribute doesn’t exist orcan’t be queried. Raises aGurobiError if there is a problem withtheModel object.

Parameters:
  • attrname – Name of the attribute.

  • objs – (optional) List or dictionary containing either constraintsor variables

Example:
# Number of integer variables in the model (model attribute)print(model.NumIntVars)print(model.getAttr("NumIntVars"))print(model.getAttr(GRB.Attr.NumIntVars))# Dictionary of solution values for a subset of variablesx=model.addVars(...)...model.optimize()solution=model.getAttr("X",x)# Solution values for all variables in the modelsolution_all=model.getAttr("X")# Dual values for all constraints in the modelduals_all=model.getAttr("Pi")
getCoeff(constr,var)#

Query the coefficient of variablevar in linear constraintconstr (note that the result can be zero).

Parameters:
  • constr – The requested constraint.

  • var – The requested variable.

Returns:

The current value of the requested coefficient.

Example:
print(model.getCoeff(constr,var))
getCol(var)#

Retrieve the list of constraints in which a variable participates, andthe associated coefficients. The result is returned as aColumn object.

Parameters:

var – The variable of interest.

Returns:

AColumn object that captures the set of constraintsin which the variable participates.

Example:
print(model.getCol(model.getVars()[0]))
getConcurrentEnv(num)#

Create/retrieve a concurrent environment for a model.

This method provides fine-grained control over the concurrent optimizer.By creating your own concurrent environments and setting appropriateparameters on these environments (e.g., theMethodparameter), you can control exactly which strategies the concurrentoptimizer employs. For example, if you create two concurrentenvironments, and setMethod to primal simplex for one and dualsimplex for the other, subsequent concurrent optimizer runs will use thetwo simplex algorithms rather than the default choices.

Note that you must create contiguously numbered concurrent environments,starting withnum=0. For example, if you want three concurrentenvironments, they must be numbered 0, 1, and 2.

Once you create concurrent environments, they will be used for everysubsequent concurrent optimization on that model. UsediscardConcurrentEnvs to revert back to default concurrentoptimizer behavior.

Parameters:

num – (int) The concurrent environment number.

Returns:

The concurrent environment for the model.

Example:
env0=model.getConcurrentEnv(0)env1=model.getConcurrentEnv(1)env0.setParam('Method',0)env1.setParam('Method',1)model.optimize()model.discardConcurrentEnvs()
getConstrByName(name)#

Retrieve a linear constraint from its name. If multiple linearconstraints have the same name, this method chooses one arbitrarily.

Parameters:

name – Name of desired constraint.

Returns:

Constraint with the specified name.

Example:
c0=model.getConstrByName("c0")

Note

Retrieving constraint objects by name is not recommended in general. Whenadding constraints to a model, you should keep track of the returned objectsin your own data structures in order to retrieve them efficiently formodel building and extracting attribute values.

getConstrs()#

Retrieve a list of all linear constraints in the model.

Returns:

All linear constraints in the model.

Example:
constrs=model.getConstrs()c0=constrs[0]
getGenConstrMax(genconstr)#

Retrieve the data associated with a general constraint of type MAX.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrMax for a description of the semanticsof this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of the MAX constraint.

  • vars – (list of Var) Operand variables of the MAX constraint.

  • constant – (float) Additional constant operand of the MAXconstraint.

Returns:

A tuple (resvar, vars, constant) that contains the dataassociated with the general constraint:

Example:
# x5 = max(x1, x3, x4, 2.0)maxconstr=model.addGenConstrMax(x5,[x1,x3,x4],2.0,"maxconstr")model.update()(resvar,vars,constant)=model.getGenConstrMax(maxconstr)
getGenConstrMin(genconstr)#

Retrieve the data associated with a general constraint of type MIN.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrMin for a description of the semanticsof this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of the MIN constraint.

  • vars – (list of Var) Operand variables of the MIN constraint.

  • constant – (float) Additional constant operand of the MINconstraint.

Returns:

A tuple (resvar, vars, constant) that contains the dataassociated with the general constraint:

Example:
# x5 = min(x1, x3, x4, 2.0)minconstr=model.addGenConstrMin(x5,[x1,x3,x4],2.0,"minconstr")model.update()(resvar,vars,constant)=model.getGenConstrMin(minconstr)
getGenConstrAbs(genconstr)#

Retrieve the data associated with a general constraint of type ABS.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrAbs for a description of the semanticsof this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of ABS constraint.

  • argvar – (Var) Argument variable of ABS constraint.

Returns:

A tuple (resvar, argvar) that contains the data associated withthe general constraint:

Example:
# x5 = abs(x1)absconstr=model.addGenConstrAbs(x5,x1,"absconstr")model.update()(resvar,argvar)=model.getGenConstrAbs(absconstr)
getGenConstrAnd(genconstr)#

Retrieve the data associated with a general constraint of type AND.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrAnd for a description of the semanticsof this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of AND constraint.

  • vars – (list of Var) Operand variables of AND constraint.

Returns:

A tuple (resvar, vars) that contains the data associated withthe general constraint:

Example:
# x5 = and(x1, x3, x4)andconstr=model.addGenConstrAnd(x5,[x1,x3,x4],"andconstr")model.update()(resvar,vars)=model.getGenConstrAnd(andconstr)
getGenConstrOr(genconstr)#

Retrieve the data associated with a general constraint of type OR.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrOr for a description of the semantics ofthis general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of OR constraint.

  • vars – (list of Var) Operand variables of OR constraint.

Returns:

A tuple (resvar, vars) that contains the data associated withthe general constraint:

Example:
# x5 = or(x1, x3, x4)orconstr=model.addGenConstrOr(x5,[x1,x3,x4],"orconstr")model.update()(resvar,vars)=model.getGenConstrOr(orconstr)
getGenConstrNorm(genconstr)#

Retrieve the data associated with a general constraint of type NORM.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrNorm for a description of the semanticsof this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • resvar – (Var) Resultant variable of NORM constraint.

  • vars – (list of Var) Operand variables of NORM constraint.

  • which – (float) Which norm (possible values are 0, 1, 2, orGRB.INFINITY).

Returns:

A tuple (resvar, vars, which) that contains the data associatedwith the general constraint:

Example:
# x5 = norm2(x1, x3, x4)normconstr=model.addGenConstrNorm(x5,[x1,x3,x4],2.0,"normconstr")model.update()(resvar,vars,which)=model.getGenConstrNorm(normconstr)
getGenConstrIndicator(genconstr)#

Retrieve the data associated with a general constraint of type INDICATOR.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrIndicator for a description of thesemantics of this general constraint type.

Parameters:
  • genconstr – The general constraint object of interest.

  • binvar – (Var) Antecedent variable of indicator constraint.

  • binval – (Boolean) Value of antecedent variable that activates thelinear constraint.

  • expr – (LinExpr) LinExpr object containing the left-hand side ofthe constraint triggered by the indicator.

  • sense – (char) Sense of linear constraint triggered by theindicator (e.g.,GRB.LESS_EQUAL).

  • rhs – (float) Right-hand side of linear constraint triggered by theindicator.

Returns:

A tuple (binvar, binval, expr, sense, rhs) that contains thedata associated with the general constraint:

Example:
# x7 = 1 -> x1 + 2 x3 + x4 = 1indconstr=model.addGenConstrIndicator(x7,True,x1+2*x3+x4,GRB.EQUAL,1.0)model.update()(binvar,binval,expr,sense,rhs)=model.getGenConstrIndicator(indconstr)
getGenConstrPWL(genconstr)#

Retrieve the data associated with a general constraint of type PWL.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrPWL for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • xpts – (list of float) The\(x\) values for the points thatdefine the piecewise-linear function.

  • ypts – (list of float) The\(y\) values for the points thatdefine the piecewise-linear function.

Returns:

A tuple (xvar, yvar, xpts, ypts) that contains the dataassociated with the general constraint:

Example:
pwlconstr=model.addGenConstrPWL(x,y,[0,1,2],[1.5,0,3],"myPWLConstr")model.update()(xvar,yvar,xpts,ypts)=model.getGenConstrPWL(pwlconstr)
getGenConstrPoly(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type POLY.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrPoly for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • p – (list of float) The coefficients for polynomial function.

Returns:

A tuple (xvar, yvar, p) that contains the data associated withthe general constraint:

Example:
# y = 2 x^3 + 1.5 x^2 + 1polyconstr=model.addGenConstrPoly(x,y,[2,1.5,0,1])model.update()(xvar,yvar,p)=model.getGenConstrPoly(polyconstr)
getGenConstrExp(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type EXP.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrExp for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = exp(x)expconstr=model.addGenConstrExp(x,y)model.update()(xvar,yvar)=model.getGenConstrExp(expconstr)
getGenConstrExpA(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type EXPA.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrExpA for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The base of the function.

Returns:

A tuple (xvar, yvar, a) that contains the data associated withthe general constraint:

Example:
# y = 3^xexpaconstr=model.addGenConstrExpA(x,y,3.0,"expa")model.update()(xvar,yvar,a)=model.getGenConstrExpA(expaconstr)
getGenConstrLog(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type LOG.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrLog for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = ln(x)lnconstr=model.addGenConstrLog(x,y)model.update()(xvar,yvar)=model.getGenConstrLog(lnconstr)
getGenConstrLogA(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type LOGA.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrLogA for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The base of the function.

Returns:

A tuple (xvar, yvar, a) that contains the data associated withthe general constraint:

Example:
# y = log10(x)log10constr=model.addGenConstrLogA(x,y,10.0,"log10")model.update()(xvar,yvar,a)=model.getGenConstrLogA(log10constr)
getGenConstrLogistic(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type LOGISTIC.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrLogistic for a description of thesemantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = 1 / (1 + exp(-x))expconstr=model.addGenConstrLogistic(x,y)model.update()(xvar,yvar)=model.getGenConstrLogistic(expconstr)
getGenConstrPow(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type POW.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrPow for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

  • a – (float) The exponent of the function.

Returns:

A tuple (xvar, yvar, a) that contains the data associated withthe general constraint:

Example:
# y = x^3.5powconstr=model.addGenConstrPow(x,y,3.5,"gf")model.update()(xvar,yvar,a)=model.getGenConstrPow(powconstr)
getGenConstrSin(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type SIN.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrSin for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = sin(x)sinconstr=model.addGenConstrSin(x,y)model.update()(xvar,yvar)=model.getGenConstrSin(sinconstr)
getGenConstrCos(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type COS.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrCos for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = cos(x)cosconstr=model.addGenConstrCos(x,y)model.update()(xvar,yvar)=model.getGenConstrCos(cosconstr)
getGenConstrTan(genconstr)#

Deprecated since version 13.0:Usingfunction constraints is deprecated since version 13.0.Please usenonlinear constraints instead.

Retrieve the data associated with a general constraint of type TAN.Calling this method for a general constraint of a different type leadsto an exception. You can query theGenConstrType attribute to determine the typeof the general constraint.

See alsoaddGenConstrTan for a description of the semanticsof this general constraint type.

Parameters:
  • genc – The general constraint object.

  • xvar – (Var) The\(x\) variable.

  • yvar – (Var) The\(y\) variable.

Returns:

A tuple (xvar, yvar) that contains the data associated with thegeneral constraint:

Example:
# y = tan(x)tanconstr=model.addGenConstrTan(x,y)model.update()(xvar,yvar)=model.getGenConstrTan(tanconstr)
getGenConstrNL(genconstr)#

See alsoaddGenConstrNL for a description of the semanticsof this general constraint type.

Parameters:

genc (GenConstr) – The general constraint object.

Returns:

A tuple(resvar,expr) that contains the dataassociated with the general constraint.

Example:
nlconstr=model.addGenConstrNL(y,nlfunc.exp(x-1))model.update()(resvar,expr)=model.getGenConstrNL(nlconstr)
getGenConstrNLAdv(genconstr)#

See alsoaddGenConstrNLAdv for a description of thesemantics of this general constraint type. This is an advancedmethod which returns a nonlinear expression\(f(x)\) as anexpression tree specified in three listsopcode,data, andparent. Most users should usegetGenConstrNL toinspect nonlinear constraints in the model.

Parameters:

genc (GenConstr) – The general constraint object.

Returns:

A tuple(resvar,opcode,data,parent) that containsthe data associated with the general constraint.

Example:
nlconstr=model.addGenConstrNLAdv(y,[GRB.OPCODE_LOG,GRB.OPCODE_PLUS,GRB.OPCODE_VARIABLE,GRB.OPCODE_CONSTANT],[-1,-1,x,1],[-1,0,1,1],name="nl_constraint",)model.update()resvar,opcode,data,parent=model.getGenConstrNLAdv(nlconstr)
getGenConstrs()#

Retrieve a list of all general constraints in the model.

Returns:

All general constraints in the model.

Example:
gencons=model.getGenConstrs()forgcingencons:ifgc.GenConstrType==GRB.GENCONSTR_INDICATOR:(binvar,binval,expr,sense,rhs)=model.getGenConstrIndicator(gc)elifgc.GenConstrType==GRB.GENCONSTR_MAX:(resvar,vars,constant)=model.getGenConstrMax(gc)...
getJSONSolution()#

After a call tooptimize, this method returns the resulting solution andrelated model attributes as a JSON string. Please refer to theJSON solution format section for details.

Returns:

A JSON string.

Example:
model=gp.read('p0033.mps')model.optimize()print(model.getJSONSolution())
getMultiobjEnv(index)#

Create/retrieve a multi-objective environment for the optimization passwith the given index. This environment enables fine-grained control overthe multi-objective optimization process. Specifically, by changingparameters on this environment, you modify the behavior of theoptimization that occurs during the corresponding pass of themulti-objective optimization.

Each multi-objective environment starts with a copy of the current modelenvironment.

Please refer to the discussion ofMultiple Objectives for information onhow to specify multiple objective functions and control the trade-offbetween them.

Please refer to the discussion onCombining Blended and Hierarchical Objectivesfor information on the optimization passes to solve multi-objectivemodels.

UsediscardMultiobjEnvs to discard multi-objectiveenvironments and return to standard behavior.

Parameters:

index – (int) The optimization pass index, starting from 0.

Returns:

The multi-objective environment for that optimization pass whensolving the model.

Example:
env0=model.getMultiobjEnv(0)env1=model.getMultiobjEnv(1)env0.setParam('TimeLimit',100)env1.setParam('TimeLimit',10)model.optimize()model.discardMultiobjEnvs()
getObjective(index=None)#

Retrieve the model objective(s).

Call this with no argument to retrieve the primary objective, or with aninteger argument to retrieve the corresponding alternative objective.

Parameters:

index – (int, optional) The index for the requested alternativeobjective.

Returns:

The model objective. ALinExpr object for a linearobjective, or aQuadExpr object for a quadratic objective.Note that alternative objectives are always linear.

Example:
obj=model.getObjective()print(obj.getValue())
getParamInfo(paramname)#

Retrieve information about a Gurobi parameter, including the type, thecurrent value, the minimum and maximum allowed values, and the defaultvalue.

Please consult theparameter section for a complete list of Gurobiparameters, including descriptions of their purposes and their minimum,maximum, and default values.

Parameters:

paramname – String containing the name of the parameter ofinterest. The case ofparamname is ignored, as are underscores.

Returns:

Returns a 6-entry tuple that contains: the parameter name, theparameter type, the current value, the minimum value, the maximum value,and the default value.

Example:
print(model.getParamInfo('Heuristics'))

Deprecated since version 12.0:Wildcard name matching using'*' and'?' inparamname isdeprecated.

getPWLObj(var)#

Retrieve the piecewise-linear objective function for a variable. Thefunction returns a list of tuples, where each provides the\(x\) and\(y\) coordinates for the points that define the piecewise-linearobjective function.

Refer tothis discussion foradditional information on what the values in\(x\) and\(y\)mean.

Parameters:

var – AVar object that gives the variable whoseobjective function is being retrieved.

Returns:

The points that define the piecewise-linear objective function.

Example:
>print(model.getPWLObj(var))[(1,1),(2,2),(3,4)]
getQConstrs()#

Retrieve a list of all quadratic constraints in the model.

Returns:

All quadratic constraints in the model.

Example:
qconstrs=model.getQConstrs()qc0=qconstrs[0]
getQCRow(qconstr)#

Retrieve the left-hand side expression from a quadratic constraint. Theresult is returned as aQuadExpr object.

Parameters:

qconstr – The constraint of interest. AQConstr object,typically obtained fromaddQConstr orgetQConstrs.

Returns:

AQuadExpr object that captures the left-hand sideof the quadratic constraint.

Example:
print(model.getQCRow(model.getQConstrs()[0]))
getRow(constr)#

Retrieve the list of variables that participate in a constraint, and theassociated coefficients. The result is returned as aLinExprobject.

Parameters:

constr – The constraint of interest. AConstr object,typically obtained fromaddConstr orgetConstrs.

Returns:

ALinExpr object that captures the set of variablesthat participate in the constraint.

Example:
constrs=model.getConstrs()print(model.getRow(constrs[0]))
getSOS(sos)#

Retrieve information about an SOS constraint. The result is a tuple thatcontains the SOS type (1 or 2), the list of participating Var objects,and the list of associated SOS weights.

Parameters:

sos – The SOS constraint of interest. AnSOS object,typically obtained fromaddSOS orgetSOSs.

Returns:

A tuple that contains the SOS type (1 or 2), a list ofparticipating Var objects, and a list of associated SOS weights.

Example:
(sostype,vars,weights)=model.getSOS(model.getSOSs()[0])
getSOSs()#

Retrieve a list of all SOS constraints in the model.

Returns:

All SOS constraints in the model.

Example:
sos=model.getSOSs()forsinsos:print(model.getSOS(s))
getTuneResult()#

Use this routine to retrieve the results of a previoustunecall. Calling this method with argumentn causes tuned parameter setn to be copied into the model. Parameter sets are stored in order ofdecreasing quality, with parameter set 0 being the best. The number ofavailable sets is stored in attributeTuneResultCount.

Once you have retrieved a tuning result, you can calloptimize to use these parameter settings to optimize themodel, orwrite to write the changed parameters to a.prmfile.

Please refer to theparameter tuning section fordetails on the tuning tool.

Parameters:

n – The index of the tuning result to retrieve. The best result isavailable as index 0. The number of stored results is available inattributeTuneResultCount.

Example:
model.tune()foriinrange(model.tuneResultCount):model.getTuneResult(i)model.write('tune'+str(i)+'.prm')
getVarByName(name)#

Retrieve a variable from its name. If multiple variables have the samename, this method chooses one arbitrarily.

Parameters:

name – Name of desired variable.

Returns:

Variable with the specified name.

Example:
x0=model.getVarByName("x0")

Note

Retrieving variable objects by name is not recommended in general. Whenadding variables to a model, you should keep track of the returned objectsin your own data structures in order to retrieve them efficiently formodel building and extracting attribute values.

getVars()#

Retrieve a list of all variables in the model.

Returns:

All variables in the model.

Example:
vars=model.getVars()x0=vars[0]
message(msg)#

Append a string to the console and the Gurobi log file.

Parameters:

msg – String to append.

Note

This call has no effect unless theOutputFlag parameter is set. In addition, it is ignoredfrom within aMESSAGE callback (seeWHERE values)and logging callback. The console logging can becontroled withLogToConsole.

Example:
model.message('New message')
optimize(callback=None,wheres=None)#

Optimize a model. The algorithm used for theoptimization depends on the model type (simplex or barrier for acontinuous model; branch-and-cut for a MIP model). Upon successfulcompletion, this method will populate the solution related attributesof the model. See theAttributes section formore information on attributes. The algorithm will terminate early if itreaches any of the limits set bytermination parameters.

Please consultthis section for adiscussion of some of the practical issues associated with solving aprecisely defined mathematical model using finite-precisionfloating-point arithmetic.

Note that this method will process all pending model modifications.

Parameters:
  • callback – Callback function. The callback function should take twoarguments,model andwhere. During the optimization, thefunction will be called periodically, withmodel set to the modelbeing optimized, andwhere indicating where in the optimization thecallback is called from. See theCallbacks sectionfor additional information.

  • wheres – A list ofwhere codes to enable in the callback. Ifthis argument is omitted, then the callback may be called for anywhere code. SeeCallback Codes for a listing of allsuch codes.

Note

Even if thePOLLING bit is not setin thewheres bit vector, the callback may still be invoked withwhere set to that value.

Example:
# Optimize a modelmodel.optimize()# Optimize a model with a callback functiondefcallback(model,where):ifwhere==GRB.Callback.MIPSOL:solution=model.cbGetSolution(x)elifwhere==GRB.Callback.MIP:status=model.cbGet(GRB.Callback.MIP_NODCNT)...model.optimize(callback)# Allow only MIPSOL callbacks to invoke the callback functionmodel.optimize(callback,wheres=[GRB.Callback.MIPSOL])
optimizeAsync(callback=None,wheres=None)#

Optimize the model asynchronously. This method returns immediately, soyour code can continue to run other tasks while the optimization proceedsin the background. To check the state of the asynchronous optimization,query theStatus attribute for the model. A value ofGRB.INPROGRESS indicates that the optimization has not yet completed.When you are done with your foreground tasks, you must callsync to sync your foreground program with the asynchronousoptimization task.

Note that the set of Gurobi calls that you are allowed to make whileoptimization is running in the background is severely limited.Specifically, you can only perform attribute queries for a limited set ofattributes (listed below) or callterminate. Any other calls onthe running model,or on any other models that were built within the sameGurobi environment, will raise an exception.

Note that there are no such restrictions on models built in otherenvironments. Thus, for example, you could create multiple environments,and then have a single foreground program launch multiple simultaneousasynchronous optimizations, each in its own environment.

As already noted, you are allowed to query the value of theStatus attribute while an asynchronous optimization is inprogress. The other attributes that can be queried are:ObjVal,ObjBound,IterCount,NodeCount,BarIterCount, andNLBarIterCount. In each case, thereturned value reflects progress in the optimization to that point. Anyattempt to query the value of an attribute not on this list will raise anexception.

Youmust callsync before attempting to query anything else(including solutions) or performing any other operation on the model.If theModel object is garbage collected, disposed, or closed by acontext manager beforesync is called, the background optimization taskwill be immediately terminated and the model freed.

Note that this method will process all pending model modifications beforestarting the optimization.

Parameters:
  • callback – Callback function. The callback function should take twoarguments,model andwhere. During the optimization, thefunction will be called periodically, withmodel set to the modelbeing optimized, andwhere indicating where in the optimization thecallback is called from. See theCallbacks sectionfor additional information.

  • wheres – A list ofwhere codes to enable in the callback. Ifthis argument is omitted, then the callback may be called for anywhere code. SeeCallback Codes for a listing of allsuch codes.

Note

Even if thePOLLING bit is not setin thewheres bit vector, the callback may still be invoked withwhere set to that value.

Example:
importtimeimportgurobipyasgpfromgurobipyimportGRBwithgp.Env()asenv,gp.Model(env=env)asmodel:# Formulate model ...model.optimizeAsync()whilemodel.Status==GRB.INPROGRESS:time.sleep(0.1)print(f"{model.ObjVal=}{model.ObjBound=}")model.sync()# Query solution, process results
optimizeBatch()#

Submit a new batch request to the Cluster Manager. Returns the BatchID(a string), which uniquely identifies the job in the Cluster Manager andcan be used to query the status of this request (from this program orfrom any other). Once the request has completed, theBatchID canalso be used to retrieve the associated solution. To submit a batchrequest, you must tag at least one element of the model by setting oneof theVTag,CTag orQCTag attributes.For more details on batch optimization, please refer to theBatch Optimization section.

Note that this routine will process all pending model modifications.

Example:
# Submit batch requestbatchID=model.optimizeBatch()
Returns:

A unique string identifier for the batch request.

Params#

Get or set parameter values.

Example:
# Print the current value of the MIPFocus parameterprint(model.Params.MIPFocus)# Set a 10 second time limit for the next optimize() callmodel.Params.TimeLimit=10.0
presolve()#

Create the presolved version of a model. This method returns a new model,which is (almost) equivalent to the model solved by Gurobi internallyafter presolve has been performed.

Please note that the presolved modelcomputed by this function may be different from the presolved modelcomputed when optimizing the model.

Returns:

Presolved version of the original model, as a newModel object.

Example:
p=model.presolve()p.printStats()
printAttr(attrs,filter='*')#

Print the value of one or more attributes. Ifattrs is a constraintor variable attribute, print all non-zero values of the attribute, alongwith the associated constraint or variable names. Ifattrs is a listof attributes, print attribute values for all listed attributes. Themethod takes an optionalfilter argument, which allows you to selectwhich specific attribute values to print (by filtering on the constraintor variable name).

See theAttributes section for a list of allavailable attributes.

Parameters:
  • attrs – Name of attribute or attributes to print. The value can bea single attribute or a list of attributes. If a list is given, alllisted attributes must be of the same type (model, variable, orconstraint).

  • filter – (optional) Filter for values to print – name ofconstr/var must match filter to be printed.

Example:
model.printAttr('x')# all non-zero solution valuesmodel.printAttr('lb','x*')# bounds for vars whose names begin with 'x'model.printAttr(['lb','ub'])# lower and upper bounds
printQuality()#

Print statistics about the quality of the computed solution (constraintviolations, integrality violations, etc.).

For continuous models, the output will include the maximum unscaled andscaled violation, as well as the variable or constraint name associatedwith the worst unscaled violation. For MIP models, the output willinclude the maximum unscaled violation and the associated variable orconstraint name.

Example:
model.optimize()model.printQuality()
printStats()#

Print statistics about the model (number of constraints and variables,number of non-zeros in constraint matrix, smallest and largestcoefficients, etc.).

Example:
model.printStats()
read(filename)#

This method is the general entry point for importing data from a fileinto a model. It can be used to read basis files for continuous models,start vectors for MIP models, variable hints for MIP models, branchingpriorities for MIP models, or parameter settings.The type of dataread is determined by the file suffix. File formats are described in theFile Format section.

Note that reading a file doesnot process all pending modelmodifications. These modifications can be processed by callingModel.update.

Note also that this isnot the method to use if you want to read anew model from a file. For that, use theread command.

Parameters:

filename – Name of the file to read. The suffix on the filemust be either.bas (for an LP basis),.mst or.sol(for a MIP start),.hnt (for MIP hints),.ord (for apriority order),.attr (for a collection of attribute settings),or.prm (for a parameter file). The suffixmay optionally be followed by.zip,.gz,.bz2,.7z or.xz. The filename may contain* or? wildcards. No file is read whenno wildcard match is found. If more than one match is found,this method will attempt to read the first matching file.

Example:
model.read('input.bas')model.read('input.mst')
relax()#

Create the relaxation of a MIP model. This method returns a copy of theoriginal model, with all integer variables transformed into continuousvariables, and all SOS and general constraints removed. The originalmodel is not modified.

Returns:

Relaxation of the original model, as a newModel object.

Example:
r=model.relax()
remove(items)#

Remove variables, linear constraints, quadratic constraints, SOSconstraints, or general constraints from a model.

Parameters:

items – The items to remove from the model. Argument can be asingleVar,MVar,Constr,MConstr,QConstr,MQConstr,SOS, orGenConstr, or alist,tuple, ordict containing these objects. If the argument is adict, thevalues will be removed, not the keys.

Example:
model.remove(model.getVars()[0])model.remove(model.getVars()[0:10])model.remove(model.getConstrs()[0])model.remove(model.getConstrs()[1:3])model.remove(model.getQConstrs()[0])model.remove(model.getSOSs()[0])model.remove(model.getGenConstrs()[0])
reset(clearall=0)#

Reset the model to an unsolved state, discarding any previously computedsolution information.

Parameters:

clearall – (int, optional) A value of 1 discards additionalinformation that affects the solution process but not the actual model(currently MIP starts, variable hints, branching priorities, lazyflags, and partition information). The default value just discards thesolution.

Example:
model.reset(0)
resetParams()#

Reset all parameters to their default values.

Example:
model.resetParams()
setAttr(attrname,newvalue)#
setAttr(attrname,objects,newvalues)

Change the value of an attribute.

Call this method with two arguments, a model attribute name and ascalar value (i.e.,setAttr(attrname,newvalue)), to set a modelattribute.

Call this method with two arguments, an attribute name anda list or iterable of appropriate length, to set the valueof the given attribute for all associated variables or constraints. Forexample, for theStart variable attribute,newvalue musthave lengthmodel.NumVars. To set the same value for all associatedvariables or constraints, you can pass a scalar value in the secondargument.

Call it with three arguments (i.e.,setAttr(attrname,objects,newvalues)) to set attribute values for alist or dict of model objects (Var objects,Constr objects,etc.). To set the same value for all objects in the second argument, youcan pass a scalar value in the third argument. If the second argument isa list, the third argument should be a list of the same length. If thesecond argument is a dict, the third argument should be dict with avalue for every key from the second.

The full list of available attributes can be found in theAttributes section.

Raises anAttributeError if the specified attribute doesn’t exist orcan’t be set. Raises aGurobiError if there is a problem with theModel object.

Note that, due to our lazy update approach,the change won’t actually take effect until you update the model (usingModel.update), optimize the model (usingModel.optimize), or write the model to disk (usingModel.write).

Parameters:
  • attrname – Name of attribute to set.

  • objects – List of model objects (Var or Constr or …)

  • newvalue – Desired new value(s) for attribute.

Example:
model.objcon=0model.setAttr("objCon",0)model.setAttr(GRB.Attr.ObjCon,0)model.setAttr("LB",[0]*model.numVars)model.setAttr("RHS",[1.0]*model.numConstrs)x=model.addVars(...)...model.setAttr("vType",x,GRB.BINARY)
setMObjective(Q,c,constant,xQ_L=None,xQ_R=None,xc=None,sense=None)#

Set the model objective equal to a quadratic (or linear) expressionusing matrix semantics.

Note that you will typically use overloaded operators to set theobjective using matrix objects. The overloaded@ operator can beused to build alinearmatrixexpression or aquadraticmatrixexpression, which is thenpassed tosetObjective.

Parameters:
  • Q – The quadratic objective matrix - a NumPy 2-D dense ndarray ora SciPy sparse matrix. This can beNone if there are no quadraticterms.

  • c – The linear constraint vector - a NumPy 1-D ndarray. This canbeNone if there are no linear terms.

  • constant – Objective constant.

  • xQ_L – (optional) Decision variables for quadratic objectiveterms; left multiplier for Q. Argument can be anMVarobject, a list ofVar objects, orNone (None usesall variables in the model). The length of the argument must match thesize of the first dimension ofQ.

  • xQ_R – (optional) Decision variables for quadratic objectiveterms; right multiplier for Q. The length of the argument must matchthe size of the second dimension ofQ.

  • xc – (optional) Decision variables for linear objective terms.Argument can be anMVar object, a list ofVarobjects, orNone (None uses all variables in the model). Thelength of the argument must match the length ofc.

  • sense – (optional) Optimization sense (GRB.MINIMIZE forminimization,GRB.MAXIMIZE for maximization). Omit this argumentto use theModelSense attribute value to determine thesense.

Example:
c=np.full(10,1.0)xc=model.addMVar(10)model.setMObjective(None,c,0.0,None,None,xc,GRB.MAXIMIZE)Q=np.full((2,3),1.0)xL=model.addMVar(2)xR=model.addMVar(3)model.setMObjective(Q,None,0.0,xL,xR,None,GRB.MINIMIZE)
setObjective(expr,sense=None)#

Set the model objective equal to a linear or quadratic expression (formulti-objective optimization, seesetObjectiveN).

Note that you can also modify a linear model objective using theObj variable attribute. If you wish to mix and match thesetwo approaches, please note that this method will replace the existingobjective.

Parameters:
  • expr – New objective expression. Argument can be a linear orquadratic expression (an objective of typeLinExpr orQuadExpr).

  • sense – (optional) Optimization sense (GRB.MINIMIZE forminimization,GRB.MAXIMIZE for maximization). Omit this argumentto use theModelSense attribute value to determine thesense.

Example:
model.setObjective(x+y,GRB.MAXIMIZE)model.setObjective(x*x+y*y)
setObjectiveN(expr,index,priority=0,weight=1,abstol=1e-6,reltol=0,name='')#

Set an alternative optimization objective equal to a linear expression.

Please refer to the discussion ofMultiple Objectives for more informationon the use of alternative objectives.

Note that you can also modify an alternative objective using theObjN variable attribute. If you wish to mix and match thesetwo approaches, please note that this method replaces the entireexisting objective, while theObjN attribute can be used tomodify individual terms.

Parameters:
  • expr – (LinExpr) New alternative objective.

  • index – (int) Index for new objective. If you use an index of 0,this routine will change the primary optimization objective.

  • priority – (int, optional) Priority for the alternative objective.This initializes theObjNPriority attribute for thisobjective.

  • weight – (float, optional) Weight for the alternative objective.This initializes theObjNWeight attribute for thisobjective.

  • abstol – (float, optional) Absolute tolerance for the alternativeobjective. This initializes theObjNAbsTol attribute forthis objective.

  • reltol – (float, optional) Relative tolerance for the alternativeobjective. This initializes theObjNRelTol attribute forthis objective. This attribute is ignored for LP models.

  • name – (string, optional) Name of the alternative objective. Thisinitializes theObjNName attribute for this objective.Note thatname will be stored as an ASCIIstring. Thus, a name like ‘A\({\rightarrow}\)B’ will produce anerror, because ‘\({\rightarrow}\)‘ can not be represented as anASCII character. Note also that names that contain spaces are stronglydiscouraged, because they can’t be written to LP format files.

Example:
# Primary objective: x + 2 ymodel.setObjectiveN(x+2*y,index=0,priority=2)# Alternative, lower priority objectives: 3 y + z and x + zmodel.setObjectiveN(3*y+z,index=1,priority=1)model.setObjectiveN(x+z,index=2,priority=0)
setPWLObj(var,x,y)#

Set a piecewise-linear objective function for a variable.

The arguments to this method specify a list of points that define apiecewise-linear objective function for a single variable. Specifically,the\(x\) and\(y\) arguments give coordinates for the verticesof the function.

For additional details on piecewise-linear objective functions, refer tothis discussion.

Parameters:
  • var – AVar object that gives the variable whoseobjective function is being set.

  • x – The\(x\) values for the points that define thepiecewise-linear function. Must be in non-decreasing order.

  • y – The\(y\) values for the points that define thepiecewise-linear function.

Example:
model.setPWLObj(var,[1,3,5],[1,2,4])
setParam(paramname,newvalue)#

Set the value of a parameter to a new value. Note that this method onlyaffects the parameter setting for this model. Use global functionsetParam to change the parameter for all models.

You can also set parameters using theModel.Params class. Forexample, to set parameterMIPGap to value 0 for modelm, you cando eitherm.setParam('MIPGap',0) orm.Params.MIPGap=0.

Please consult theparameter section for a complete list of Gurobiparameters, including descriptions of their purposes and their minimum,maximum, and default values.

Parameters:
  • paramname – String containing the name of the parameter that youwould like to modify. The case ofparamname is ignored, as areunderscores.

  • newvalue – Desired new value for the parameter.

Example:
model.setParam("Heuristics",0.5)model.setParam(GRB.Param.Heuristics,0.5)

Deprecated since version 12.0:Wildcard name matching using'*' and'?' inparamname isdeprecated. Passing'default' asnewvalue is deprecated.

singleScenarioModel()#

Capture a single scenario from a multi-scenario model. Use theScenarioNumber parameter to indicate which scenario tocapture.

The model on which this method is invoked must be a multi-scenariomodel, and the result will be a single-scenario model.

Returns:

Model for a single scenario.

Example:
model.params.ScenarioNumber=0s=model.singleScenarioModel()
sync()#

Wait for a previous asynchronous optimization call to complete.

CallingoptimizeAsync returns control to the callerimmediately. The caller can perform other computations while optimizationproceeds, and can check on the progress of the optimization by querying alimited set of model attributes.

Thesync call blocks until the asynchronous optimization completes.Note thatsync is not interruptible. To maintain control by thecalling code you should verify that the optimization is completed bychecking themodel status before callingsync.

Thesync call raises aGurobiError if the optimizationitself ran into any problems. In other words, exceptions raised by thismethod are those thatoptimize itself would have raised if thesolve was run synchronously.

Note that you need to callsync even if you know that the asynchronousoptimization has already completed. Only aftersync is called can youperform other operations on the model, such as querying solutions. Youmust callsync before the corresponding model is freed.

Ifsync is called when an asynchronous optimization isnot runningfor this model, it has no effect and returns immediately.

Example:
importtimeimportgurobipyasgpfromgurobipyimportGRBwithgp.Env()asenv,gp.Model(env=env)asmodel:# Formulate model ...model.optimizeAsync()whilemodel.Status==GRB.INPROGRESS:time.sleep(0.1)print(f"{model.ObjVal=}{model.ObjBound=}")model.sync()# Query solution, process results
terminate()#

Generate a request to terminate the current optimization. This methodcan be called at any time during an optimization (from a callback, fromanother thread, from an interrupt handler, etc.). Note that, in general,the request won’t be acted upon immediately.

When the optimization stops, theStatus attribute will beequal toGRB_INTERRUPTED.

Example:
model.terminate()
tune(callback=None)#

Perform an automated search for parameter settings that improveperformance. Upon completion, this method stores the best parameter setsit found. The number of stored parameter sets can be determined byquerying the value of theTuneResultCount attribute. Theactual settings can be retrieved usinggetTuneResult.

Please refer to theparameter tuning section fordetails on the tuning tool.

Parameters:

callback – Callback function. The callback function should take twopositional arguments,tunercb andwhere. While the tuner isrunning, the function will be called periodically, withtunercbbeing aTunerCb object. Calling theterminate method of this object fromthe callback will terminate the tuner. SeeCallbacks in the Tunerfor additional information.

Example:
model.tune()
update()#

Process any pending model modifications.

Example:
model.update()
write(filename)#

This method is the general entry point for writing optimization data toa file. It can be used to write optimization models, solution vectors,basis vectors, start vectors, or parameter settings. The type of datawritten is determined by the file suffix. File formats are described intheFile Format section.

Note that writing a model to a file will process all pending modelmodifications. This is also true when writing other model informationsuch as solutions, bases, etc.

Note also that when you write a Gurobi parameter file (PRM), bothinteger or double parameters not at their default value will be saved,but no string parameter will be saved into the file.

Finally, note that whenIgnoreNames=1, the namesof variables and constraints are replaced with default names whenwriting a file.

Parameters:

filename – The name of the file to be written. The file typeis encoded in the file name suffix. Valid suffixes are.mps,.rew,.lp, or.rlp for writing the model itself,.dua or.dlp for writing the dualized model (only pureLP),.ilp for writing just the IIS associated with aninfeasible model (seeModel.computeIIS for furtherinformation),.sol for writing the solution selected by theSolutionNumber parameter,.mst for writing astart vector,.hnt for writing a hint file,.bas forwriting an LP basis,.prm for writing modified parametersettings,.attr for writing model attributes, or.jsonfor writing solution information in JSON format. If your systemhas compression utilities installed (e.g.,7z orzip forWindows, andgzip,bzip2, orunzip for Linux ormacOS), then the files can be compressed, so additional suffixesof.zip,.gz,.bz2,.7z or.xz are accepted.

Example:
model.write("out.mst")model.write("out.sol")

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp