Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

GRBModel#

GRBModel#

Gurobi model object. Commonly used methods includeAddVar (adds a new decision variable tothe model),AddConstr (adds a newconstraint to the model),Optimize(optimizes the current model), andGet(retrieves the value of an attribute).

Objects of this class have unmanaged resources associated with them. Theclass implements theIDisposable interface.

While the .NET garbage collector will eventually collect an unusedGRBModel object, the vast majority of the memory associated with amodel is stored outside of the .NET heap. As a result, the garbagecollector can’t see this memory usage, and thus it can’t take thisquantity into account when deciding whether collection is necessary. Werecommend that you callGRBModel.Dispose when you aredone using a model (or use the .NETusing statement).

GRBModelGRBModel(GRBEnvenv)#

Constructor forGRBModel that creates an empty model. You can thencallAddVarandAddConstrto populate the model with variables and constraints.

Parameters:

env – Environment for new model.

Returns:

New model object. Model initially contains no variables orconstraints.

Example:
// Create environmentGRBEnvenv=newGRBEnv();// Create model and attach it to environmentGRBModelmodel=newGRBModel(env);
GRBModelGRBModel(GRBEnvenv,stringfilename)#

Constructor forGRBModel that reads a model from a file. Note thatthe type of the file is encoded in the file name suffix. Valid suffixes are.mps,.rew,.lp,.rlp,.dua,.dlp,.ilp, or.opb. The files can be compressed, so additionalsuffixes of.zip,.gz,.bz2,.7z or.xz are accepted.

Parameters:
  • env – Environment for new model.

  • modelname – Name of the file containing the model.

Returns:

New model object.

Example:
// Create environmentGRBEnvenv=newGRBEnv();// Create model from file myModel.mps and attach it to environmentGRBModelmodel=newGRBModel(env,"myModel.mps");
GRBModelGRBModel(GRBModelmodel)#

Constructor forGRBModel that creates a copy of an existing model. Notethat due to the lazy update approach in Gurobi, you have to callUpdate before copying it.

Parameters:

model – Model to copy.

Returns:

New model object. Model is a clone of the original.

Example:
// Create environmentGRBEnvenv=newGRBEnv();// Create model1 and attach it to environmentGRBModelmodel1=newGRBModel(env);// ...// Update model before copyingmodel1.Update();// Copy modelGRBModelmodel2=newGRBModel(model1);
GRBModelGRBModel(GRBModelmodel,GRBEnvtargetenv)#

Constructor forGRBModel.

Copy an existing model to a different environment. Multiple threads cannot work simultaneously within the same environment. Copies of modelsmust therefore reside in different environments for multiple threads tooperate on them simultaneously.

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 likethose to be included in 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:
  • model – Model to copy.

  • targetenv – Environment to copy model into.

Returns:

New model object. Model is a clone of the original.

Example:
// Create environmentGRBEnvenv=newGRBEnv();// Create model1 and attach it to environmentGRBModelmodel1=newGRBModel(env);// ...// Update model before copyingmodel1.Update();// Copy model and attach it to envGRBModelmodel2=newGRBModel(model1,env2);
GRBConstrAddConstr(GRBLinExprlhsExpr,charsense,GRBLinExprrhsExpr,stringname)#

Add a single linear constraint to a model.

Parameters:
  • lhsExpr – Left-hand side expression for new linear constraint.

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

  • rhsExpr – Right-hand side expression for new linear constraint.

  • name – Name for new constraint.

Returns:

New constraint object.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create linear expression x + yGRBLinExprlexpr=newGRBLinExpr(0);lexpr.AddTerm(1.0,x);lexpr.AddTerm(1.0,y);// Add linear constraint x + y = 0 with name c1GRBConstrconstr=model.AddConstr(lexpr,GRB.EQUAL,0.0,"c1");
GRBConstrAddConstr(GRBTempConstrtempConstr,stringname)#

Add a single linear constraint to a model.

Parameters:
  • tempConstr – Temporary constraint object, created by an overloadedcomparison operator. SeeGRBTempConstr for moreinformation.

  • name – Name for new constraint.

Returns:

New constraint object.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add linear constraint x + y = 0 with name c1GRBConstrconstr=model.AddConstr(x+y==0,"c1");
GRBConstr[]AddConstrs(intcount)#

Addcount new linear constraints to a model. The new constraints areall of the form0<=0.

We recommend that you build your model one constraint at a time (usingAddConstr), since it introduces nosignificant overhead and we find that it produces simpler code. Feelfree to use these methods if you disagree, though.

Parameters:

count – Number of constraints to add.

Returns:

Array of new constraint objects.

Example:
// Add 10 trivial linear constraints to modelGRBConstr[]constrs=model.AddConstrs(10);
GRBConstr[]AddConstrs(GRBLinExpr[]lhsExprs,char[]senses,double[]rhsVals,string[]names)#

Add new linear constraints to a model. The number of added constraintsis determined by the length of the input arrays (which must beconsistent across all arguments).

We recommend that you build your model one constraint at a time (usingAddConstr), since it introduces nosignificant overhead and we find that it produces simpler code. Feelfree to use these methods if you disagree, though.

Parameters:
  • lhsExprs – Left-hand side expressions for the new linearconstraints.

  • senses – Senses for new linear constraints (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhsVals – Right-hand side values for the new linear constraints.

  • names – Names for new constraints.

Returns:

Array of new constraint objects.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create linear expressions x + y and x - 2.0 * yGRBLinExprlexpr1=newGRBLinExpr(0);lexpr1.AddTerm(1.0,x);lexpr1.AddTerm(1.0,y);GRBLinExprlexpr2=newGRBLinExpr(0);lexpr2.AddTerm(1.0,x);lexpr2.AddTerm(-2.0,y);// Create arrays holding constraint dataGRBLinExpr[]lexprs={lexpr1,lexpr2};char[]senses={GRB.LESS_EQUAL,GRB.GREATER_EQUAL};double[]rhsVals={0.0,1.0};string[]names={"c1","c2"};// Add constraints x + y <= 0.0 and x - 2.0 * y >= 1.0GRBConstr[]constrs=model.AddConstrs(lexprs,senses,rhsVals,names);
GRBConstr[]AddConstrs(GRBLinExpr[]lhsExprs,char[]senses,GRBLinExpr[]rhsExprs,intstart,intlen,string[]names)#

Add new linear constraints to a model. This signature allows you to usearrays to hold the various constraint attributes (left-hand side, sense,etc.), without forcing you to add one constraint for each entry in thearray. Thestart andlen arguments allow you to specify whichconstraints to add.

We recommend that you build your model one constraint at a time (usingAddConstr), since it introduces nosignificant overhead and we find that it produces simpler code. Feelfree to use these methods if you disagree, though.

Parameters:
  • lhsExprs – Left-hand side expressions for the new linearconstraints.

  • senses – Senses for new linear constraints (GRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL).

  • rhs – Right-hand side expressions for the new linear constraints.

  • start – The first constraint in the list to add.

  • len – The number of constraints to add.

  • names – Names for new constraints.

Returns:

Array of new constraint objects.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create linear expressions x + y and x - 2.0 * yGRBLinExprlexpr1=newGRBLinExpr(0);lexpr1.AddTerm(1.0,x);lexpr1.AddTerm(1.0,y);GRBLinExprlexpr2=newGRBLinExpr(0);lexpr2.AddTerm(1.0,x);lexpr2.AddTerm(-2.0,y);// Create arrays holding constraint dataGRBLinExpr[]lexprs={lexpr1,lexpr2};char[]senses={GRB.LESS_EQUAL,GRB.GREATER_EQUAL};double[]rhsVals={0.0,1.0};string[]names={"c1","c2"};// Add constraints x + y <= 0.0 and x - 2.0 * y >= 1.0model.AddConstrs(lexprs,senses,rhsVals,0,2,names);
GRBGenConstrAddGenConstrMax(GRBVarresvar,GRBVar[]vars,doubleconstant,stringname)#

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\).

Parameters:
  • resvar – The resultant variable of the new constraint.

  • vars – Array of variables that are the operands of the newconstraint.

  • constant – The additional constant operand of the new constraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create variablesGRBVarresvar=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"resvar");double[]ub={10.0,10.0,10.0};GRBVar[]x=model.AddVars(null,ub,null,null,null);// Add constraint resvar = max{x[0], x[1], x[2], 2.0}GRBGenConstrgc=model.AddGenConstrMax(resvar,x,2.0,"maxconstr");
GRBGenConstrAddGenConstrMin(GRBVarresvar,GRBVar[]vars,doubleconstant,stringname)#

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\).

Parameters:
  • resvar – The resultant variable of the new constraint.

  • vars – Array of variables that are the operands of the newconstraint.

  • constant – The additional constant operand of the new constraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create variablesGRBVarresvar=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"resvar");double[]lb={-10.0,-10.0,-10.0};double[]ub={0.0,0.0,0.0};GRBVar[]x=model.AddVars(lb,ub,null,null,null);// Add constraint resvar = min{x[0], x[1], x[2], -2.0}GRBGenConstrgc=model.AddGenConstrMin(resvar,x,-2.0,"minconstr");
GRBGenConstrAddGenConstrAbs(GRBVarresvar,GRBVarargvar,stringname)#

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\).

Parameters:
  • resvar – The resultant variable of the new constraint.

  • argvar – The argument variable of the new constraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create variablesGRBVarresvar=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"resvar");GRBVarx=model.AddVar(-2.0,2.0,0.0,GRB.CONTINUOUS,"x");// Add constraint resvar = |x|GRBGenConstrgc=model.AddGenConstrAbs(resvar,x,"absconstr");
GRBGenConstrAddGenConstrAnd(GRBVarresvar,GRBVar[]vars,stringname)#

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.

Parameters:
  • resvar – The resultant variable of the new constraint.

  • vars – Array of variables that are the operands of the newconstraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create binary variablesGRBVarresvar=model.AddVar(0.0,1.0,0.0,GRB.BINARY,"resvar");GRBVar[]x=model.AddVars(3,GRB.BINARY);// Add constraint resvar = AND{x[0], x[1], x[2]}GRBGenConstrgc=model.AddGenConstrAnd(resvar,x,"andconstr");
GRBGenConstrAddGenConstrOr(GRBVarresvar,GRBVar[]vars,stringname)#

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.

Parameters:
  • resvar – The resultant variable of the new constraint.

  • vars – Array of variables that are the operands of the newconstraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create binary variablesGRBVarresvar=model.AddVar(0.0,1.0,0.0,GRB.BINARY,"resvar");GRBVar[]x=model.AddVars(3,GRB.BINARY);// Add constraint resvar = OR{x[0], x[1], x[2]}GRBGenConstrgc=model.AddGenConstrOr(resvar,x,"orconstr");
GRBGenConstrAddGenConstrNorm(GRBVarresvar,GRBVar[]vars,doublewhich,stringname)#

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 – The resultant variable of the new constraint.

  • vars – Array of variables that are the operands of the newconstraint. Note that this array may not contain duplicates.

  • which – Which norm to use. Options are 0, 1, 2, and GRB.INFINITY.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create variablesGRBVarresvar=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"resvar");double[]lb={-10.0,-10.0,-10.0};double[]ub={10.0,10.0,10.0};GRBVar[]x=model.AddVars(lb,ub,null,null,null);// Add constraint resvar = (x_0^2 + x_1^2 + x_2^2)^(0.5)GRBGenConstrgc=model.AddGenConstrNorm(resvar,x,2,"2normconstr");
GRBGenConstrAddGenConstrNL(GRBVarresvar,int[]opcode,double[]data,int[]parent,stringname)#

Add a newgeneral constraintof typeGRB.GENCONSTR_NL to a model.

A NL constraint\(r = f(x)\) states that the resultant variable\(r\)should be equal to the function value\(f(x)\) of the given function\(f\),provided as an expression tree described inNonlinear Constraints.

Parameters:
  • resvar – The resultant variable of the new constraint.

  • opcode – An array containing theoperation codes for the nodes.

  • data – An array containing the auxiliary data for each node.

  • parent – An array providing the parent index of the nodes

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Add nonlinear constraint x0 = sin(2.5 * x1) + x2 to the modelGRBVarx0=model.AddVar(0.0,1.0,0.0,GRB.CONTINUOUS,"x0");GRBVarx1=model.AddVar(0.0,1.0,0.0,GRB.CONTINUOUS,"x1");GRBVarx2=model.AddVar(0.0,1.0,0.0,GRB.CONTINUOUS,"x2");// Initialize data for expression treeint[]opcode=newint[]{GRB.OPCODE_PLUS,GRB.OPCODE_SIN,GRB.OPCODE_MULTIPLY,GRB.OPCODE_CONSTANT,GRB.OPCODE_VARIABLE,GRB.OPCODE_VARIABLE};double[]data=newdouble[]{-1.0,-1.0,-1.0,2.5,1.0,2.0};int[]parent=newint[]{-1,0,1,2,2,0};// Add nonlinear constraintmodel.AddGenConstrNL(x0,opcode,data,parent,"nlconstr");
GRBGenConstrAddGenConstrIndicator(GRBVarbinvar,intbinval,GRBLinExprexpr,charsense,doublerhs,stringname)#

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.

Parameters:
  • binvar – The binary indicator variable.

  • binval – The value for the binary indicator variable that wouldforce the linear constraint to be satisfied (\(0\) or\(1\)).

  • expr – Left-hand side expression for the linear constrainttriggered by the indicator.

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

  • rhs – Right-hand side value for the linear constraint.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create binary indicator variableGRBVarz=model.AddVar(0.0,1.0,0.0,GRB.BINARY,"z");// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create linear expression x + yGRBLinExprlexpr1=newGRBLinExpr(0);lexpr1.AddTerm(1.0,x);lexpr1.AddTerm(1.0,y);// Add constraint if z = 1 then x + y <= 2GRBGenConstrgc=model.AddGenConstrIndicator(z,1,lexpr,GRB.LESS_EQUAL,2.0,"indicatorconstr");
GRBGenConstrAddGenConstrIndicator(GRBVarbinvar,intbinval,GRBTempConstrconstr,stringname)#

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.

Parameters:
  • binvar – The binary indicator variable.

  • binval – The value for the binary indicator variable that wouldforce the linear constraint to be satisfied (\(0\) or\(1\)).

  • constr – Temporary constraint object defining the linear constraintthat is triggered by the indicator. The temporary constraint object iscreated using an overloaded comparison operator. SeeGRBTempConstr for more information.

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create binary indicator variableGRBVarz=model.AddVar(0.0,1.0,0.0,GRB.BINARY,"z");// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint if z = 1 then x + y <= 2GRBGenConstrgc=model.AddGenConstrIndicator(z,1,x+y<=2.0,"indicatorconstr");
GRBGenConstrAddGenConstrPWL(GRBVarxvar,GRBVaryvar,double[]xpts,double[]ypts,stringname)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

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

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

  • name – Name for the new general constraint.

Returns:

New general constraint.

