Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

gurobipy.MVar#

classMVar#

Gurobi matrix variable object. AnMVar is a NumPy ndarray of Gurobivariables. Variables are always associated with a particular model. Youtypically create these objects usingModel.addMVar.

Many concepts, properties and methods of the MVar class lean onequivalents in NumPy’s ndarray class. For explanations of concepts likeshape, dimensions, or broadcasting, we refer you to the NumPydocumentation.

You generally useMVar objects to build matrix expressions,typically using overloaded operators. You can buildlinearmatrixexpressions orquadraticmatrixexpressions:

expr1=A@xexpr2=A@x+B@y+zexpr3=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 beNumPy ndarray objects or any of the sparse matrix classes defined inSciPy.sparse. Dimensions of the operands must compatible, in the usualsense of Python’s matrix multiplication operator. For example, in theexpression\(A @ x\), both\(A\) and\(x\) must have atleast one dimension, and their inner-most dimensions must agree. For acomplete description of shape compatibility rules, we refer you toPython’s documentation

An expression is typically then passed tosetObjective (to set the optimizationobjective) oraddConstr (to add aconstraint).

MVar objects support standard NumPy indexing and slicing. An MVar ofsize\(1\) can be passed in all places where gurobipy accepts a Varobject.

Variable objects have a number of attributes. Somevariable attributes can only be queried, while others can also be set.Recall that the Gurobi Optimizer employs a lazy update approach, sochanges to attributes don’t take effect until the next call toModel.update,Model.optimize, orModel.write on the associated model.

We should point out a few things about variable attributes. Consider thelb attribute. Its value can be queried usingmvar.lb. The Gurobilibrary ignores letter case in attribute names, so it can also bequeried asvar.LB. Attribute values are returned as a NumPyndarray that has the same shape asmvar, where each elementcontains the attribute value for the corresponding element of theMVar object. An attribute can be set, using a standard assignmentstatement (e.g.,var.lb=l), withl being either anndarraywith the appropriate shape, or a scalar which is then applied to all ofthe associated variables. However, as mentioned earlier, attributemodification is done in a lazy fashion, so you won’t see the effect ofthe change immediately. And some attributes can not be set (e.g., thex attribute), so attempts to assign new values to them will raise anexception.

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

The full list of attributescan be found in theAttributes section of thisdocument. Examples of how to query and set attributes can also be foundinthis section.

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 diagonalof this MVar.

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

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

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

Returns:

An MVar representing the requested diagonal of this MVar.

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

Convert a list of variables into an MVar object. The shape is inferredfrom the contents of the list - a list of Var objects produces a 1-DMVar 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 MVarx_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.

Raises anAttributeError if the requested attribute doesn’t exist orcan’t be queried. Raises aGurobiError if there is a problem withtheMVar object (e.g., it was removed from the model).

The result is returned in a NumPy ndarray with the same shape as theMVar 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 thatelement as a Var object. Calling this method on an MVar with more thanone 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 objectx_var=x[0,1].item()# The resident Var object itself
propertyndim#

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

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

  • order – (optional) A string ‘C’ or ‘F’. Read the elements of thisMVar using C-like (‘C’) or Fortran-like (‘F’) order, and write theelements 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 stackedx_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 (usingModel.update), optimize the model (usingModel.optimize), or write the model to disk (usingModel.write).

Raises anAttributeError if the specified attribute doesn’t exist orcan’t be set. Raises aGurobiError if there is a problem with theMVar 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 mustbe the same as theMVar object. Alternatively, you can pass a scalarargument, 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)
propertyshape#

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)"
propertysize#

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 anMLinExpr object.

Parameters:

axis – An int, or None. Sum along the specified axis. If set toNone, 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 Xsum_col=x.sum(axis=1)# Sum along the columns of Xsum_all=x.sum()# Sum all variables in this MVar
propertyT#

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 ofindividualVar objects.

Returns:

List ofVar objects.

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

Transpose this MVar; create a new MVar object by reversing the order ofthe original MVar’s axes. For 1-D MVar objects, this routine simplyreturns 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)
propertynl#

Returns anMNLExpr representing this matrix variable.Using this property is as advanced technique and is not requiredin the vast majority of cases. SeeMore control over expression creationfor further details.

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp