gurobipy.Model#

class Model#

Gurobi model object. Commonly used methods on the model object in the Gurobi shell include optimize (optimizes the model), printStats (prints statistics about the model), printAttr (prints the values of an attribute), and write (writes information about the model to a file). Commonly used methods when building a model include addVar (adds a new variable), addVars (adds multiple new variables), addMVar (adds an a NumPy ndarray of Gurobi variables), addConstr (adds a new constraint), and addConstrs (adds multiple new constraints).

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

Model constructor.

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

  • env – Environment in which to create the model. Creating your own environment (using the Env constructor) gives you more control (for example, to solve your model on a specific Compute Server). It can make your program more verbose, though, so we suggest that you use the default environment unless you know that you need to control your own environments.

Returns:

New model object. Model initially contains no variables or constraints.

Example:
m = gp.Model("NewModel")
x0 = m.addVar()

env = gp.Env("my.log")
m2 = gp.Model("NewModel2", env)
addConstr(constr, name='')#

Add a constraint to a model.

This method accepts a TempConstr as its first argument, and the constraint name as its optional second argument. You use operator overloading to create the argument (see this section for details). This one method allows you to add linear constraints, matrix constraints, quadratic constraints, and general constraints.

Parameters:
  • constrTempConstr argument.

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

Returns:

New constraint object. This can be a Constr, an MConstr, a QConstr, or an MQConstr, depending on the type of the argument.

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

Warning

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

addConstrs(generator, name='')#

Add multiple constraints to a model using a Python generator expression. Returns a Gurobi tupledict that contains the newly created constraints, indexed by the values generated by the generator expression.

The first argument to addConstrs is a Python generator expression, a special feature of the Python language that allows you to iterate over a Python expression. In this case, the Python expression will be a Gurobi constraint and the generator expression provides values to plug into that constraint. A new Gurobi constraint is added to the model for each iteration of the generator expression.

To give an example, if x is a Gurobi variable, then

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

would add a single linear constraint involving this variable. In contrast, if x is a list of Gurobi variables, then

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

would add four constraints to the model. The entire first argument is a generator expression, where the indexing is controlled by the statement for i in range(4), The first constraint that results from this expression would be named c[0], and would involve variable x[0]. The second would be named c[1], and would involve variable x[1].

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

m.addConstrs((x[i,j] == 0 for i in range(4)
                          for j in range(4)
                          if i != j), name='c')

One restriction that addConstrs places on the generator expression is that each variable must always take a scalar value (int, float, string, …). Thus, for i in [1, 2.0, 'a', 'bc'] is fine, but for i in [(1, 2), [1, 2, 3]] isn’t.

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

Note that if you supply a name argument, the generator expression must be enclosed in parenthesis. This requirement comes from the Python language interpreter.

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

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

Returns:

A dictionary of Constr objects, indexed by the values specified by the generator expression.

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

Warning

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

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

Add a new general constraint of type GRB.GENCONSTR_MAX to a model.

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

You can also add a MAX constraint using the max_ function.

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

  • vars – (list of Var, or tupledict of Var values) The variables over which the MAX will be taken.

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

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

Example:
# x5 = max(x1, x3, x4, 2.0)
model.addGenConstrMax(x5, [x1, x3, x4], 2.0, "maxconstr")

# overloaded forms
model.addConstr(x5 == max_([x1, x3, x4], constant=2.0), name="maxconstr")
model.addConstr(x5 == max_(x1, x3, x4, constant=2.0), name="maxconstr")
addGenConstrMin(resvar, vars, constant=None, name='')#

Add a new general constraint of type GRB.GENCONSTR_MIN to a model.

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

You can also add a MIN constraint using the min_ function.

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

  • vars – (list of Var, or tupledict of Var values) The variables over which the MIN will be taken.

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

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

Example:
# x5 = min(x1, x3, x4, 2.0)
model.addGenConstrMin(x5, [x1, x3, x4], 2.0, "minconstr")

# overloaded forms
model.addConstr(x5 == min_([x1, x3, x4], constant=2.0), name="minconstr")
model.addConstr(x5 == min_(x1, x3, x4, constant=2.0), name="minconstr")
addGenConstrAbs(resvar, argvar, name='')#

Add a new general constraint of type GRB.GENCONSTR_ABS to a model.

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

You can also add an ABS constraint using the abs_ function.

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

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

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

Example:
# x5 = abs(x1)
model.addGenConstrAbs(x5, x1, "absconstr")

# overloaded form
model.addConstr(x5 == abs_(x1), name="absconstr")
addGenConstrAnd(resvar, vars, name='')#

Add a new general constraint of type GRB.GENCONSTR_AND to a model.

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

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

You can also add an AND constraint using the and_ function.

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

  • vars – (list of Var) The variables over which the AND concatenation will be taken.

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

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

# overloaded forms
model.addConstr(x5 == and_([x1, x3, x4]), "andconstr")
model.addConstr(x5 == and_(x1, x3, x4), "andconstr")
addGenConstrOr(resvar, vars, name='')#

Add a new general constraint of type GRB.GENCONSTR_OR to a model.

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

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

You can also add an OR constraint using the or_ function.

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

  • vars – (list of Var) The variables over which the OR concatenation will be taken.

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

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

# overloaded forms
model.addConstr(x5 == or_([x1, x3, x4]), "orconstr")
model.addConstr(x5 == or_(x1, x3, x4), "orconstr")
addGenConstrNorm(resvar, vars, which, name='')#

Add a new general constraint of type GRB.GENCONSTR_NORM to a model.

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

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

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

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

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

Example:
# x5 = 2-norm(x1, x3, x4)
model.addGenConstrNorm(x5, [x1, x3, x4], 2.0, "normconstr")
addGenConstrIndicator(binvar, binval, lhs, sense=None, rhs=None, name='')#

Add a new general constraint of type GRB.GENCONSTR_INDICATOR to a model.

An INDICATOR constraint \(z = f \rightarrow a^Tx \leq b\) states that 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 linear constraint can also be specified to be \(=\) or \(\geq\).

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

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

Multiple INDICATOR constraints can be added in a single addGenConstrIndicator call by using matrix-friendly modeling objects. In this case, an MGenConstr object will be returned. The input arguments follow NumPy’s broadcasting rules, with some restrictions:

  • binvar cannot be broadcasted over binval, and

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

This means that via broadcasting, you can use a single indicator variable to control whether multiple linear constraints should hold. We refer you to the NumPy documentation for further information regarding broadcasting behaviour.

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

  • binval – (Boolean or ndarray) The value for the binary indicator variable that would force the linear constraint to be satisfied. Can be provided as an ndarray of distinct values if binvar is an MVar.

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

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

  • rhs – (float or ndarray) Right-hand side value for the linear constraint. Can be provided as an ndarray of distinct values if lhs is an MVar or an MLinExpr.

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

Returns:

New general constraint object. This can be a GenConstr or an MGenConstr depending on the types of the input arguments.

Example:
# x7 = 1 -> x1 + 2 x3 + x4 = 1
model.addGenConstrIndicator(x7, True, x1 + 2*x3 + x4, GRB.EQUAL, 1.0)

# alternative form
model.addGenConstrIndicator(x7, True, x1 + 2*x3 + x4 == 1.0)

# overloaded form
model.addConstr((x7 == 1) >> (x1 + 2*x3 + x4 == 1.0))

# Matrix-friendly form where Z is an MVar. Creates multiple
# indicator constraints, each specifying
#   z_i = 1 -> sum a_ij x_j = b_i.
model.addGenConstrIndicator(z, 1.0, A @ x == b)

# Matrix-friendly form where z is an Var. Creates multiple
# indicator constraints, each specifying
#   z = 1 -> sum a_ij x_j = b_i
# (the indicator variable is broadcasted).
model.addGenConstrIndicator(z, 1.0, A @ x == b)
addGenConstrPWL(xvar, yvar, xpts, ypts, name='')#

Add a new general constraint of type GRB.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 of piecewise-linear objectives for details of how piecewise-linear functions are defined.

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

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.GENCONSTR_POLY to a model.

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

A piecewise-linear approximation of the function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.GENCONSTR_LOGISTIC to a model.

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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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\) is the (constant) exponent.

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

A piecewise-linear approximation of the function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

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

Add a new general constraint of type GRB.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 function is added to the model. The details of the approximation are controlled using the following four attributes (or using the parameters with the same names): FuncPieces, FuncPieceError, FuncPieceLength, and FuncPieceRatio. Alternatively, the function can be treated as a nonlinear constraint by setting the attribute FuncNonlinear. For details, consult the General Constraint discussion.

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

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

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

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

Returns:

New general constraint.

Example:
# y = tan(x)
gc = model.addGenConstrTan(x, y)
addLConstr(lhs, sense=None, rhs=None, name='')#

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

Note that this method also accepts a TempConstr as its first argument (with the name as its second argument). This allows you to use operator overloading to create constraints. See TempConstr for more information.

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

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

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

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

Returns:

New constraint object.

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

Add a set of linear constraints to the model using matrix semantics. The added constraints are \(A x = b\) (except that the constraint sense is determined by the sense argument). The A argument must be a NumPy dense ndarray or a SciPy sparse matrix.

Note that you will typically use overloaded operators to build and add constraints using matrix semantics. The overloaded @ operator can be used to build a linear matrix expression, which can then be used with an overloaded comparison operator to build a TempConstr object. This can then be passed to addConstr.

Parameters:
  • A – The constraint matrix - a NumPy 2-D dense ndarray or a SciPy sparse matrix.

  • x – Decision variables. Argument can be an MVar object, a list of Var objects, or None (None uses all variables in the model). The length of the argument must match the size of the second dimension of A.

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

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

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

Returns:

MConstr object.

Example:
A = np.full((5, 10), 1)
x = model.addMVar(10)
b = np.full(5, 1)

model.addMConstr(A, x, '=', b)
addMQConstr(Q, c, sense, rhs, xQ_L=None, xQ_R=None, xc=None, name='')#

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

Note that you will typically use overloaded operators to build and add constraints using matrix semantics. The overloaded @ operator can be used to build a linear matrix expression or quadratic matrix expression. An overloaded comparison operator can then be used to build a TempConstr object, which is then passed to addConstr.

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

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

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

  • rhs – Right-hand-side value.

  • xQ_L – Decision variables for quadratic terms; left multiplier for Q. Argument can be an MVar object, a list of Var objects, or None (None uses all variables in the model). The length of the argument must match the size of the first dimension of Q.

  • xQ_R – Decision variables for quadratic terms; right multiplier for Q. The length of the argument must match the size of the second dimension of Q.

  • xc – Decision variables for linear terms. Argument can be an MVar object, a list of Var objects, or None (None uses all variables in the model). The length of the argument must match the length of c.

  • name – Name for new constraint.

Returns:

The QConstr object.

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

Add an MVar object to a model. An MVar acts like a NumPy ndarray of Gurobi decision variables. An MVar can have an arbitrary number of dimensions, defined by the shape argument.

You can use arithmetic operations with MVar objects to create linear matrix expressions or quadratic matrix expressions, which can then be used to build linear or quadratic objectives or constraints.

The returned MVar object supports standard NumPy indexing and slicing. An MVar of size \(1\) can be passed in all places where gurobipy accepts a Var object.

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

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

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

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

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

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

The values of the lb, ub, obj, and vtype arguments can either be scalars, lists, or ndarrays. Their shapes should match the shape of the new MVar object, or they should be broadcastable to the given shape.

The name argument can either be a single string, used as a common base name that will be suffixed for each variable by its indices, or an ndarray of strings matching the shape of the new MVar object.

Returns:

New MVar object.

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

Add a quadratic constraint to a model.

Important

Gurobi can handle both convex and non-convex quadratic constraints. The differences between them can be both important and subtle. Refer to this discussion for additional information.

Parameters:
  • lhs – Left-hand side for new quadratic constraint. Can be a constant, a Var, a LinExpr, or a QuadExpr.

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

  • rhs – Right-hand side for new quadratic constraint. Can be a constant, a Var, a LinExpr, or a QuadExpr.

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

Returns:

New quadratic constraint object.

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

Add a range constraint to a model. A range constraint states that the value of the input expression must be between the specified lower and upper bounds in any solution.

Note that range constraints are stored internally as equality constraints. We add an extra variable to the model to capture the range information. Thus, the Sense attribute on a range constraint will always be GRB.EQUAL. In particular introducing a range constraint

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

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

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

  • lower – Lower bound for linear expression.

  • upper – Upper bound for linear expression.

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

Returns:

New constraint object.

Example:
# 1 <= x + y <= 2
model.addRange(x + y, 1.0, 2.0, "range0")

# overloaded forms
model.addConstr(x + y == [1.0, 2.0], name="range0")
addSOS(type, vars, wts=None)#

Add an SOS constraint to the model. Please refer to this section for details on SOS constraints.

Parameters:
  • type – SOS type (can be GRB.SOS_TYPE1 or GRB.SOS_TYPE2).

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

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

Returns:

New SOS object.

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

Add a decision variable to a model.

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

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

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

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

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

  • column – (optional) Column object that indicates the set of constraints in which the new variable participates, and the associated coefficients.

Returns:

New variable object.

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

Add multiple decision variables to a model.

Returns a Gurobi tupledict object that contains the newly created variables. The keys for the tupledict are derived from the indices argument(s). The arguments for this method can take several different forms, which will be described now.

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

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

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

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

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

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

Finally, if your indices argument is a single list, you can provide a Python list of the same length for the named arguments. For each variable, it will pull the value from the corresponding position in the list.

As noted earlier, the name argument is special. If you provide a scalar argument for the name, that argument will be transformed to have a subscript that corresponds to the index of the associated variable. For example, if you do x = model.addVars(2,3,name="x"), the variables will get names x[0,0], x[0,1], etc.

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

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

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

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

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

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

Returns:

New tupledict object that contains the new variables as values, using the provided indices as keys.

Example:
# 3-D array of binary variables
x = model.addVars(3, 4, 5, vtype=GRB.BINARY)

# variables index by tuplelist
l = tuplelist([(1, 2), (1, 3), (2, 3)])
y = model.addVars(l, ub=[1, 2, 3])

# variables with predetermined names
z = model.addVars(3, name=["a","b","c"])
cbCut(lhs, sense, rhs)#

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

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

Cutting planes are typically used to cut off the current relaxation solution. To retrieve the relaxation solution at the current node, you should first call cbGetNodeRel.

You should consider setting parameter PreCrush to value 1 when adding your own cuts. This setting shuts off a few presolve reductions that can sometimes prevent your cut from being applied to the presolved model (which would result in your cut being silently ignored).

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

Note that this method also accepts a TempConstr as its first argument. This allows you to use operator overloading to create constraints. See TempConstr for more information.

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

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

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

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPNODE:
    status = model.cbGet(GRB.Callback.MIPNODE_STATUS)
    if status == GRB.OPTIMAL:
      rel = model.cbGetNodeRel([model._vars[0], model._vars[1]])
      if rel[0] + rel[1] > 1.1:
        model.cbCut(model._vars[0] + model._vars[1] <= 1)

model._vars = model.getVars()
model.optimize(mycallback)
cbGet(what)#

Query the optimizer from within the user callback.

Parameters:

what – Integer code that indicates what type of information is being requested by the callback. The set of valid codes depends on the where value that is passed into the user callback function. Please refer to the Callback Codes section for a list of possible where and what values.

Example:
def mycallback(model, where):
  if where == GRB.Callback.SIMPLEX:
    print(model.cbGet(GRB.Callback.SPX_OBJVAL))

model.optimize(mycallback)
cbGetNodeRel(vars)#

Retrieve values from the node relaxation solution at the current node. Note that this method can only be invoked when the where value on the callback function is equal to GRB.Callback.MIPNODE, and GRB.Callback.MIPNODE_STATUS is equal to GRB.OPTIMAL (see the Callback Codes section for more information).

Parameters:

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

Returns:

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

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPNODE:
    status = model.cbGet(GRB.Callback.MIPNODE_STATUS)
    if status == GRB.OPTIMAL:
      print(model.cbGetNodeRel(model._vars))

model._vars = model.getVars()
model.optimize(mycallback)
cbGetSolution(vars)#

Retrieve values from the new MIP solution. Note that this method can only be invoked when the where value on the callback function is equal to GRB.Callback.MIPSOL or GRB.Callback.MULTIOBJ (see the Callback Codes section for more information).

Parameters:

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

Returns:

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

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPSOL:
    print(model.cbGetSolution(model._vars))

model._vars = model.getVars()
model.optimize(mycallback)
cbLazy(lhs, sense, rhs)#

Add a new lazy constraint to a MIP model from within a callback function. Note that this method can only be invoked when the where value on the callback function is GRB.Callback.MIPNODE or GRB.Callback.MIPSOL (see the Callback Codes section for more information).

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

You would typically add a lazy constraint by first querying the current node solution (by calling cbGetSolution from a GRB.Callback.MIPSOL callback, or cbGetNodeRel from a GRB.Callback.MIPNODE callback), and then calling cbLazy() to add a constraint that cuts off the solution. Gurobi guarantees that you will have the opportunity to cut off any solutions that would otherwise be considered feasible.

MIP solutions may be generated outside of a MIP node. Thus, generating lazy constraints is optional when the where value in the callback function equals GRB.Callback.MIPNODE. To avoid this, we recommend to always check when the where value equals GRB.Callback.MIPSOL.

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

Note that you must set the LazyConstraints parameter if you want to use lazy constraints.

Note that this method also accepts a TempConstr as its first argument. This allows you to use operator overloading to create constraints. See TempConstr for more information.

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

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

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

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPSOL:
    sol = model.cbGetSolution([model._vars[0], model._vars[1]])
    if sol[0] + sol[1] > 1.1:
      model.cbLazy(model._vars[0] + model._vars[1] <= 1)

model._vars = model.getVars()
model.optimize(mycallback)
cbProceed()#

Generate a request to proceed to the next phase of the computation. This routine can be called from any callback. Note that the request is only accepted in a few phases of the algorithm, and it won’t be acted upon immediately.

In the current Gurobi version, this callback allows you to proceed from the NoRel heuristic to the standard MIP search. You can determine the current algorithm phase using MIP_PHASE, MIPNODE_PHASE, or MIPSOL_PHASE queries from a callback.

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPSOL:
    phase = model.cbGet(GRB.Callback.MIPSOL_PHASE)
    obj = model.cbGet(GRB.Callback.MIPSOL_OBJ)
    if phase == GRB.PHASE_MIP_NOREL and obj < target_obj:
      model.cbProceed()

model.optimize(mycallback)
cbSetSolution(vars, solution)#

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

When you specify a heuristic solution from a callback, variables initially take undefined values. You should use this method to specify variable values. You can make multiple calls to cbSetSolution from one callback invocation to specify values for multiple sets of variables. After the callback, if values have been specified for any variables, the Gurobi Optimizer will try to compute a feasible solution from the specified values, possibly filling in values for variables whose values were left undefined. You can also optionally call cbUseSolution within your callback function to try to immediately compute a feasible solution from the specified values.

Note that this method is not supported in a Compute Server environment.

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

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

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPNODE:
    model.cbSetSolution(vars, newsolution)

model.optimize(mycallback)
cbStopOneMultiObj(objcnt)#

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

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

import time

def mycallback(model, where):
  if where == GRB.Callback.MULTIOBJ:
    # get current objective number
    model._objcnt = model.cbGet(GRB.Callback.MULTIOBJ_OBJCNT)

    # reset start time to current time
    model._starttime = time.time()

  # See if we want to stop current multiobjective step
  else if time.time() - model._starttime > 1000:  # or solution is good enough
    # stop only this optimization step
    model.cbStopOneMultiObj(model._objcnt)

model._objcnt = 0
model._starttime = time.time()
model.optimize(mycallback)

You should refer to the section on Multiple Objectives for information on how to specify multiple objective functions and control the trade-off between them.

Parameters:

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

cbUseSolution()#

Once you have imported solution values using cbSetSolution, you can optionally call cbUseSolution in a GRB.Callback.MIPNODE callback to immediately use these values to try to compute a heuristic solution. Alternatively, you can call cbUseSolution in a GRB.Callback.MIP or GRB.Callback.MIPSOL callback, which will store the solution until it can be processed internally.

Returns:

The objective value for the solution obtained from your solution values. It equals GRB.INFINITY if no improved solution is found or the method has been called from a callback other than GRB.Callback.MIPNODE as, in these contexts, the solution is stored instead of being processed immediately.

Example:
def mycallback(model, where):
  if where == GRB.Callback.MIPNODE:
    model.cbSetSolution(vars, newsolution)
    objval = model.cbUseSolution()

model.optimize(mycallback)
chgCoeff(constr, var, newvalue)#

Change one coefficient in the model. The desired change is captured using a Var object, a Constr object, and a desired coefficient for the specified variable in the specified constraint. If you make multiple changes to the same coefficient, the last one will be applied.

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

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

  • var – Variable for coefficient to be changed.

  • newvalue – Desired new value for coefficient.

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

Free all resources associated with this Model object. This method is a synonym for dispose.

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

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

Compute an Irreducible Inconsistent Subsystem (IIS).

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

  • It is still infeasible, and

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

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

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

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

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

If an IIS computation is interrupted before completion, Gurobi will return the smallest infeasible subsystem found to that point.

The IISConstrForce, IISLBForce, IISUBForce, IISSOSForce, IISQConstrForce, and IISGenConstrForce attributes allow you mark model elements to either include or exclude from the computed IIS. Setting the attribute to 1 forces the corresponding element into the IIS, setting it to 0 forces it out of the IIS, and setting it to -1 allows the algorithm to decide.

To give an example of when these attributes might be useful, consider the case where an initial model is known to be feasible, but it becomes infeasible after adding constraints or tightening bounds. If you are only interested in knowing which of the changes caused the infeasibility, you can force the unmodified bounds and constraints into the IIS. That allows the IIS algorithm to focus exclusively on the new constraints, which will often be substantially faster.

Note that setting any of the Force attributes to 0 may make the resulting subsystem feasible, which would then make it impossible to construct an IIS. Trying anyway will result in a IIS_NOT_INFEASIBLE error. Similarly, setting this attribute to 1 may result in an IIS that is not irreducible. More precisely, the system would only be irreducible with respect to the model elements that have force values of -1 or 0.

This method populates the IISConstr, IISQConstr, and IISGenConstr constraint attributes, the IISSOS, SOS attribute, and the IISLB and IISUB variable attributes. You can also obtain information about the results of the IIS computation by writing an .ilp format file (see Model.write). This file contains only the IIS from the original model.

Use the IISMethod parameter to adjust the behavior of the IIS algorithm.

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

Parameters:

callback – Callback function. The callback function should take two arguments, model and where. While the IIS algorithm is running, the function will be called periodically, with model set to the model being optimized, and where indicating where in the optimization the callback is called from. See the Callbacks section for additional information.

Example:
model.computeIIS()
model.write("model.ilp")
copy(targetenv=None)#

Copy a model.

With no arguments, the copy will live in the same environment as the original model. Provide an argument to copy an existing model to a different environment, typically to enable different threads to operate on different versions of the same model, since multiple threads can not simultaneously work within the same environment.

Note that this method itself is not thread safe, so you should either call 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 you should call update before copying if you would like those to be included in the copy.

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

Parameters:

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

Returns:

Copy of model.

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

Discard concurrent environments for a model.

The concurrent environments created by getConcurrentEnv will be used by every subsequent call to the concurrent optimizer until the concurrent environments are discarded.

Example:
env0 = model.getConcurrentEnv(0)
env1 = model.getConcurrentEnv(1)

env0.setParam('Method', 0)
env1.setParam('Method', 1)

model.optimize()

model.discardConcurrentEnvs()
discardMultiobjEnvs()#

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

Please refer to the discussion of Multiple Objectives for information on how to specify multiple objective functions and control the trade-off between them.

Use getMultiobjEnv to create a multi-objective environment.

Example:
env0 = model.getMultiobjEnv(0)
env1 = model.getMultiobjEnv(1)

env0.setParam('Method', 2)
env1.setParam('Method', 1)

model.optimize()

model.discardMultiobjEnvs()
dispose()#

Free all resources associated with this Model object. This method is a synonym for close.

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

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

Modifies the Model object to create a feasibility relaxation. Note that you need to call optimize on the result to compute the actual relaxed solution. Note also that this is a simplified version of this method - use feasRelax for more control over the relaxation performed.

The feasibility relaxation is a model that, when solved, minimizes the amount by which the solution violates the bounds and linear constraints of the original model. This method provides a number of options for specifying the relaxation.

If you specify relaxobjtype=0, the objective of the feasibility relaxation is to minimize the sum of the magnitudes of the bound and constraint violations.

If you specify relaxobjtype=1, the objective of the feasibility relaxation is to minimize the sum of the squares of the bound and constraint violations.

If you specify relaxobjtype=2, the objective of the feasibility relaxation is to minimize the total number of bound and constraint violations.

To give an example, if a constraint is violated by 2.0, it would contribute 2.0 to the feasibility relaxation objective for relaxobjtype=0, it would contribute 2.0*2.0 for relaxobjtype=1, and it would contribute 1.0 for relaxobjtype=2.

The minrelax argument is a boolean that controls the type of feasibility relaxation that is created. If minrelax=False, optimizing the returned model gives a solution that minimizes the cost of the violation. If minrelax=True, optimizing the returned model finds a solution that minimizes the original objective, but only from among those solutions that minimize the cost of the violation. Note that feasRelaxS must solve an optimization problem to find the minimum possible relaxation when minrelax=True, which can be quite expensive.

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

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

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

  • minrelax – The type of feasibility relaxation to perform.

  • vrelax – Indicates whether variable bounds can be relaxed.

  • crelax – Indicates whether constraints can be relaxed.

Returns:

Zero if minrelax is False. If minrelax is True, the return value is the objective value for the relaxation performed. If the value is less than 0, it indicates that the method failed to create the feasibility relaxation.

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

Modifies the Model object to create a feasibility relaxation. Note that you need to call optimize on the result to compute the actual relaxed solution. Note also that this is a more complex version of this method - use feasRelaxS for a simplified version.

The feasibility relaxation is a model that, when solved, minimizes the amount by which the solution violates the bounds and linear constraints of the original model. This method provides a number of options for specifying the relaxation.

If you specify relaxobjtype=0, the objective of the feasibility relaxation is to minimize the sum of the weighted magnitudes of the bound and constraint violations. The lbpen, ubpen, and rhspen arguments specify the cost per unit violation in the lower bounds, upper bounds, and linear constraints, respectively.

If you specify relaxobjtype=1, the objective of the feasibility relaxation is to minimize the weighted sum of the squares of the bound and constraint violations. The lbpen, ubpen, and rhspen arguments specify the coefficients on the squares of the lower bound, upper bound, and linear constraint violations, respectively.

If you specify relaxobjtype=2, the objective of the feasibility relaxation is to minimize the weighted count of bound and constraint violations. The lbpen, ubpen, and rhspen arguments specify the cost of violating a lower bound, upper bound, and linear constraint, respectively.

To give an example, if a constraint with rhspen value p is violated by 2.0, it would contribute 2*p to the feasibility relaxation objective for relaxobjtype=0, it would contribute 2*2*p for relaxobjtype=1, and it would contribute p for relaxobjtype=2.

The minrelax argument is a boolean that controls the type of feasibility relaxation that is created. If minrelax=False, optimizing the returned model gives a solution that minimizes the cost of the violation. If minrelax=True, optimizing the returned model finds a solution that minimizes the original objective, but only from among those solutions that minimize the cost of the violation. Note that feasRelax must solve an optimization problem to find the minimum possible relaxation when minrelax=True, which can be quite expensive.

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

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

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

  • 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 for each variable in argument vars.

  • ubpen – Penalty for violating a variable upper bound. One entry for each variable in argument vars.

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

  • rhspen – Penalty for violating a linear constraint. One entry for each constraint in argument constrs.

Returns:

Zero if minrelax is False. If minrelax is True, the return value is the objective value for the relaxation performed. If the value is less than 0, it indicates that the method failed to create the feasibility relaxation.

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

Create the fixed model associated with a MIP model. The MIP model must have a solution loaded (e.g., after a call to the optimize method). In the fixed model, each integer variable is fixed to the value that variable takes in the MIP solution. In addition, continuous variables may be fixed to satisfy SOS or general constraints. The result is a model without any integrality constraints, SOS constraints, or general constraints.

Note that, while the fixed problem is always a continuous model, it may contain a non-convex quadratic objective or non-convex quadratic constraints. As a result, it may still be solved using the MIP algorithm.

Returns:

Fixed model associated with calling object.

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

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

Returns:

The matrix as a scipy.sparse matrix in CSR format.

Example:
A     = model.getA()
sense = numpy.array(model.getAttr("Sense",model.getConstrs()))
# extract sub matrices of (in)equality constraints
Aeq = A[sense == '=', :]
Ale = A[sense == '<', :]
Age = A[sense == '>', :]
getAttr(attrname, objs=None)#

Query the value of an attribute. When called with a single argument, it returns the value of a model attribute. When called with two arguments, it returns the value of an attribute for either a list or a dictionary containing either variables or constraints. If called with a list, the result is a list. If called with a dictionary, the result is a dictionary that uses the same keys, but is populated with the requested attribute values. The full list of available attributes can be found in the Attributes section.

Raises an AttributeError if the requested attribute doesn’t exist or can’t be queried. Raises a GurobiError if there is a problem with the Model object.

Parameters:
  • attrname – Name of the attribute.

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

Example:
print(model.numintvars)
print(model.getAttr("numIntVars"))
print(model.getAttr(GRB.Attr.NumIntVars))
print(model.getAttr("X", model.getVars()))
print(model.getAttr("Pi", model.getConstrs()))
getCoeff(constr, var)#

Query the coefficient of variable var in linear constraint constr (note that the result can be zero).

Parameters:
  • constr – The requested constraint.

  • var – The requested variable.

Returns:

The current value of the requested coefficient.

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

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

Parameters:

var – The variable of interest.

Returns:

A Column object that captures the set of constraints in which the variable participates.

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

Create/retrieve a concurrent environment for a model.

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

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

Once you create concurrent environments, they will be used for every subsequent concurrent optimization on that model. Use discardConcurrentEnvs to revert back to default concurrent optimizer behavior.

Parameters:

num – (int) The concurrent environment number.

Returns:

The concurrent environment for the model.

Example:
env0 = model.getConcurrentEnv(0)
env1 = model.getConcurrentEnv(1)

env0.setParam('Method', 0)
env1.setParam('Method', 1)

model.optimize()

model.discardConcurrentEnvs()
getConstrByName(name)#

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

Parameters:

name – Name of desired constraint.

Returns:

Constraint with the specified name.

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

Retrieve a list of all linear constraints in the model.

Returns:

All linear constraints in the model.

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

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

See also addGenConstrMax for a description of the semantics of this general constraint type.

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

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

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

  • constant – (float) Additional constant operand of the MAX constraint.

Returns:

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

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

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

See also addGenConstrMin for a description of the semantics of this general constraint type.

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

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

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

  • constant – (float) Additional constant operand of the MIN constraint.

Returns:

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

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

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

See also addGenConstrAbs for a description of the semantics of this general constraint type.

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

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

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

Returns:

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

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

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

See also addGenConstrAnd for a description of the semantics of this general constraint type.

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

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

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

Returns:

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

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

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

See also addGenConstrOr for a description of the semantics of this general constraint type.

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

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

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

Returns:

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

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

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

See also addGenConstrNorm for a description of the semantics of this general constraint type.

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

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

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

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

Returns:

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

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

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

See also addGenConstrIndicator for a description of the semantics of this general constraint type.

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

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

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

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

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

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

Returns:

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

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

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

See also addGenConstrPWL for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

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

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

Returns:

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

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

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

See also addGenConstrPoly for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

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

Returns:

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

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

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

See also addGenConstrExp for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

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

See also addGenConstrExpA for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

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

Returns:

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

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

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

See also addGenConstrLog for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

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

See also addGenConstrLogA for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

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

Returns:

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

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

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

See also addGenConstrLogistic for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

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

See also addGenConstrPow for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

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

Returns:

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

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

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

See also addGenConstrSin for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

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

See also addGenConstrCos for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

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

See also addGenConstrTan for a description of the semantics of this general constraint type.

Parameters:
  • genc – The general constraint object.

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

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

Returns:

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

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

Retrieve a list of all general constraints in the model.

Returns:

All general constraints in the model.

Example:
gencons = model.getGenConstrs()
for gc in gencons:
    if gc.GenConstrType == GRB.GENCONSTR_INDICATOR:
        (binvar, binval, expr, sense, rhs) = model.getGenConstrIndicator(gc)
    elif gc.GenConstrType == GRB.GENCONSTR_MAX:
        (resvar, vars, constant) = model.getGenConstrMax(gc)
    ...
getJSONSolution()#

After a call to optimize, this method returns the resulting solution and related model attributes as a JSON string. Please refer to the JSON solution format section for details.

Returns:

A JSON string.

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

Create/retrieve a multi-objective environment for the optimization pass with the given index. This environment enables fine-grained control over the multi-objective optimization process. Specifically, by changing parameters on this environment, you modify the behavior of the optimization that occurs during the corresponding pass of the multi-objective optimization.

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

Please refer to the discussion of Multiple Objectives for information on how to specify multiple objective functions and control the trade-off between them.

Please refer to the discussion on Combining Blended and Hierarchical Objectives for information on the optimization passes to solve multi-objective models.

