If you are using Gurobi 10 or later
You can natively multiply two MLinExpr objects together following normal matrix multiplication rules. For example, consider the following constraint:
$$\begin{align} y &= (Ax + b)^\top (Ax + b). \end{align}$$
This can be formulated naturally as follows:
import gurobipy as gp
import numpy as np
m = gp.Model()
x = m.addMVar(3)
y = m.addMVar(1)
A = np.random.rand(4,3)
b = np.random.rand(4)
m.addConstr(y == (A @ x + b) @ (A @ x + b))
If you are using Gurobi 9.x
In Gurobi 9.x, it was not possible to multiply two MLinExpr objects together to create an MQuadExpr object. The above code would result in GurobiError: Cannot multiply with an MLinExpr from the left.
To work around this in version 9.x, define an auxiliary MVar \( z \) equal to \( A x + b \), then set \( y \) equal to the inner product \( z^\top z \):
import gurobipy as gp
from gurobipy import GRB
import numpy as np
m = gp.Model()
x = m.addMVar(3)
y = m.addMVar(1)
z = m.addMVar(4, lb=-GRB.INFINITY)
A = np.random.rand(4,3)
b = np.random.rand(4)
m.addConstr(z == A @ x + b)
m.addConstr(y == z @ z)
Note: Gurobi 9.0 introduced the first version of the Python matrix API. The developers are continually working to improve the usability of the matrix API.
Further information
- How do I pointwise multiply a numpy vector with a (1,) MVar with the matrix-friendly Python API?
- How do I pointwise multiply two MVars with the matrix-friendly Python API?
- How do I multiply an array and a 2-D MVar object using the matrix-friendly Python API?
- How do I pointwise multiply an array and an MVar with the matrix-friendly Python API?
Comments
0 comments
Article is closed for comments.