If you are using Gurobi 10 or later
You can pointwise multiply a 1-D ndarray with a 1-D MVar of length one natively. This operation follows numpy's broadcasting rules. For example, the following expression:
$$\begin{align} \begin{bmatrix} y_1 \\ y_2 \\ y_3 \end{bmatrix} &= \begin{bmatrix} 1 \\ 1 \\ 1 \end{bmatrix} x \end{align}$$
can be constructed using the multiplication operator:
import gurobipy as gp
import numpy as np
m = gp.Model()
x = m.addMVar(1)
y = m.addMVar(3)
m.addConstr(y == np.ones(3) * x)
If you are using Gurobi 9.x
In Gurobi 9.x, it was not possible to pointwise multiply a 1-D ndarray with a 1-D MVar of length one. The above code results in TypeError: only size-1 arrays can be converted to Python scalars. Instead, this operation can be recast as a matrix-vector product:
import gurobipy as gp
import numpy as np
m = gp.Model()
x = m.addMVar(1)
y = m.addMVar(3)
m.addConstr(y == np.ones((3, 1)) @ x)
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 multiply two MLinExpr objects together 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.