Example:
// Create variablesGRBVarx=model.AddVar(-1.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create point pairs for the PWL functiondouble[]xpts={-1,0,0,0,1};double[]ypts={2,1,0,1,2};// Add PWL constraint y = PWL(x)GRBGenConstrgc=model.AddGenConstrPWL(x,y,xpts,ypts,"pwlconstr");
GRBGenConstrAddGenConstrPoly(GRBVarxvar,GRBVaryvar,double[]p,stringname,stringoptions)#

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

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

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

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create array holding coefficientsdouble[]p={3.0,2.0,0.0,1.0};// Add constraint y = 3.0 * x^3 + 2.0 * x^2 + 1.0GRBGenConstrgc=model.AddGenConstrPoly(x,y,p,"polyconstr","");
GRBGenConstrAddGenConstrExp(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = exp(x)GRBGenConstrgc=model.AddGenConstrExp(x,y,"expconstr","");
GRBGenConstrAddGenConstrExpA(GRBVarxvar,GRBVaryvar,doublea,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

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

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(1.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = 2.0^xGRBGenConstrgc=model.AddGenConstrExpA(x,y,2.0,"exp2constr","");
GRBGenConstrAddGenConstrLog(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(1.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = log(x)GRBGenConstrgc=model.AddGenConstrLog(x,y,"logconstr","");
GRBGenConstrAddGenConstrLogA(GRBVarxvar,GRBVaryvar,doublea,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

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

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(1.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = log_2(x)GRBGenConstrgc=model.AddGenConstrLogA(x,y,2.0,"log2constr","");
GRBGenConstrAddGenConstrLogistic(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = logistic(x) = 1.0 / (1.0 + exp(-x))GRBGenConstrgc=model.AddGenConstrLogistic(x,y,"logisticconstr","");
GRBGenConstrAddGenConstrPow(GRBVarxvar,GRBVaryvar,doublea,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • a – The exponent of the function.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = x^3GRBGenConstrgc=model.AddGenConstrPow(x,y,3,"pow3constr","");
GRBGenConstrAddGenConstrSin(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = sin(x)GRBGenConstrgc=model.AddGenConstrSin(x,y,"sinconstr","");
GRBGenConstrAddGenConstrCos(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-5.0,5.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = cos(x)GRBGenConstrgc=model.AddGenConstrCos(x,y,"cosconstr","");
GRBGenConstrAddGenConstrTan(GRBVarxvar,GRBVaryvar,stringname,stringoptions)#

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 – The\(x\) variable.

  • yvar – The\(y\) variable.

  • name – Name for the new general constraint.

  • options – 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:
// Create argument variableGRBVarx=model.AddVar(-1.0,1.0,0.0,GRB.CONTINUOUS,"x");// Create resultant variableGRBVary=model.AddVar(-GRB.INFINITY,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Add constraint y = tan(x)GRBGenConstrgc=model.AddGenConstrTan(x,y,"tanconstr","");
GRBQConstrAddQConstr(GRBQuadExprlhsExpr,charsense,GRBQuadExprrhsExpr,stringname)#

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:
  • lhsExpr – Left-hand side expression for new quadratic constraint.

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

  • rhsExpr – Right-hand side expression for new quadratic constraint.

  • name – Name for new constraint.

Returns:

New quadratic constraint object.

Example:
// Create variablesGRBVarx=model.AddVar(-2.0,2.0,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,3.0,0.0,GRB.CONTINUOUS,"y");// Create quadratric expression x^2 + x*y + yGRBQuadExprqexpr=newGRBQuadExpr(0);qexpr.AddTerm(1.0,x,x);qexpr.AddTerm(1.0,x,y);qexpr.AddTerm(1.0,y);// Add quadratic constraint x^2 + x*y + y = 0 with name c1GRBQConstrconstr=model.AddQConstr(qexpr,GRB.EQUAL,0.0,"c1");
GRBQConstrAddQConstr(GRBTempConstrtempConstr,stringname)#

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:
  • tempConstr – Temporary constraint object, created by an overloadedcomparison operator. SeeGRBTempConstr for moreinformation.

  • name – Name for new constraint.

Returns:

New quadratic constraint object.

Example:
// Create variablesGRBVarx=model.AddVar(-2.0,2.0,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,3.0,0.0,GRB.CONTINUOUS,"y");// Add quadratic constraint x^2 + x*y + y = 0 with name c1GRBQConstrconstr=model.AddQConstr(x*x+x*y+y==0,"c1");
GRBConstrAddRange(GRBLinExprexpr,doublelower,doubleupper,stringname)#

Add a single range constraint to a model. A range constraint states thatthe value of the input expression must be between the specifiedlower andupper 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.

  • lower – Lower bound for linear expression.

  • upper – Upper bound for linear expression.

  • name – Name for new constraint.

Returns:

New constraint object.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,10.0,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(-10.0,3.0,0.0,GRB.CONTINUOUS,"y");// Create linear expression x + yGRBLinExprlexpr=newGRBLinExpr(0);lexpr.AddTerm(1.0,x);lexpr.AddTerm(1.0,y);// Add range constraints -3 <= x + y <= 2 with name c1GRBConstrconstr=model.AddRange(lexpr,-3.0,2.0,"c1");
GRBConstr[]AddRanges(GRBLinExpr[]exprs,double[]lower,double[]upper,string[]names)#

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

Parameters:
  • exprs – Linear expressions for the new range constraints.

  • lower – Lower bounds for linear expressions.

  • upper – Upper bounds for linear expressions.

  • name – Names for new range constraints.

  • count – Number of range constraints to add.

Returns:

Array of new constraint objects.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create linear expressions x + y and x - 2.0 * yGRBLinExprlexpr1=newGRBLinExpr(0);lexpr1.AddTerm(1.0,x);lexpr1.AddTerm(1.0,y);GRBLinExprlexpr2=newGRBLinExpr(0);lexpr2.AddTerm(1.0,x);lexpr2.AddTerm(-2.0,y);double[]lower={-3.0,2.0};double[]upper={-1.0,5.0};string[]names={"c1","c2"};// Add constraints -3.0 <= x + y <= 2.0 and -1.0 <= x - 2.0 * y <= 5.0GRBConstr[]constrs=model.AddRanges(lexprs,lower,upper,names);
GRBSOSAddSOS(GRBVar[]vars,double[]weights,inttype)#

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

Parameters:
  • vars – Array of variables that participate in the SOS constraint.

  • weights – Weights for the variables in the SOS constraint.

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

Returns:

New SOS constraint.

Example:
// Create variablesGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");GRBVary=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"y");// Create helper arraysGRBVar[]vars={x,y};double[]weights={1.0,2.0};// Add SOS1 constraint over x and yGRBSOSconstr=model.AddSOS(vars,weights,GRB.SOS_TYPE1);
GRBVarAddVar(doublelb,doubleub,doubleobj,chartype,stringname)#

Add a single decision variable to a model; non-zero entries will be added later.

Parameters:
  • lb – Lower bound for new variable.

  • ub – Upper bound for new variable.

  • obj – Objective coefficient for new variable.

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

  • name – Name for new variable.

Returns:

New variable object.

Example:
// Create variableGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,"x");
GRBVarAddVar(doublelb,doubleub,doubleobj,chartype,GRBConstr[]constrs,double[]coeffs,stringname)#

Add a single decision variable and the associated non-zero coefficients to a model.

Parameters:
  • lb – Lower bound for new variable.

  • ub – Upper bound for new variable.

  • obj – Objective coefficient for new variable.

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

  • constrs – Array of constraints in which the variable participates.

  • coeffs – Array of coefficients for each constraint in which thevariable participates. The lengths of theconstrs andcoeffsarrays must be identical.

  • name – Name for new variable.

Returns:

New variable object.

Example:
// Add 3 trivial linear constraints to modelGRBConstr[]constrs=model.AddConstrs(3);// Constraint coefficients for variable xdouble[]coeffs={1.0,2.0,3.0};// Add variable x with coeffs 1.0, 2.0, 3.0 to the newly created trivial constraintsGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,constrs,coeffs,"x");
GRBVarAddVar(doublelb,doubleub,doubleobj,chartype,GRBColumncol,stringname)#

Add a variable to a model. This signature allows you to specify the setof constraints to which the new variable belongs using aGRBColumn object.

Parameters:
  • lb – Lower bound for new variable.

  • ub – Upper bound for new variable.

  • obj – Objective coefficient for new variable.

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

  • col – GRBColumn object for specifying a set of constraints to whichnew variable belongs.

  • name – Name for new variable.

Returns:

New variable object.

Example:
// Add 3 trivial linear constraints to modelGRBConstr[]constrs=model.AddConstrs(3);// Constraint coefficients for variable xdouble[]coeffs={1.0,2.0,3.0};// Create and fill GRBColumn objectGRBColumncol=newGRBColumn();col.AddTerms(coeffs,constrs);// Add variable x with coefs 1.0, 2.0, 3.0 to the newly created trivial constraintsGRBVarx=model.AddVar(0.0,GRB.INFINITY,0.0,GRB.CONTINUOUS,col,"x");
GRBVar[]AddVars(intcount,chartype)#

Addcount new decision variables to a model. All associatedattributes take their default values, except the variabletype,which is specified as an argument.

Parameters:
  • count – Number of variables to add.

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

Returns:

Array of new variable objects.

Example:
// Add 3 binary variablesGRBVar[]x=model.AddVars(3,GRB.BINARY);
GRBVar[]AddVars(double[]lb,double[]ub,double[]obj,char[]type,string[]names)#

Add new decision variables to a model. The number of added variables isdetermined by the length of the input arrays (which must be consistentacross all arguments).

Parameters:
  • lb – Lower bounds for new variables. Can benull, in which casethe variables get lower bounds of 0.0.

  • ub – Upper bounds for new variables. Can benull, in which casethe variables get infinite upper bounds.

  • obj – Objective coefficients for new variables. Can benull, inwhich case the variables get objective coefficients of 0.0.

  • type – Variable types for new variables (GRB.CONTINUOUS,GRB.BINARY,GRB.INTEGER,GRB.SEMICONT, orGRB.SEMIINT).Can benull, in which case the variables are assumed to becontinuous.

  • names – Names for new variables. Can benull, in which case allvariables are given default names.

Returns:

Array of new variable objects.

Example:
// Create 3 variables with default lower bound and default typedouble[]ub={1,1,2};double[]obj={-2,-1,-1};string[]names={"x0","x1","x2"};GRBVar[]x=model.AddVars(null,ub,obj,null,names);
GRBVar[]AddVars(double[]lb,double[]ub,double[]obj,char[]type,string[]names,intstart,intlen)#

Add new decision variables to a model. This signature allows you to usearrays to hold the various variable attributes (lower bound, upperbound, etc.), without forcing you to add a variable for each entry inthe array. Thestart andlen arguments allow you to specifywhich variables to add.

Parameters:
  • lb – Lower bounds for new variables. Can benull, in which casethe variables get lower bounds of 0.0.

  • ub – Upper bounds for new variables. Can benull, in which casethe variables get infinite upper bounds.

  • obj – Objective coefficients for new variables. Can benull, inwhich case the variables get objective coefficients of 0.0.

  • type – Variable types for new variables (GRB.CONTINUOUS,GRB.BINARY,GRB.INTEGER,GRB.SEMICONT, orGRB.SEMIINT).Can benull, in which case the variables are assumed to becontinuous.

  • names – Names for new variables. Can benull, in which case allvariables are given default names.

  • start – The first variable in the list to add.

  • len – The number of variables to add.

Returns:

Array of new variable objects.

Example:
// Create 2 variables with default lower bound and default typedouble[]ub={1,1,2};double[]obj={-2,-1,-1};string[]names={"x0","x1","x2"};GRBVar[]x=model.AddVars(null,ub,obj,null,names,0,2);
GRBVar[]AddVars(double[]lb,double[]ub,double[]obj,char[]type,string[]names,GRBColumn[]col)#

Add new decision variables to a model. This signature allows you tospecify the list of constraints to which each new variable belongs usingan array ofGRBColumn objects.

Parameters:
  • lb – Lower bounds for new variables. Can benull, in which casethe variables get lower bounds of 0.0.

  • ub – Upper bounds for new variables. Can benull, in which casethe variables get infinite upper bounds.

  • obj – Objective coefficients for new variables. Can benull, inwhich case the variables get objective coefficients of 0.0.

  • type – Variable types for new variables (GRB.CONTINUOUS,GRB.BINARY,GRB.INTEGER,GRB.SEMICONT, orGRB.SEMIINT).Can benull, in which case the variables are assumed to becontinuous.

  • names – Names for new variables. Can benull, in which case allvariables are given default names.

  • cols – GRBColumn objects for specifying a set of constraints towhich each new column belongs.

Returns:

Array of new variable objects.

Example:
// Create 3 variables with default lower bound and default typedouble[]ub={1,1,2};double[]obj={-2,-1,-1};string[]names={"x0","x1","x2"};// Create an array of previously created GRBColumn objectsGRBColumn[]col={col1,col2,col3};GRBVar[]x=model.AddVars(null,ub,obj,null,names,col);
voidChgCoeff(GRBConstrconstr,GRBVarvar,doublenewvalue)#

Change one coefficient in the model. The desired change is capturedusing aGRBVar object, aGRBConstrobject, and a desired coefficient for the specified variable in thespecified constraint. If you make multiple changes to the samecoefficient, 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 (usingGRBModel.Update), optimize the model (usingGRBModel.Optimize), or write the model to disk (usingGRBModel.Write).

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

  • var – Variable for coefficient to be changed.

  • newvalue – Desired new value for coefficient.

Example:
// Change coefficient of variable x in constraint c1 to 2.0model.ChgCoeff(c1,x,2.0);
voidChgCoeffs(GRBConstr[]constrs,GRBVar[]vars,double[]vals)#

Change a list of coefficients in the model. Each desired change iscaptured using aGRBVar object, aGRBConstr object, and adesired coefficient for the specified variable in the specifiedconstraint. The entries in the input arrays each correspond to a singledesired coefficient change. The lengths of the input arrays must all bethe same. If you make multiple changes to the same coefficient, the lastone will be applied.

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

Parameters:
  • constrs – Constraints for coefficients to be changed.

  • vars – Variables for coefficients to be changed.

  • vals – Desired new values for coefficients.

Example:
// Create arrays using previously created constraints and variablesGRBConstr[]constrs={c1,c2,c3};GRBVar[]vars={x,y,z};double[]vals={1.0,2.0,3.0};// Change coefficients of variables x, y, z in constraints c1, c2, and c3, respectivelymodel.ChgCoeffs(constrs,vars,vals);
voidComputeIIS()#

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 a.ilp formatfile (seeGRBModel.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.

Example:
// Compute IIS for infeasible modelif(model.Status==GRB.Status.INFEASIBLE){model.ComputeIIS();}
voidConvertToFixed()#

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.

Example:
model.ConvertToFixed();
voidDiscardConcurrentEnvs()#

Discard concurrent environments for a model.

The concurrent environments created byGetConcurrentEnv will be usedby every subsequent call to the concurrent optimizer until theconcurrent environments are discarded.

Example:
env0=model.GetConcurrentEnv(0);env1=model.GetConcurrentEnv(1);env0.Set(GRB.IntParam.Method,0);env1.Set(GRB.IntParam.Method,1);model.Optimize();model.DiscardConcurrentEnvs();
voidDiscardMultiobjEnvs()#

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 amulti-objective environment.

Example:
env0=model.GetMultiobjEnv(0);env1=model.GetMultiobjEnv(1);env0.Set(GRB.IntParam.Method,0);env1.Set(GRB.IntParam.Method,1);model.Optimize();model.DiscardMultiobjEnvs();
voidDispose()#

Release the resources associated with aGRBModel object. While the.NET garbage collector will eventually reclaim these resources, werecommend that you call theDispose method when you are done using amodel.

You should not attempt to use aGRBModel object after callingDispose on it.

Example:
GRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env);// ...model.Optimize();model.Dispose();env.Dispose();
doubleFeasRelax(intrelaxobjtype,booleanminrelax,GRBVar[]vars,double[]lbpen,double[]ubpen,GRBConstr[]constrs,double[]rhspen)#

Modifies theGRBModel object to create a feasibility relaxation.Note that you need to callOptimize on the result to computethe actual relaxed solution.

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.

There are two signatures for this method. The more complex one takes alist of variables and constraints, as well as penalties associated withrelaxing the corresponding lower bounds, upper bounds, and constraints.If a variable or constraint is not included in one of these lists, theassociated bounds or constraints may not be violated. The simplersignature takes a pair of boolean arguments,vrelax andcrelax,that indicate whether variable bounds and/or constraints can beviolated. Ifvrelax/crelax istrue, then everybound/constraint is allowed to be violated, respectively, and theassociated cost is 1.0.

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, use theGRBModelconstructor to create a copy beforeinvoking this method.

Create a feasibility relaxation model.

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:
// Compute feasibility relaxation for infeasible modelif(model.Status==GRB.Status.INFEASIBLE){GRBVar[]vars=model.GetVars();double[]ubpen=newdouble[model.NumVars];for(inti=0;i<model.NumVars;i++){ubpen[i]=1.0;}model.FeasRelax(0,false,vars,null,ubpen,null,null);model.Optimize();}
doubleFeasRelax(intrelaxobjtype,booleanminrelax,booleanvrelax,booleancrelax)#

Modifies theGRBModel object to create a feasibility relaxation.Note that you need to callOptimize on the result to computethe actual relaxed solution.

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.

There are two signatures for this method. The more complex one takes alist of variables and constraints, as well as penalties associated withrelaxing the corresponding lower bounds, upper bounds, and constraints.If a variable or constraint is not included in one of these lists, theassociated bounds or constraints may not be violated. The simplersignature takes a pair of boolean arguments,vrelax andcrelax,that indicate whether variable bounds and/or constraints can beviolated. Ifvrelax/crelax istrue, then everybound/constraint is allowed to be violated, respectively, and theassociated cost is 1.0.

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, use theGRBModelconstructor to create a copy beforeinvoking this method.

Simplified method for creating a feasibility relaxation model.

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 (with acost of 1.0 for any violations.

  • crelax – Indicates whether linear constraints can be relaxed (witha cost of 1.0 for any violations.

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:
// Compute feasibility relaxation for infeasible modelif(model.Status==GRB.Status.INFEASIBLE){model.FeasRelax(1,false,false,true);model.Optimize();}
GRBModelFixedModel()#

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:
GRBModelfixedModel=model.FixedModel();
doubleGet(GRB.DoubleParamparam)#
intGet(GRB.IntParamparam)#
stringGet(GRB.StringParamparam)#

Query the value of a double, integer, or string-valued parameter.

Parameters:

param – The parameter being queried.

Returns:

The current value of the requested parameter.

Example:
// Get value of TimeLimit parameterdoubleval=model.Get(GRB.DoubleParam.TimeLimit);// Get value of PumpPasses parameterintval=model.Get(GRB.IntParam.PumpPasses);// Get value of LogFile parameterstringval=model.Get(GRB.StringParam.LogFile);
doubleGet(GRB.DoubleAttrattr)#
intGet(GRB.IntAttrattr)#
stringGet(GRB.StringAttrattr)#

Query the value of a double, integer, or string-valued model attribute.

Parameters:

attr – The attribute being queried.

Returns:

The current value of the requested attribute.

Example:
// Get number of variables in the modelintnumvars=model.Get(GRB.IntAttr.NumVars);// Get ModelName attributestringmodelname=model.Get(GRB.StringAttr.ModelName);// Get runtime for the most recent optimization (in seconds)doubleruntime=model.Get(GRB.DoubleAttr.Runtime);
char[]Get(GRB.CharAttrattr,GRBVar[]objs)#
char[]Get(GRB.CharAttrattr,GRBConstr[]objs)#
char[]Get(GRB.CharAttrattr,GRBQConstr[]objs)#
double[]Get(GRB.DoubleAttrattr,GRBVar[]objs)#
double[]Get(GRB.DoubleAttrattr,GRBConstr[]objs)#
double[]Get(GRB.DoubleAttrattr,GRBQConstr[]objs)#
double[]Get(GRB.DoubleAttrattr,GRBGenConstr[]objs)#
int[]Get(GRB.IntAttrattr,GRBVar[]objs)#
int[]Get(GRB.IntAttrattr,GRBConstr[]objs)#
int[]Get(GRB.IntAttrattr,GRBQConstr[]objs)#
int[]Get(GRB.IntAttrattr,GRBGenConstr[]objs)#
string[]Get(GRB.StringAttrattr,GRBVar[]objs)#
string[]Get(GRB.StringAttrattr,GRBConstr[]objs)#
string[]Get(GRB.StringAttrattr,GRBQConstr[]objs)#
string[]Get(GRB.StringAttrattr,GRBGenConstr[]objs)#

Query an attribute for an array of modeling objects.

Parameters:
  • attr – The attribute being queried.

  • objs – The modeling objects, i.e., variables or constraints, whoseattribute values are being queried.

Returns:

The current values of the requested attribute for each inputobject.

Example:
// Get variable type attribute valuesGRBVar[]vars=model.GetVars();char[]vtype=model.Get(GRB.CharAttr.VType,vars);// Get RHS attribute values of all linear constraintsGRBConstr[]constrs=model.GetConstrs();double[]rhs=model.Get(GRB.DoubleAttr.RHS,constrs);// Get constraint name values of all linear constraintsstring[]constrNames=model.Get(GRB.StringAttr.ConstrName,qconstrs);
char[]Get(GRB.CharAttrattr,GRBVar[]objs,intstart,intlen)#
char[]Get(GRB.CharAttrattr,GRBConstr[]objs,intstart,intlen)#
char[]Get(GRB.CharAttrattr,GRBQConstr[]objs,intstart,intlen)#
double[]Get(GRB.DoubleAttrattr,GRBVar[]objs,intstart,intlen)#
double[]Get(GRB.DoubleAttrattr,GRBConstr[]objs,intstart,intlen)#
double[]Get(GRB.DoubleAttrattr,GRBQConstr[]objs,intstart,intlen)#
double[]Get(GRB.DoubleAttrattr,GRBGenConstr[]objs,intstart,intlen)#
int[]Get(GRB.IntAttrattr,GRBVar[]objs,intstart,intlen)#
int[]Get(GRB.IntAttrattr,GRBConstr[]objs,intstart,intlen)#
int[]Get(GRB.IntAttrattr,GRBQConstr[]objs,intstart,intlen)#
int[]Get(GRB.IntAttrattr,GRBGenConstr[]objs,intstart,intlen)#
string[]Get(GRB.StringAttrattr,GRBVar[]objs,intstart,intlen)#
string[]Get(GRB.StringAttrattr,GRBConstr[]objs,intstart,intlen)#
string[]Get(GRB.StringAttrattr,GRBQConstr[]objs,intstart,intlen)#
string[]Get(GRB.StringAttrattr,GRBGenConstr[]objs,intstart,intlen)#

Query an attribute for a sub-array of modeling objects.

Parameters:
  • attr – The attribute being queried.

  • objs – A one-dimensional array of modeling objects, i.e., variablesor constraints, whose attribute values are being queried.

  • start – The index of the first object of interest in the list.

  • len – The number of objects.

Returns:

The current values of the requested attribute for each inputobject.

Example:
// Get variable type attribute values for variables indexed from 0 to 2GRBVar[]vars=model.GetVars();char[]vtype=model.Get(GRB.CharAttr.VType,vars,0,3);// Get RHS attribute values for linear constraints indexed from 0 to 2GRBConstr[]constrs=model.GetConstrs();double[]rhs=model.Get(GRB.DoubleAttr.RHS,constrs,0,3);// Get constraint name values for linear constraints indexed from 0 to 2string[]constrNames=model.Get(GRB.StringAttr.ConstrName,constrs,0,3);
char[,]Get(GRB.CharAttrattr,GRBVar[,]objs)#
char[,]Get(GRB.CharAttrattr,GRBConstr[,]objs)#
char[,]Get(GRB.CharAttrattr,GRBQConstr[,]objs)#
double[,]Get(GRB.DoubleAttrattr,GRBVar[,]objs)#
double[,]Get(GRB.DoubleAttrattr,GRBConstr[,]objs)#
double[,]Get(GRB.DoubleAttrattr,GRBQConstr[,]objs)#
double[,]Get(GRB.DoubleAttrattr,GRBGenConstr[,]objs)#
int[,]Get(GRB.IntAttrattr,GRBVar[,]objs)#
int[,]Get(GRB.IntAttrattr,GRBConstr[,]objs)#
int[,]Get(GRB.IntAttrattr,GRBQConstr[,]objs)#
int[,]Get(GRB.IntAttrattr,GRBGenConstr[,]objs)#
string[,]Get(GRB.StringAttrattr,GRBVar[,]objs)#
string[,]Get(GRB.StringAttrattr,GRBConstr[,]objs)#
string[,]Get(GRB.StringAttrattr,GRBQConstr[,]objs)#
string[,]Get(GRB.StringAttrattr,GRBGenConstr[,]objs)#

Query an attribute for a two-dimensional array of modeling objects.

Parameters:
  • attr – The attribute being queried.

  • objs – A two-dimensional array of modeling objects, i.e., variablesor constraints, whose attribute values are being queried.

Returns:

The current values of the requested attribute for each inputobject.

Example:
// Get variable type attribute valuesGRBVar[,]vars=newGRBVar[10,10];char[,]vtype=model.Get(GRB.CharAttr.VType,vars);// Get RHS attribute values of linear constraintsGRBConstr[,]constrs=newGRBConstr[10,10];double[,]rhs=model.Get(GRB.DoubleAttr.RHS,constrs);// Get linear constraint namesstring[,]constrNames=model.Get(GRB.StringAttr.ConstrName,constrs);
char[,,]Get(GRB.CharAttrattr,GRBVar[,,]objs)#
char[,,]Get(GRB.CharAttrattr,GRBConstr[,,]objs)#
char[,,]Get(GRB.CharAttrattr,GRBQConstr[,,]objs)#
double[,,]Get(GRB.DoubleAttrattr,GRBVar[,,]objs)#
double[,,]Get(GRB.DoubleAttrattr,GRBConstr[,,]objs)#
double[,,]Get(GRB.DoubleAttrattr,GRBQConstr[,,]objs)#
double[,,]Get(GRB.DoubleAttrattr,GRBGenConstr[,,]objs)#
int[,,]Get(GRB.IntAttrattr,GRBVar[,,]objs)#
int[,,]Get(GRB.IntAttrattr,GRBConstr[,,]objs)#
int[,,]Get(GRB.IntAttrattr,GRBQConstr[,,]objs)#
int[,,]Get(GRB.IntAttrattr,GRBGenConstr[,,]objs)#
string[,,]Get(GRB.StringAttrattr,GRBVar[,,]objs)#
string[,,]Get(GRB.StringAttrattr,GRBConstr[,,]objs)#
string[,,]Get(GRB.StringAttrattr,GRBQConstr[,,]objs)#
string[,,]Get(GRB.StringAttrattr,GRBGenConstr[,,]objs)#

Query an attribute for a three-dimensional array of modeling objects.

Parameters:
  • attr – The attribute being queried.

  • objs – A three-dimensional array of modeling objects, i.e.,variables or constraints, whose attribute values are being queried.

Returns:

The current values of the requested attribute for each inputobject.

Example:
// Get variable type attribute valuesGRBVar[,,]vars=newGRBVar[10,10,10];char[,,]vtype=model.Get(GRB.CharAttr.VType,vars);// Get RHS attribute values of quadratic constraintsGRBQConstr[,,]constrs=newGRBQConstr[10,10,10];double[,,]qrhs=model.Get(GRB.DoubleAttr.QCRHS,constrs);// Get quadratic constraint namesstring[,,]sense=model.Get(GRB.StringAttr.QCName,constrs);
doubleGetCoeff(GRBConstrconstr,GRBVarvar)#

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:
// Get coefficient of variable x in constraint c1doublecoeff=model.GetCoeff(c1,x);
GRBColumnGetCol(GRBVarvar)#

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

Parameters:

var – The variable of interest.

Returns:

AGRBColumn object that captures the set ofconstraints in which the variable participates.

Example:
// Get column of coefficient and constraint pairs for variable xGRBColumncol=model.GetCol(x);
GRBEnvGetConcurrentEnv(intnum)#

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 torevert back to default concurrent optimizer behavior.

Parameters:

num – The concurrent environment number.

Returns:

The concurrent environment for the model.

Example:
env0=model.GetConcurrentEnv(0);env1=model.GetConcurrentEnv(1);env0.Set(GRB.IntParam.Method,0);env1.Set(GRB.IntParam.Method,1);model.Optimize();model.DiscardConcurrentEnvs();
GRBConstrGetConstrByName(stringname)#

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

Parameters:

name – The name of the desired linear constraint.

Returns:

The requested linear constraint.

Example:
// Retrieve linear constraint named "constr1"GRBConstrc1=model.GetConstrByName("constr1");

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.

GRBConstr[]GetConstrs()#

Retrieve an array of all linear constraints in the model.

Returns:

All linear constraints in the model.

Example:
// Retrieve all linear constraintsGRBConstr[]constrs=model.GetConstrs();
voidGetGenConstrMax(GRBGenConstrgenc,outGRBVarresvar,outGRBVar[]vars,outdoubleconstant)#

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 adescription of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • vars – Stores the array of operand variables of the constraint.

  • constant – Stores the additional constant operand of theconstraint.

Example:
GRBVarresvar;GRBVar[]vars;doubleconstant;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_MAX){// Retrieve data for given max constraintmodel.GetGenConstrMax(genc,outresvar,outvars,outconstant);}
voidGetGenConstrMin(GRBGenConstrgenc,outGRBVarresvar,outGRBVar[]vars,outdoubleconstant)#

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 adescription of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • vars – Stores the array of operand variables of the constraint.

  • constant – Stores the additional constant operand of theconstraint.

Example:
GRBVarresvar;GRBVar[]vars;doubleconstant;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_MIN){// Retrieve data for given min constraintmodel.GetGenConstrMin(genc,outresvar,outvars,outconstant);}
voidGetGenConstrAbs(GRBGenConstrgenc,outGRBVarresvar,outGRBVarargvar)#

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 adescription of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • argvar – Stores the argument variable of the constraint.

Example:
GRBVarresvar;GRBVarargvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_ABS){// Retrieve data for given abs constraintmodel.GetGenConstrAbs(genc,outresvar,outargvar);}
voidGetGenConstrAnd(GRBGenConstrgenc,outGRBVarresvar,outGRBVar[]vars)#

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 adescription of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • vars – Stores the array of operand variables of the constraint.

Example:
GRBVarresvar;GRBVar[]vars;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_AND){// Retrieve data for given AND constraintmodel.GetGenConstrAnd(genc,outresvar,outvars);}
voidGetGenConstrOr(GRBGenConstrgenc,outGRBVarresvar,outGRBVar[]vars)#

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 adescription of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • vars – Stores the array of operand variables of the constraint.

Example:
GRBVarresvar;GRBVar[]vars;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_OR){// Retrieve data for given OR constraintmodel.GetGenConstrOr(genc,outresvar,outvars);}
voidGetGenConstrNorm(GRBGenConstrgenc,outGRBVarresvar,outGRBVar[]vars,outdoublewhich)#

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 fora description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • vars – Stores the array of operand variables of the constraint.

  • which – Stores the norm type (possible values are 0, 1, 2, orGRB.INFINITY).

Example:
GRBVarresvar;GRBVar[]vars;doublewhich;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_NORM){// Retrieve data for given norm constraintmodel.GetGenConstrNorm(genc,outresvar,outvars,outwhich);}
voidGetGenConstrNL(GRBGenConstrgenc,outGRBVarresvar,outintnnodes,int[]opcode,double[]data,int[]parent)#

Retrieve the data associated with a general constraint of type NL.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.

Typical usage is to call this routine twice. In the first call, you specifythe requested general constraint, with anull value for theopcode,data andparent arguments. The routine returns the total number ofnodes that form the expression tree for the specified general constraint innnodes. That allows you to make certain that theopcode,data andparent arrays are of sufficient size to hold the result of the second call.

See alsoAddGenConstrNL fora description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • resvar – Stores the resultant variable of the constraint.

  • nnodes – Stores the number of nodes required to describe the nonlinear expression.

  • opcode – Stores the array containing theoperation codes for the nodes.

  • data – Stores the array containing auxiliary data for each node.

  • parent – Stores the array providing the parent index of each node.

Example:
GRBVarresvar;intnnodes;int[]opcode;double[]data;int[]parent;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_NL){// Get number of nodesmodel.GetGenConstrNL(genc,outresvar,outnnodes,null,null,null);// Initialize correct array sizesopcode=newint[nnodes];data=newdouble[nnodes];parent=newint[nnodes];// Get array datamodel.GetGenConstrNL(genc,outresvar,outnnodes,opcode,data,parent);}
voidGetGenConstrIndicator(GRBGenConstrgenc,outGRBVarbinvar,outintbinval,outGRBLinExprexpr,outcharsense,outdoublerhs)#

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 alsoAddGenConstrIndicatorfor a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

  • binvar – Stores the binary indicator variable of the constraint.

  • binval – Stores the value that the indicator variable has to takein order to trigger the linear constraint.

  • expr – Stores the left-hand side expression of the linearconstraint that is triggered by the indicator.

  • sense – Stores the sense for the linear constraint. Options areGRB.LESS_EQUAL,GRB.EQUAL, orGRB.GREATER_EQUAL.

  • rhs – Stores the right-hand side value for the linear constraint.

Example:
GRBVarbinvar;intbinval;GRBLinExprexpr;charsense;doublerhs;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_INDICATOR){// Retrieve data for given indicator constraintmodel.GetGenConstrIndicator(genc,outbinvar,outbinval,outexpr,outsense,outrhs);}
voidGetGenConstrPWL(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar,outintnpts,double[]xpts,double[]ypts)#

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.

Typical usage is to call this routine twice. In the first call, youspecify the requested general constraint, with anull value for thexpts andypts arguments. The routine returns the length for thexpts andypts arrays innpts. That allows you to makecertain that thexpts andypts arrays are of sufficient size tohold the result of the second call.

See alsoAddGenConstrPWL for adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

  • npts – Store the number of points that define the piecewise-linearfunction.

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

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

Example:
GRBVarxvar;GRBVaryvar;intnpts;double[]xpts;double[]ypts;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_PWL){// Get number of pointsmodel.GetGenConstrPWL(genc,outxvar,outyvar,outnpts,null,null);// Initialize correct array sizesxpts=newdouble[npts];ypts=newdouble[npts];// Retrieve data for given PWL constraintmodel.GetGenConstrPWL(genc,outxvar,outyvar,outnpts,xpts,ypts);}
voidGetGenConstrPoly(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar,outintplen,double[]p)#

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.

Typical usage is to call this routine twice. In the first call, youspecify the requested general constraint, with anull value for thep argument. The routine returns the length of thep array inplen. That allows you to make certain that thep array is ofsufficient size to hold the result of the second call.

See alsoAddGenConstrPoly fora description of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

  • plen – Store the array length for p. If\(x^d\) is the highestpower term, then\(d+1\) will be returned.

  • p – The coefficients for polynomial function.

Example:
GRBVarxvar;GRBVaryvar;intplen;double[]p;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_POLY){// Get number of coefficientsmodel.GetGenConstrPoly(genc,outxvar,outyvar,outplen,null);// Initialize correct array sizep=newdouble[plen];// Retrieve data for given poly constraintmodel.GetGenConstrPoly(genc,outxvar,outyvar,outplen,p);}
voidGetGenConstrExp(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_EXP){// Retrieve data for given exp constraintmodel.GetGenConstrExp(genc,outxvar,outyvar);}
voidGetGenConstrExpA(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar,outdoublea)#

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 fora description of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

  • a – Store the base of the function.

Example:
GRBVarxvar;GRBVaryvar;doublea;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_EXPA){// Retrieve data for given exp_a constraintmodel.GetGenConstrExpA(genc,outxvar,outyvar,outa);}
voidGetGenConstrLog(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_LOG){// Retrieve data for given log constraintmodel.GetGenConstrLog(genc,outxvar,outyvar);}
voidGetGenConstrLogA(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar,outdoublea)#

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 fora description of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

  • a – Store the base of the function.

Example:
GRBVarxvar;GRBVaryvar;doublea;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_LOGA){// Retrieve data for given log_a constraintmodel.GetGenConstrLogA(genc,outxvar,outyvar,outa);}
voidGetGenConstrLogistic(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 fora description of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_LOGISTIC){// Retrieve data for given logistic constraintmodel.GetGenConstrLogistic(genc,outxvar,outyvar);}
voidGetGenConstrPow(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar,outdoublea)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

  • a – Store the power of the function.

Example:
GRBVarxvar;GRBVaryvar;doublea;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_POW){// Retrieve data for given power constraintmodel.GetGenConstrPow(genc,outxvar,outyvar,outa);}
voidGetGenConstrSin(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_SIN){// Retrieve data for given sin constraintmodel.GetGenConstrSin(genc,outxvar,outyvar);}
voidGetGenConstrCos(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_COS){// Retrieve data for given cos constraintmodel.GetGenConstrCos(genc,outxvar,outyvar);}
voidGetGenConstrTan(GRBGenConstrgenc,outGRBVarxvar,outGRBVaryvar)#

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 adescription of the semantics of this general constraint type.

Any of the following arguments can benull.

Parameters:
  • genc – The general constraint object.

  • xvar – Store the\(x\) variable.

  • yvar – Store the\(y\) variable.

Example:
GRBVarxvar;GRBVaryvar;// Retrieve general constraint typeinttype=genc.Get(GRB.IntAttr.GenConstrType);if(type==GRB.GENCONSTR_TAN){// Retrieve data for given tan constraintmodel.GetGenConstrTan(genc,outxvar,outyvar);}
GRBGenConstr[]GetGenConstrs()#

Retrieve an array of all general constraints in the model.

Returns:

All general constraints in the model.

Example:
GRBGenConstr[]constrs=model.GetGenConstrs();
stringGetJSONSolution()#

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:
stringsolution=model.GetJSONSolution();
GRBEnvGetMultiobjEnv(intindex)#

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 todiscard multi-objective environments and return to standard behavior.

Parameters:

index – 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.Set(GRB.IntParam.Method,0);env1.Set(GRB.IntParam.Method,1);model.Optimize();model.DiscardMultiobjEnvs();
GRBExprGetObjective()#

Retrieve the optimization objective.

Note that the constant and linear portions of the objective can also beretrieved using theObjCon andObj attributes.

Returns:

The model objective.

Example:
// Get linear objective expressionGRBLinExprobj=model.GetObjective();doubleobjval=obj.Value;
GRBLinExprGetObjective(intindex)#

Retrieve an alternative optimization objective. Alternative objectiveswill always be linear. You can also use this routine to retrieve theprimary objective (usingindex = 0), but you will get an exceptionif the primary objective contains quadratic terms.

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

Note that alternative objectives can also be retrieved using theObjNCon andObjN attributes.

Parameters:

index – The index for the requested alternative objective.

Returns:

The requested alternative objective.

Example:
// Get second linear objectiveGRBLinExprobj=model.GetObjective(1);doubleobjval=obj.Value;
intGetPWLObj(GRBVarvar,double[]x,double[]y)#

Retrieve the piecewise-linear objective function for a variable. Thereturn value gives the number of points that define the function, andthe\(x\) and\(y\) arguments give the coordinates of thepoints, respectively. The\(x\) and\(y\) arguments must belarge enough to hold the result. Call this method withnull valuesfor\(x\) and\(y\) if you just want the number of points.

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

Parameters:
  • var – The variable whose objective function is being retrieved.

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

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

Returns:

The number of points that define the piecewise-linear objectivefunction.

Example:
// Get PWL objective dataintnpts=model.GetPWLObj(var,null,null);double[]x=newdouble[npts];double[]y=newdouble[npts];model.GetPWLObj(var,x,y);
GRBQConstr[]GetQConstrs()#

Retrieve an array of all quadratic constraints in the model.

Returns:

All quadratic constraints in the model.

Example:
GRBQConstr[]constrs=model.GetQConstrs();
GRBQuadExprGetQCRow(GRBQConstrqc)#

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

Parameters:

qc – The quadratic constraint of interest.

Returns:

AGRBQuadExpr object that captures the left-handside of the quadratic constraint.

Example:
// Get quadratic LHS expression of first quadratic constraintGRBQConstr[]constrs=model.GetQConstrs();GRBQuadExprqexpr=model.GetQCRow(constrs[0]);
GRBLinExprGetRow(GRBConstrconstr)#

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

Parameters:

constr – The constraint of interest. AGRBConstrobject, typically obtained fromAddConstr orGetConstrs.

Returns:

AGRBLinExpr object that captures the set ofvariables that participate in the constraint.

Example:
// Get linear LHS expression of first linear constraintGRBConstr[]constrs=model.GetConstrs();GRBLinExprlexpr=model.GetRow(constrs[0]);
intGetSOS(GRBSOSsos,GRBVar[]vars,double[]weights,int[]type)#

Retrieve the list of variables that participate in an SOS constraint,and the associated coefficients. The return value is the length of thislist. Note that the argument arrays must be long enough to accommodatethe result. Call the method withnull array arguments to determinethe appropriate array lengths.

Parameters:
  • sos – The SOS set of interest.

  • vars – A list of variables that participate insos. Can benull.

  • weights – The SOS weights for each participating variable. Can benull.

  • type – The type of the SOS set (eitherGRB.SOS_TYPE1 orGRB.SOS_TYPE2) is returned intype[0].

Returns:

The number of entries placed in the output arrays. Note that youshould consult the return value to determine the length of the result;the arrays sizes won’t necessarily match the result size.

Example:
GRBSOS[]constrs=model.GetSOSs();// Get data of first SOS constraintintlen=model.GetSOS(constrs[0],null,null,null);GRBVar[]vars=newGRBVar[len];double[]weights=newdouble[len];int[]type=newint[len];model.GetSOS(constrs[0],vars,weights,type);
GRBSOS[]GetSOSs()#

Retrieve an array of all SOS constraints in the model.

Returns:

All SOS constraints in the model.

Example:
GRBSOS[]constrs=model.GetSOSs();
voidGetTuneResult(intn)#

Use this method to retrieve the results of a previousTune call. Calling this method withargumentn causes tuned parameter setn to be copied into themodel. Parameter sets are stored in order of decreasing quality, withparameter set 0 being the best. The number of available sets is storedin attributeTuneResultCount.

Once you have retrieved a tuning result, you can calloptimize to use these parametersettings to optimize the model, orwriteto write the changed parameters to a.prm file.

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();// Get best tuning resultmodel.GetTuneResult(0);// Optimize model using the best found parameter setmodel.Optimize();
GRBVarGetVarByName(stringname)#

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

Parameters:

name – The name of the desired variable.

Returns:

The requested variable.

Example:
// Get variable named "var1"GRBVarvar=model.GetVarByName("var1");

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.

GRBVar[]GetVars()#

Retrieve an array of all variables in the model.

Returns:

All variables in the model.

Example:
GRBVar[]vars=model.GetVars();
voidOptimize()#

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.

Example:
model.Optimize();
voidOptimizeAsync()#

Optimize a model asynchronously. This method returns immediately. Yourprogram can perform other computations while optimization proceeds inthe background. To check the state of the asynchronous optimization,query theStatus attribute for the model. A value ofGRB.Status.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, and only for afew attributes (listed below). Any other calls on the running model,or on any other models that were built within the same Gurobienvironment, will raise an exception with error codeGRB.Error.OPTIMIZATION_IN_PROGRESS.

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,NLBarIterCount, andNLBarIterCount. In each case, the returned value reflectsprogress in the optimization to that point. Any attempt to query the valueof an attribute not on this list will raise an exception with error codeGRB.Error.OPTIMIZATION_IN_PROGRESS.

Example:
// Start asynchronous optimizationmodel.OptimizeAsync();// Poll the status while optimization is in progresswhile(model.Get(GRB.IntAttr.Status)==GRB.Status.INPROGRESS){Thread.Sleep(100);// Sleep for 100 msConsole.WriteLine($"ObjVal={model.Get(GRB.DoubleAttr.ObjVal)} ObjBound={model.Get(GRB.DoubleAttr.ObjBound)}");}// Synchronize modelmodel.Sync();// Query solution and process results// ...
stringOptimizeBatch()#

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 requeststringbatchID=model.OptimizeBatch();
Parameters#

(Attribute) Get or set parameter values.

Example:
// Print the current value of MIPFocus parameterConsole.WriteLine(model.Parameters.MIPFocus);// Set a 10 second time limitmodel.Parameters.TimeLimit=10;
GRBModelPresolve()#

Perform presolve on a model.

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

Returns:

Presolved version of original model.

Example:
GRBModelpresolved=model.Presolve();
voidRead(stringfilename)#

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 callingGRBModel.Update.

Note also that this isnot the method to use if you want to read anew model from a file. For that, use theGRBModelconstructor. One variant of theconstructor takes the name of the file that contains the new model asits argument.

Parameters:

filename – Name of the file to read. The suffix on the file must beeither.bas (for an LP basis),.mst or.sol (for a MIPstart),.hnt (for MIP hints),.ord (for a priority order),.attr (for a collection of attribute settings), or.prm (for a parameter file). The suffix may optionally be followedby.zip,.gz,.bz2,.7z or.xz.

Example:
model.Read("myModel.mps");
voidRemove(GRBConstrobj)#
voidRemove(GRBGenConstrobj)#
voidRemove(GRBQConstrobj)#
voidRemove(GRBSOSobj)#
voidRemove(GRBVarobj)#

Remove an object from the model. Note that, due to our lazy update approach,the change won’t actually take effect until you update the model (usingGRBModel.Update), optimize the model (usingGRBModel.Optimize), or write the model to disk (usingGRBModel.Write).

Parameters:

obj – The modeling object, i.e., variable or constraint, to remove.

Example:
GRBConstr[]constrs=model.GetConstrs();// Remove first linear constraintmodel.Remove(constrs[0]);GRBVar[]vars=model.GetVars();// Remove first variablemodel.Remove(vars[0]);
voidReset()#

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

Example:
model.Reset();
voidReset(intclearall)#

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

Parameters:

clearall – A value of 1 discards additional information thataffects the solution process but not the actual model (currently MIPstarts, variable hints, branching priorities, lazy flags, and partitioninformation). Pass 0 to just discard the solution.

Example:
model.Reset(1);
voidResetParams()#

Reset all parameters to their default values.

Example:
model.ResetParams();
voidSetCallback(GRBCallbackcb)#

Set the callback object for a model. TheCallback() method on thisobject will be called periodically from the Gurobi solver. You will havethe opportunity to obtain more detailed information about the state ofthe optimization from this callback. See the documentation forGRBCallback for additional information.

Note that a model can only have a single callback method, so this callwill replace an existing callback. To disable a previously set callback,call this method with anull argument.

Parameters:

cb – The callback object to be used for the given model. Can benullto disable a previously set callback.

Example:
classMyCallback:GRBCallback{// ...}// ...MyCallbackCB=newMyCallback();// ...model.SetCallback(CB);
voidSetCallback(GRBCallbackcb,uintwheres)#

Set the callback object for a model. TheCallback() method on thisobject will be called periodically from the Gurobi solver. You will havethe opportunity to obtain more detailed information about the state ofthe optimization from this callback. See the documentation forGRBCallback for additional information.

Note that a model can only have a single callback method, so this callwill replace an existing callback. To disable a previously set callback,call this method with anull argument.

Parameters:
  • cb – The callback object to be used for the given model. Can benullto disable a previously set callback.

  • wheres – A bit vector defining for whichwhere flags thecallback should be invoked. It should contain value 1 in the n-thposition if you want the callback to be invoked for thewhere flagof value n. See the possible values atCallback Codes, andthe example below. This argument is optional and has a default value(1<<10)-1, which sets all bits to 1.

Note

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

Example:
classMyCallback:GRBCallback{// ...}// ...MyCallbackCB=newMyCallback();// ...// Call callback only if the ``where`` flag equals POLLING or MESSAGEmodel.SetCallback(CB,(1<<GRB.Callback.POLLING)|(1<<GRB.Callback.MESSAGE));
voidSet(GRB.DoubleParamparam,doublenewvalue)#
voidSet(GRB.IntParamparam,intnewvalue)#
voidSet(GRB.StringParamparam,stringnewvalue)#

Set the value of a double, int or string-valued parameter.

The difference between setting a parameter on a model and setting it onan environment (i.e., throughGRBEnv.Set) is that theformer modifies the parameter for a single model, while the lattermodifies the parameter for every model that is subsequently built usingthat environment (and leaves the parameter unchanged for models thatwere previously built using that environment).

Parameters:
  • param – The parameter being modified.

  • newvalue – The desired new value for the parameter.

Example:
// Set parameter TimeLimit to value 10.0model.Set(GRB.DoubleParam.TimeLimit,10.0);// Set parameter PumpPasses to value 10model.Set(GRB.IntParam.PumpPasses,10);// Set parameter LogFile to value "myLog.log"model.Set(GRB.StringParam.LogFile,"myLog.log");
voidSet(GRB.DoubleAttrattr,doublenewvalue)#
voidSet(GRB.IntAttrattr,intnewvalue)#
voidSet(GRB.StringAttrattr,stringnewvalue)#

Set the value of a double-valued model attribute.

Parameters:
  • attr – The attribute being modified.

  • newvalue – The desired new value for the attribute.

Example:
// Adjust objective constantmodel.Set(GRB.DoubleAttr.ObjCon,2.0);// Adjust model sensemodel.Set(GRB.IntAttr.ModelSense,GRB.MINIMIZE);// Adjust model namemodel.Set(GRB.StringAttr.ModelName,"myModel");
voidSet(GRB.CharAttrattr,GRBVar[]objs,char[]newvalues)#
voidSet(GRB.CharAttrattr,GRBConstr[]objs,char[]newvalues)#
voidSet(GRB.CharAttrattr,GRBQConstr[]objs,char[]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBVar[]objs,double[]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBConstr[]objs,double[]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBQConstr[]objs,double[]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBGenConstr[]objs,double[]newvalues)#
voidSet(GRB.IntAttrattr,GRBVar[]objs,int[]newvalues)#
voidSet(GRB.IntAttrattr,GRBConstr[]objs,int[]newvalues)#
voidSet(GRB.IntAttrattr,GRBQConstr[]objs,int[]newvalues)#
voidSet(GRB.IntAttrattr,GRBGenConstr[]objs,int[]newvalues)#
voidSet(GRB.StringAttrattr,GRBVar[]objs,string[]newvalues)#
voidSet(GRB.StringAttrattr,GRBConstr[]objs,string[]newvalues)#
voidSet(GRB.StringAttrattr,GRBQConstr[]objs,string[]newvalues)#
voidSet(GRB.StringAttrattr,GRBGenConstr[]objs,string[]newvalues)#

Set an attribute for an array of modeling objects.

Parameters:
  • attr – The attribute being modified.

  • objs – The modeling objects, i.e., variables or constraints, whoseattribute values are being modified.

  • newvalues – The desired new values for the attribute for each inputobject.

Example:
// Add 3 binary variablesGRBVar[]x=model.AddVars(3,GRB.BINARY);// Change the type of the 3 variable to CONTINUOUSchar[]newvalues={"C","C","C"};model.Set(GRB.CharAttr.VType,x,newvalues);// Add 3 quadratic constraintsGRBQConstrc1=model.AddQConstr(x[0]*x[0]+y[1]*y[1]==0,"c1");GRBQConstrc2=model.AddQConstr(x[1]*y[1]-y[0]*y[2]==0,"c2");GRBQConstrc3=model.AddQConstr(x[2]*x[2]-x[0]*y[0]==0,"c3");GRBQConstr[]constrs={c1,c2,c3};// Change the RHS of the 3 constraintsdouble[]newvalues={1.0,2.0,3.0};model.Set(GRB.DoubleAttr.QCRHS,constrs,newvalues);
voidSet(GRB.CharAttrattr,GRBVar[]objs,char[]newvalues,intstart,intlen)#
voidSet(GRB.CharAttrattr,GRBConstr[]objs,char[]newvalues,intstart,intlen)#
voidSet(GRB.CharAttrattr,GRBQConstr[]objs,char[]newvalues,intstart,intlen)#
voidSet(GRB.DoubleAttrattr,GRBVar[]objs,double[]newvalues,intstart,intlen)#
voidSet(GRB.DoubleAttrattr,GRBConstr[]objs,double[]newvalues,intstart,intlen)#
voidSet(GRB.DoubleAttrattr,GRBQConstr[]objs,double[]newvalues,intstart,intlen)#
voidSet(GRB.DoubleAttrattr,GRBGenConstr[]objs,double[]newvalues,intstart,intlen)#
voidSet(GRB.IntAttrattr,GRBVar[]objs,int[]newvalues,intstart,intlen)#
voidSet(GRB.IntAttrattr,GRBConstr[]objs,int[]newvalues,intstart,intlen)#
voidSet(GRB.IntAttrattr,GRBQConstr[]objs,int[]newvalues,intstart,intlen)#
voidSet(GRB.IntAttrattr,GRBGenConstr[]objs,int[]newvalues,intstart,intlen)#
voidSet(GRB.StringAttrattr,GRBVar[]objs,string[]newvalues,intstart,intlen)#
voidSet(GRB.StringAttrattr,GRBConstr[]objs,string[]newvalues,intstart,intlen)#
voidSet(GRB.StringAttrattr,GRBQConstr[]objs,string[]newvalues,intstart,intlen)#
voidSet(GRB.StringAttrattr,GRBGenConstr[]objs,string[]newvalues,intstart,intlen)#

Set an attribute for a sub-array of modeling objects.

Parameters:
  • attr – The attribute being modified.

  • vars – A one-dimensional array of modeling objects, i.e., variablesor constraints, whose attribute values are being modified.

  • newvals – The desired new values for the attribute for each inputobject. This array must have the same length as theobjs array, evenif not all elements will be used.

  • start – The index of the first object of interest in the list.

  • len – The number of objects for which the attribute should bechanged, counting forward fromstart.

Deprecated since version 12.0.2:This method is deprecated, please use theSet(attr,vars,newvalues) function instead.

Example:
// Add 3 binary variablesGRBVar[]x=model.AddVars(3,GRB.BINARY);// Change the type of the first 2 variable to CONTINUOUS// Length of newvalues has to be the same as length of array xchar[]newvalues={"C","C"," "};model.Set(GRB.CharAttr.VType,x,newvalues,0,2);// Add 3 quadratic constraintsGRBQConstrc1=model.AddQConstr(x[0]*x[0]+y[1]*y[1]==0,"c1");GRBQConstrc2=model.AddQConstr(x[1]*y[1]-y[0]*y[2]==0,"c2");GRBQConstrc3=model.AddQConstr(x[2]*x[2]-x[0]*y[0]==0,"c3");GRBQConstr[]qconstrs={c1,c2,c3};// Change the RHS of the first 2 constraints// Length of newvalues has to be the same as length of array qconstrsdouble[]newvalues={1.0,2.0,0.0};model.Set(GRB.DoubleAttr.QCRHS,qconstrs,newvalues,0,2);
voidSet(GRB.CharAttrattr,GRBVar[,]objs,char[,]newvalues)#
voidSet(GRB.CharAttrattr,GRBConstr[,]objs,char[,]newvalues)#
voidSet(GRB.CharAttrattr,GRBQConstr[,]objs,char[,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBVar[,]objs,double[,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBConstr[,]objs,double[,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBQConstr[,]objs,double[,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBGenConstr[,]objs,double[,]newvalues)#
voidSet(GRB.IntAttrattr,GRBVar[,]objs,int[,]newvalues)#
voidSet(GRB.IntAttrattr,GRBConstr[,]objs,int[,]newvalues)#
voidSet(GRB.IntAttrattr,GRBQConstr[,]objs,int[,]newvalues)#
voidSet(GRB.IntAttrattr,GRBGenConstr[,]objs,int[,]newvalues)#
voidSet(GRB.StringAttrattr,GRBVar[,]objs,string[,]newvalues)#
voidSet(GRB.StringAttrattr,GRBConstr[,]objs,string[,]newvalues)#
voidSet(GRB.StringAttrattr,GRBQConstr[,]objs,string[,]newvalues)#
voidSet(GRB.StringAttrattr,GRBGenConstr[,]objs,string[,]newvalues)#

Set an attribute for a two-dimensional array of modeling objects.

Parameters:
  • attr – The attribute being modified.

  • objs – A two-dimensional array of modeling objects, i.e., variablesor constraints, whose attribute values are being modified.

  • newvalues – The desired new values for the attribute for each inputobject.

voidSet(GRB.CharAttrattr,GRBVar[,,]objs,char[,,]newvalues)#
voidSet(GRB.CharAttrattr,GRBConstr[,,]objs,char[,,]newvalues)#
voidSet(GRB.CharAttrattr,GRBQConstr[,,]objs,char[,,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBVar[,,]objs,double[,,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBConstr[,,]objs,double[,,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBQConstr[,,]objs,double[,,]newvalues)#
voidSet(GRB.DoubleAttrattr,GRBGenConstr[,,]objs,double[,,]newvalues)#
voidSet(GRB.IntAttrattr,GRBVar[,,]objs,int[,,]newvalues)#
voidSet(GRB.IntAttrattr,GRBConstr[,,]objs,int[,,]newvalues)#
voidSet(GRB.IntAttrattr,GRBQConstr[,,]objs,int[,,]newvalues)#
voidSet(GRB.IntAttrattr,GRBGenConstr[,,]objs,int[,,]newvalues)#
voidSet(GRB.StringAttrattr,GRBVar[,,]objs,string[,,]newvalues)#
voidSet(GRB.StringAttrattr,GRBConstr[,,]objs,string[,,]newvalues)#
voidSet(GRB.StringAttrattr,GRBQConstr[,,]objs,string[,,]newvalues)#
voidSet(GRB.StringAttrattr,GRBGenConstr[,,]objs,string[,,]newvalues)#

Set an attribute for a three-dimensional array of modeling objects

Parameters:
  • attr – The attribute being modified.

  • objs – A three-dimensional array of modeling objects, i.e.,variables or constraints, whose attribute values are being modified.

  • newvalues – The desired new values for the attribute for each inputobject.

voidSetObjective(GRBExprexpr,intsense)#

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

Note that you can also modify the linear portion of a model objectiveusing theObj variable attribute. If you wish to mix andmatch these two approaches, please note that this method replaces theentire existing objective, while theObj attribute can be used tomodify individual linear terms.

Parameters:
  • expr – New model objective.

  • sense – New optimization sense (GRB.MINIMIZE for minimization,GRB.MAXIMIZE for maximization).

Example:
model.SetObjective(x+y,GRB.MINIMIZE);
voidSetObjective(GRBExprexpr)#

Set the model objective equal to a quadratic expression (formulti-objective optimization, seeSetObjectiveN). The sense of the objective is determined bythe value of theModelSense attribute.

Note that this method replaces the entire existing objective, while theObj attribute can be used to modify individual linear terms.

Parameters:

expr – New model objective.

Example:
model.SetObjective(x+y);
voidSetObjectiveN(GRBLinExprexpr,intindex,intpriority,doubleweight,doubleabstol,doublereltol,stringname)#

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 – New alternative objective.

  • index – Index for new objective. If you use an index of 0, thisroutine will change the primary optimization objective.

  • priority – Priority for the alternative objective. Thisinitializes theObjNPriority attribute for this objective.

  • weight – Weight for the alternative objective. This initializestheObjNWeight attribute for this objective.

  • abstol – Absolute tolerance for the alternative objective. Thisinitializes theObjNAbsTol attribute for this objective.

  • reltol – Relative tolerance for the alternative objective. Thisinitializes theObjNRelTol attribute for this objective.

  • name – Name of the alternative objective. This initializes theObjNName attribute for this objective.

Example:
// Primary objective: x + 2 ymodel.SetObjectiveN(x+2*y,0,2,1.0,2.0,0.1,"Primary Obj");// Secondary objective: 3 y + zmodel.SetObjectiveN(3*y+z,1,1,1.0,0.0,0.0,"Secondary Obj");
voidSetPWLObj(GRBVarvar,double[]x,double[]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 – The variable whose objective 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:
GRBVarvar=model.AddVar(0.0,1.0,0.0,GRB.CONTINUOUS,"var");double[]x={0.0,0.5,1.0};double[]y={0.5,0.25,0.75};model.SetPWLObj(var,x,y);
GRBModelSingleScenarioModel()#

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.Set(GRB.IntAttr.NumScenarios,1);model.Update();GRBModelsinglescenario=model.SingleScenarioModel();
voidSync()#

Wait for a previous asynchronous optimization call to complete.

CallingOptimizeAsync returnscontrol to the calling routine immediately. The caller can perform othercomputations while optimization proceeds, and can check on the progressof the optimization by querying various model attributes. Thesynccall forces the calling program to wait until the asynchronousoptimization call completes. Youmust callsync before thecorresponding model object is deleted.

Thesync call throws an exception if the optimization itself raninto any problems. In other words, exceptions thrown by this method arethose thatoptimize itself would have thrown, had the originalmethod not been asynchronous.

Note that you need to callsync even if you know that theasynchronous optimization has already completed.

Example:
model.OptimizeAsync();// ...model.Sync();
voidTerminate()#

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();
voidTune()#

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.

Example:
model.Tune();// Get best tuning resultmodel.GetTuneResult(0);// Optimize model using the best found parameter setmodel.Optimize();
voidUpdate()#

Process any pending model modifications.

Example:
model.Update();
voidWrite(stringfilename)#

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 (seeGRBModel.ComputeIIS forfurther information),.sol for writing the solution selectedby theSolutionNumber parameter,.mst forwriting a start vector,.hnt for writing a hint file,.bas for writing an LP basis,.prm for writing modifiedparameter settings,.attr for writing model attributes, or.json for writing solution information in JSON format. Ifyour system has compression utilities installed (e.g.,7z orzip for Windows, andgzip,bzip2, orunzip forLinux or macOS), then the files can be compressed, so additionalsuffixes of.zip,.gz,.bz2,.7z or.xz are accepted.

Example:
model.Write("myModel.lp");

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp