gurobipy.MVar#

class MVar#

Gurobi matrix variable object. An MVar is a NumPy ndarray of Gurobi variables. Variables are always associated with a particular model. You typically create these objects using Model.addMVar.

Many concepts, properties and methods of the MVar class lean on equivalents in NumPy’s ndarray class. For explanations of concepts like shape, dimensions, or broadcasting, we refer you to the NumPy documentation.

You generally use MVar objects to build matrix expressions, typically using overloaded operators. You can build linear matrix expressions or quadratic matrix expressions:

expr1 = A @ x
expr2 = A @ x + B @ y + z
expr3 = x @ A @ x + y @ B @ y

The first two expressions are linear, while the third is quadratic.

In the examples above (and in general), \(A\) and \(B\) can be NumPy ndarray objects or any of the sparse matrix classes defined in SciPy.sparse. Dimensions of the operands must compatible, in the usual sense of Python’s matrix multiplication operator. For example, in the expression \(A @ x\), both \(A\) and \(x\) must have at least one dimension, and their inner-most dimensions must agree. For a complete description of shape compatibility rules, we refer you to Python’s documentation

An expression is typically then passed to setObjective (to set the optimization objective) or addConstr (to add a constraint).

Variable objects have a number of attributes. The full list can be found in the Attributes section of this document. Some variable attributes can only be queried, while others can also be set. Recall that the Gurobi optimizer employs a lazy update approach, so changes to attributes don’t take effect until the next call to Model.update, Model.optimize, or Model.write on the associated model.

We should point out a few things about variable attributes. Consider the lb attribute. Its value can be queried using mvar.lb. The Gurobi library ignores letter case in attribute names, so it can also be queried as var.LB. Attribute values are returned as a NumPy ndarray that has the same shape as mvar, where each element contains the attribute value for the corresponding element of the MVar object. An attribute can be set, using a standard assignment statement (e.g., var.lb = l), with l being either an ndarray with the appropriate shape, or a scalar which is then applied to all of the associated variables. However, as mentioned earlier, attribute modification is done in a lazy fashion, so you won’t see the effect of the change immediately. And some attributes can not be set (e.g., the x attribute), so attempts to assign new values to them will raise an exception.

You can also use MVar.getAttr/ MVar.setAttr to access attributes. The attribute name can be passed to these routines as a string, or you can use the constants defined in the GRB.Attr class (e.g., GRB.Attr.LB).

copy()#

Create a copy of this MVar.

Returns:

The new object.

Example:
orig = model.addMVar(3)
copy = orig.copy()
diagonal(offset=0, axis1=0, axis2=1)#

Create an MVar corresponding to the variables on the specified diagonal of this MVar.

Parameters:
  • offset – (optional) Offset of the diagonal w.r.t. the main diagonal. Values >0 mean above it, and values <0 below it

  • axis1 – (optional) Axis to be used as the first axis of the 2-D sub-MVar from which the diagonal should be taken. Defaults to 0. You need to consider this argument only for MVar objects with more than 2 dimensions.

  • axis2 – (optional) Axis to be used as the second axis of the 2-D sub-MVar from which the diagonal should be taken. Defaults to 1. You need to consider this argument only for MVar objects with more than 2 dimensions.

Returns:

An MVar representing the requested diagonal of this MVar.

Example:
x = model.addMVar((8, 8))
diag_main = x.diagonal()  # The main diagonal of x
diag_sup = x.diagonal(1)  # The first superdiagonal of x
diag_sup = x.diagonal(-2)  # The second subdiagonal of x
adiag_main = x[:, ::-1].diagonal()  # The main anti-diagonal of x
fromlist(varlist)#

Convert a list of variables into an MVar object. The shape is inferred from the contents of the list - a list of Var objects produces a 1-D MVar object, a list of lists of Var objects produces a 2-D MVar, etc.

Parameters:

varlist – A list of Var objects to populate the returned MVar.

Returns:

MVar object corresponding to the input variables.

Example:
x0 = model.addVar()
x1 = model.addVar()
x2 = model.addVar()
x3 = model.addVar()
x_1d = MVar.fromlist([x0, x1, x2, x3])  # 1-D MVar
x_2d = MVar.fromlist([[x0, x1], [x2, x3]])  # 2-D MVar
fromvar(var)#

Convert a Var object into a 0-dimensional MVar object.

Parameters:

var – The variable object to populate the returned MVar.

Returns:

MVar object corresponding to the input variable.

Example:
x = model.addVar()
x_as_mvar = MVar.fromvar(x)
getAttr(attrname)#

Query the value of an attribute for a matrix variable. 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 MVar object (e.g., it was removed from the model).

The result is returned in a NumPy ndarray with the same shape as the MVar object.

Parameters:

attrname – The attribute being queried.

Returns:

Current values for the requested attribute.

Example:
print(var.getAttr(GRB.Attr.X))
print(var.getAttr("x"))
item()#

For an MVar that contains a single element, returns a copy of that element as a Var object. Calling this method on an MVar with more than one element will raise a ValueError.

Returns:

A Var object

Example:
x = model.addMVar((2, 2))
x_sub = x[0, 1]  # A 0-D MVar encapsulating one Var object
x_var = x[0, 1].item()  # The resident Var object itself
property ndim#

The number of dimensions in this matrix variable.

Returns:

An int

Example:
x1 = model.addMVar((3,))
print(x1.ndim)  #  "1"
x2 = model.addMVar((1, 3))
print(x2.ndim)  #  "2"
reshape(shape, order='C')#

Return a copy of this MVar with the same variables, but with a new shape.

Parameters:
  • shape – An int, or a tuple of int. The new shape should be compatible with this MVar’s shape. The special value of -1 can be passed in at one position, which then infers the length of that dimension from the overall number of Var objects in the MVar and the provided lengths of the other dimensions.

  • order – (optional) A string ‘C’ or ‘F’. Read the elements of this MVar using C-like (‘C’) or Fortran-like (‘F’) order, and write the elements into the reshaped array in this order.

Returns:

An MVar of requested shape

Example:
x = model.addMVar((2, 2))
x_vec = x.reshape(-1, order='C')  # 1-D result, rows of x stacked
x_vec = x.reshape(-1, order='F')  # 1-D result, columns of x stacked
setAttr(attrname, newvalue)#

Set the value of a matrix variable attribute.

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

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 MVar object (e.g., it was removed from the model).

Parameters:
  • attrname – The attribute being modified.

  • newvalue – The desired new value of the attribute. The shape must be the same as the MVar object. Alternatively, you can pass a scalar argument, which will automatically be promoted to have the right shape.

Example:
var.setAttr("ub", np.full((5,), 0)
var.setAttr(GRB.Attr.UB, 0.0)
var.setAttr("ub", 0.0)
property shape#

The shape of this MVar.

Returns:

A tuple of int

Example:
x1 = model.addMVar((3,))
print(x1.shape)  #  "(3,)"
x2 = model.addMVar((1, 3))
print(x2.shape)  #  "(1, 3)"
property size#

The total number of elements in this matrix variable.

Returns:

An int

Example:
x1 = model.addMVar((3,))
print(x1.size)  #  "3"
x2 = model.addMVar((2, 3))
print(x2.size)  #  "6"
sum(axis=None)#

Sum the elements of the MVar; returns an MLinExpr object.

Parameters:

axis – An int, or None. Sum along the specified axis. If set to None, summation takes place along all axes of this MVar.

Returns:

An MLinExpr representing the sum.

Example:
x = model.addMVar((2, 2))
sum_row = x.sum(axis=0)  # Sum along the rows of X
sum_col = x.sum(axis=1)  # Sum along the columns of X
sum_all = x.sum()  # Sum all variables in this MVar
property T#

Synonymous property for transpose.

Example:
x = model.addMVar((4, 1))  # Resembles a "column vector"
x_t = x.T  # Same variables, but as a "row vector"
y = model.addMVar((3, 2))
y_t = x.T  # Has shape (2, 3)
tolist()#

Return the variables associated with this matrix variable as a list of individual Var objects.

Returns:

List of Var objects.

Example:
mvar = model.addMVar(5)
varlist = mvar.tolist()
# Do something with the Var correponding to mvar[3]
print(varlist[3])
transpose()#

Transpose this MVar; create a new MVar object by reversing the order of the original MVar’s axes. For 1-D MVar objects, this routine simply returns a copy of the original MVar.

Returns:

An MVar object representing the transpose.

Example:
x = model.addMVar((4, 1))  # Resembles a "column vector"
x_t = x.transpose()  # Same variables, but as a "row vector"
y = model.addMVar((3, 2))
y_t = x.transpose()  # Has shape (2, 3)