Movatterモバイル変換


[0]ホーム

URL:


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

Concepts

Features

Reference

Gurobi
Back to top

gurobipy.MLinExpr#

classMLinExpr#

Gurobi linear matrix expression object. A linear matrix expressionresults from an arithmetic operation with anMVar object. Acommon example is a matrix-vector product, where the matrix is a NumPyndarray or a SciPy sparse matrix and the vector is a GurobiMVar object. Linear matrix expressions are used to buildlinear objectives and constraints. They are temporary objects thattypically have short lifespans.

You generally build linear matrix expressions using overloadedoperators, typically by multiplying a 2-D matrix (dense or sparse) by a1-DMVar object using the Python matrix multiply (@)operator (e.g.,expr=A@x). You can also promote anMVarobject to anMLinExpr using arithmetic expressions (e.g.,expr=x+1). Most arithmetic operations are supported onMLinExpr objects, including addition and subtraction (e.g.,expr=A@x-B@y), multiplication by a constant (e.g.expr=2*A@x), and point-wise multiplication with an ndarray ora sparse matrix. AnMLinExpr object containing empty expressions canbe created using thezeros method.

AnMLinExpr object has ashape representing its dimensions, asize that counts the total number of elements, and anndim thatgives the number of dimensions. These properties lean on theircounterparts in NumPy’s ndarray class.

When working withMLinExpr objects, you need to make sure that theoperands’ shapes are compatible. For matrix multiplication, we followthe rules of Python’s matrix multiplication operator: both operands needto have at least one dimension, and their inner dimensions must agree.For more information we refer you to Python’s documentation. Otherbinary operations such as addition and multiplication arestraightforward to understand if both operands have the same shape: theoperation is applied point wise on the matching indices. For operandsthat have different shapes, the arithmetic follows NumPy’s broadcastingrules. We refer you to the NumPy documentation for more information.

The full list of overloaded operators onMLinExpr objects isas follows:+,+=,-,-=,*,*=, and@. InPython parlance, we’ve defined the followingMLinExpr functions:__add__,__radd__,__iadd__,__sub__,__rsub__,__isub__,__neg__,__mul__,__rmul__,__imul__,__matmul__, and__rmatmul__.

We’ve also overloaded the comparison operators (==,<=, and>=), to make it easierto build constraints from linear matrix expressions.

clear()#

Reset this expression to all zeros.

Example:
expr=2*model.addMVar(3)+1expr.clear()# All three entries are reset to constant 0.0
copy()#

Create a copy of a linear matrix expression.

Returns:

Copy of expression object.

Example:
orig=2*model.addMVar(3)+1.0copy=orig.copy()copy+=2.0# Leaves 'orig' untouched
getValue()#

Compute the value of a linear matrix expression using the currentsolution.

Returns:

Value of expression as an ndarray.

Example:
expr=A@x+bmodel.addConstr(expr==0)model.optimize()val=expr.getValue()
item()#

For an MLinExpr that contains a single element, returns a copy of thatelement as a LinExpr object. Calling this method on an MLinExpr withmore than one element will raise a ValueError.

Returns:

An LinExpr object

Example:
mle=2*model.addMVar((2,2))+1mle_sub=mle[0,1]# A 0-D MLinExpr encapsulating one LinExpr objectmle_le=mle[0,1].item()# A copy of the resident LinExpr object
propertyndim#

The number of dimensions in this expression.

Returns:

An int

Example:
expr1=2*model.addMVar((3,))+1print(expr1.ndim)#  "1"expr2=2*model.addMVar((1,3))+1print(expr2.ndim)#  "2"
propertyshape#

The shape of this expression.

Returns:

A tuple of int

Example:
expr1=2*model.addMVar((3,))+1print(expr1.shape)#  "(3,)"expr2=2*model.addMVar((1,3))+1print(expr2.shape)#  "(1, 3)"
propertysize#

The total number of elements in this expression.

Returns:

An int

Example:
expr1=2*model.addMVar((3,))+1print(expr1.size)#  "3"expr2=2*model.addMVar((2,3))+1print(expr2.size)#  "6"
sum(axis=None)#

Sum the elements of this MLinExpr; returns anMLinExprobject.

Parameters:

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

Returns:

An MLinExpr representing the sum.

Example:
expr=2*model.addMVar((2,2))-1sum_row=expr.sum(axis=0)# Sum along the rowssum_col=expr.sum(axis=1)# Sum along the columnssum_all=expr.sum()# Sum all elements, result is 0-D
zeros(shape)#

Construct an all-zero MLinExpr object of the given shape.

Parameters:

shape – An int, or tuple of int. The requested shape.

Returns:

An MLinExpr, initialized to zero.

Example:
mle=gp.MLinExpr.zeros(3)x=model.addMVar(3)mle+=2*x
__eq__()#

Overloads the== operator, creating aTempConstr objectthat captures an array of equality constraints. The result is typicallyimmediately passed toModel.addConstr.

Returns:

ATempConstr object.

Example:
m.addConstr(A@x==1)
__ge__(arg)#

Overloads the>= operator, creating aTempConstr objectthat captures an array of inequality constraints. The result istypically immediately passed toModel.addConstr.

Returns:

ATempConstr object.

Example:
m.addConstr(A@x>=1)
__getitem__()#

Index or slice this MLinExpr.

Returns:

AnMLinExpr object.

Example:
mle=2*m.addMVar((2,2))col0=mle[:,0]# The first column of mle, 1-D resultelmt=mle[1,0]# The element at position (1, 0), 0-D result

You can index and slice MLinExpr objects like you would index NumPy’sndarray, and indexing behavior is straightforward to understand if youonlyread from the returned object. When youwrite to the returnedobject, be aware that some kinds of indexing return NumPyviews on theindexed expression (e.g., slices), while others result in copies beingreturned (e.g., fancy indexing). Here is an example:

Example:
mle=2*m.addMVar(4)leading_part_1=mle[:2]leading_part_2=mle[[0,1]]leading_part_1+=99# This modifies mle, tooleading_part_2+=1# This doesn't modify mle

If you are unsure about any of these concepts and want to avoid any riskof accidentally writing back to the indexed object, you should alwayscombine indexing with thecopy method.

Example:
expr=2*model.addMVar((2,2))+1first_col=expr[:,0].copy()first_col=+1# Leaves expr untouched
__le__()#

Overloads the<= operator, creating aTempConstr objectthat captures an array of inequality constraints. The result istypically immediately passed toModel.addConstr.

Returns:

ATempConstr object.

Example:
m.addConstr(A@x<=1)
__setitem__()#

Assign into this MLinExpr.

Example:
mle=2*model.addMVar((2,2))v=model.addVar()w=model.addVar()mle[:]=v+1# Overwrite mle with four independent copies of 'v+1'mle[1,1]=w# Overwrite the entry at position (1, 1) of mle with 'w'

Note that assignment into an existing MLinExpr always entails multipledata copies and is less efficient than building matrix expressionsthrough operations with MVar objects.

Help and Feedback

On this page

[8]ページ先頭

©2009-2025 Movatter.jp