Use discardMultiobjEnvs to discard multi-objective environments and return to standard behavior.

Parameters:

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

Returns:

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

Example:
env0 = model.getMultiobjEnv(0)
env1 = model.getMultiobjEnv(1)

env0.setParam('TimeLimit', 100)
env1.setParam('TimeLimit', 10)

model.optimize()

model.discardMultiobjEnvs()
getObjective(index=None)#

Retrieve the model objective(s).

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

Parameters:

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

Returns:

The model objective. A LinExpr object for a linear objective, or a QuadExpr object for a quadratic objective. Note that alternative objectives are always linear.

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

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

Please consult the parameter section for a complete list of Gurobi parameters, including descriptions of their purposes and their minimum, maximum, and default values.

Parameters:

paramname – String containing the name of the parameter of interest. The name can include ‘*’ and ‘?’ wildcards. If more than one parameter matches, the matching names are listed and the method returns None.

Returns:

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

Example:
print(model.getParamInfo('Heuristics'))
getPWLObj(var)#

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

Refer to this discussion for additional information on what the values in \(x\) and \(y\) mean.

Parameters:

var – A Var object that gives the variable whose objective function is being retrieved.

Returns:

The points that define the piecewise-linear objective function.

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

Retrieve a list of all quadratic constraints in the model.

Returns:

All quadratic constraints in the model.

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

Retrieve the left-hand side expression from a quadratic constraint. The result is returned as a QuadExpr object.

Parameters:

qconstr – The constraint of interest. A QConstr object, typically obtained from addQConstr or getQConstrs.

Returns:

A QuadExpr object that captures the left-hand side of the quadratic constraint.

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

Retrieve the list of variables that participate in a constraint, and the associated coefficients. The result is returned as a LinExpr object.

Parameters:

constr – The constraint of interest. A Constr object, typically obtained from addConstr or getConstrs.

Returns:

A LinExpr object that captures the set of variables that participate in the constraint.

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

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

Parameters:

sos – The SOS constraint of interest. An SOS object, typically obtained from addSOS or getSOSs.

Returns:

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

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

Retrieve a list of all SOS constraints in the model.

Returns:

All SOS constraints in the model.

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

Use this routine to retrieve the results of a previous tune call. Calling this method with argument n causes tuned parameter set n to be copied into the model. Parameter sets are stored in order of decreasing quality, with parameter set 0 being the best. The number of available sets is stored in attribute TuneResultCount.

Once you have retrieved a tuning result, you can call optimize to use these parameter settings to optimize the model, or write to write the changed parameters to a .prm file.

Please refer to the parameter tuning section for details on the tuning tool.

Parameters:

n – The index of the tuning result to retrieve. The best result is available as index 0. The number of stored results is available in attribute TuneResultCount.

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

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

Parameters:

name – Name of desired variable.

Returns:

Variable with the specified name.

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

Retrieve a list of all variables in the model.

Returns:

All variables in the model.

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

Append a string to the Gurobi log file.

Parameters:

msg – String to append to Gurobi log file.

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

Optimize the model. The algorithm used for the optimization depends on the model type (simplex or barrier for a continuous model; branch-and-cut for a MIP model). Upon successful completion, this method will populate the solution related attributes of the model. See the Attributes section for more information on attributes.

Please consult this section for a discussion of some of the practical issues associated with solving a precisely defined mathematical model using finite-precision floating-point arithmetic.

Note that this method will process all pending model modifications.

Parameters:

callback – Callback function. The callback function should take two arguments, model and where. During the optimization, the function will be called periodically, with model set to the model being optimized, and where indicating where in the optimization the callback is called from. See the Callbacks section for additional information.

Example:
model.optimize()
optimizeBatch()#

Submit a new batch request to the Cluster Manager. Returns the BatchID (a string), which uniquely identifies the job in the Cluster Manager and can be used to query the status of this request (from this program or from any other). Once the request has completed, the BatchID can also be used to retrieve the associated solution. To submit a batch request, you must tag at least one element of the model by setting one of the VTag, CTag or QCTag attributes. For more details on batch optimization, please refer to the Batch Optimization section.

Note that this routine will process all pending model modifications.

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

A unique string identifier for the batch request.

Params#

Get or set parameter values.

Example:
# Print the current value of the MIPFocus parameter
print(model.Params.MIPFocus)

# Set a 10 second time limit for the next optimize() call
model.Params.TimeLimit = 10.0
presolve()#

Perform presolve on a model.

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

Returns:

Presolved version of original model.

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

Print the value of one or more attributes. If attrs is a constraint or variable attribute, print all non-zero values of the attribute, along with the associated constraint or variable names. If attrs is a list of attributes, print attribute values for all listed attributes. The method takes an optional filter argument, which allows you to select which specific attribute values to print (by filtering on the constraint or variable name).

See the Attributes section for a list of all available attributes.

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

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

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

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

For continuous models, the output will include the maximum unscaled and scaled violation, as well as the variable or constraint name associated with the worst unscaled violation. For MIP models, the output will include the maximum unscaled violation and the associated variable or constraint name.

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

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

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

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

Note that reading a file does not process all pending model modifications. These modifications can be processed by calling Model.update.

Note also that this is not the method to use if you want to read a new model from a file. For that, use the read command.

Parameters:

filename – Name of the file to read. The suffix on the file must be either .bas (for an LP basis), .mst or .sol (for a MIP start), .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 followed by .zip, .gz, .bz2, or .7z. The file name may contain * or ? wildcards. No file is read when no wildcard match is found. If more than one match is found, this method will attempt to read the first matching file.

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

Create the relaxation of a MIP model. Transforms integer variables into continuous variables, and removes SOS and general constraints.

Returns:

Relaxed version of model.

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

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

Parameters:

items – The items to remove from the model. Argument can be a single Var, MVar, Constr, MConstr, QConstr, MQConstr, SOS, or GenConstr, or a list, tuple, or dict containing these objects. If the argument is a dict, the values will be removed, not the keys.

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

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

Parameters:

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

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

Reset all parameters to their default values.

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

Change the value of an attribute.

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

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

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

Raises an AttributeError if the specified attribute doesn’t exist or can’t be set. Raises a GurobiError if there is a problem with the Model object.

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

Parameters:
  • attrname – Name of attribute to set.

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

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

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

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

Note that you will typically use overloaded operators to set the objective using matrix objects. The overloaded @ operator can be used to build a linear matrix expression or a quadratic matrix expression, which is then passed to setObjective.

Parameters:
  • Q – The quadratic objective matrix - a NumPy 2-D dense ndarray or a SciPy sparse matrix. This can be None if there are no quadratic terms.

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

  • constant – Objective constant.

  • xQ_L – (optional) Decision variables for quadratic objective terms; left multiplier for Q. Argument can be an MVar object, a list of Var objects, or None (None uses all variables in the model). The length of the argument must match the size of the first dimension of Q.

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

  • xc – (optional) Decision variables for linear objective terms. Argument can be an MVar object, a list of Var objects, or None (None uses all variables in the model). The length of the argument must match the length of c.

  • sense – (optional) Optimization sense (GRB.MINIMIZE for minimization, GRB.MAXIMIZE for maximization). Omit this argument to use the ModelSense attribute value to determine the sense.

Example:
c = np.full(10, 1.0)
xc = model.addMVar(10)

model.setMObjective(None, c, 0.0, None, None, xc, GRB.MAXIMIZE)

Q = np.full((2, 3), 1.0)
xL = model.addMVar(2)
xR = model.addMVar(3)

model.setMObjective(Q, None, 0.0, xL, xR, None, GRB.MINIMIZE)
setObjective(expr, sense=None)#

Set the model objective equal to a linear or quadratic expression (for multi-objective optimization, see setObjectiveN).

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

Parameters:
  • expr – New objective expression. Argument can be a linear or quadratic expression (an objective of type LinExpr or QuadExpr).

  • sense – (optional) Optimization sense (GRB.MINIMIZE for minimization, GRB.MAXIMIZE for maximization). Omit this argument to use the ModelSense attribute value to determine the sense.

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

Set an alternative optimization objective equal to a linear expression.

Please refer to the discussion of Multiple Objectives for more information on the use of alternative objectives.

Note that you can also modify an alternative objective using the ObjN variable attribute. If you wish to mix and match these two approaches, please note that this method replaces the entire existing objective, while the ObjN attribute can be used to modify individual terms.

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

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

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

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

  • abstol – (float, optional) Absolute tolerance for the alternative objective. This initializes the ObjNAbsTol attribute for this objective.

  • reltol – (float, optional) Relative tolerance for the alternative objective. This initializes the ObjNRelTol attribute for this objective.

  • name – (string, optional) Name of the alternative objective. This initializes the ObjNName attribute for this objective. Note that name will be stored as an ASCII string. Thus, a name like ‘A\({\rightarrow}\)B’ will produce an error, because ‘\({\rightarrow}\)‘ can not be represented as an ASCII character. Note also that names that contain spaces are strongly discouraged, because they can’t be written to LP format files.

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

Set a piecewise-linear objective function for a variable.

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

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

Parameters:
  • var – A Var object that gives the variable whose objective function is being set.

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

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

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

Set the value of a parameter to a new value. Note that this method only affects the parameter setting for this model. Use global function setParam to change the parameter for all models.

You can also set parameters using the Model.Params class. For example, to set parameter MIPGap to value 0 for model m, you can do either m.setParam('MIPGap', 0) or m.Params.MIPGap=0.

Please consult the parameter section for a complete list of Gurobi parameters, including descriptions of their purposes and their minimum, maximum, and default values.

Parameters:
  • paramname – String containing the name of parameter that you would like to modify. The name can include ‘*’ and ‘?’ wildcards. If more than one parameter matches, the matching names are listed and none are modified. Note that case is ignored.

  • newvalue – Desired new value for parameter. Can be ‘default’, which indicates that the parameter should be reset to its default value.

Example:
model.setParam("heu*", 0.5)
model.setParam(GRB.Param.heuristics, 0.5)
model.setParam("heu*", "default")
singleScenarioModel()#

Capture a single scenario from a multi-scenario model. Use the ScenarioNumber parameter to indicate which scenario to capture.

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

Returns:

Model for a single scenario.

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

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

When the optimization stops, the Status attribute will be equal to GRB_INTERRUPTED.

Example:
model.terminate()
tune()#

Perform an automated search for parameter settings that improve performance. Upon completion, this method stores the best parameter sets it found. The number of stored parameter sets can be determined by querying the value of the TuneResultCount attribute. The actual settings can be retrieved using getTuneResult.

Please refer to the parameter tuning section for details on the tuning tool.

Example:
model.tune()
update()#

Process any pending model modifications.

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

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

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

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

Parameters:

filename – The name of the file to be written. The file type is 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 pure LP), .ilp for writing just the IIS associated with an infeasible model (see Model.computeIIS for further information), .sol for writing the solution selected by the SolutionNumber parameter, .mst for writing a start vector, .hnt for writing a hint file, .bas for writing an LP basis, .prm for writing modified parameter settings, .attr for writing model attributes, or .json for writing solution information in JSON format. If your system has compression utilities installed (e.g., 7z or zip for Windows, and gzip, bzip2, or unzip for Linux or macOS), then the files can be compressed, so additional suffixes of .gz, .bz2, or .7z are accepted.

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