Incompatible Dimensions?
AnsweredI'm using Gurobi 9.1.2 in Python. The program below yields the message "Incompatible Dimensions". This looks like a bug to me. How do I add things with scalar variables to results from vector variables?
import gurobipy as gp
import numpy as np
model = gp.Model()
xvars = model.addMVar((10, 10), vtype = gp.GRB.CONTINUOUS, name = 'x')
yvar = model.addVar(vtype = gp.GRB.CONTINUOUS, name = 'y')
coeff = np.arange(1, 11)
first = coeff @ xvars[: , -1]
print(first.shape)
lin = first + yvar
-
Operations between an object from the matrix-friendly interface (MVar, MLinExpr, MQuadExpr) and an object from the term-based modeling interface (Var, LinExpr, QuadExpr) are largely unsupported. In your example, \( \texttt{first} \) is an MLinExpr object and \( \texttt{yvar} \) is a Var object.
One way to resolve the issue is to define \( \texttt{yvar} \) as an MVar by adding it to the model with Model.addMVar():
yvar = model.addMVar(shape=(1,), name='y')
Note that you can use MVar() to create an MVar object from a list of Var objects, and MVar.tolist() to create a list of Var objects from an MVar object. These conversions can be useful in situations like yours. For example, an alternative solution is as follows:
lin = first + gp.MVar(yvar)
0 -
Eli, Thanks for the answer. As a related question, is there a convenient way to sum MVars along an axis (as in numpy)?
0 -
Unfortunately, there isn't currently a built-in way to sum an MVar along an axis. As a workaround, you could create a numpy array of Var objects by leveraging the MVar.tolist() method, then sum along an axis with ndarray.sum():
>>> x = model.addMVar(shape=(3,3), name='x')
>>> model.update()
>>> xarr = np.array(x.tolist())
>>> xarr.sum(axis=1)
array([<gurobi.LinExpr: x[0] + x[1] + x[2]>,
<gurobi.LinExpr: x[3] + x[4] + x[5]>,
<gurobi.LinExpr: x[6] + x[7] + x[8]>], dtype=object)0
Please sign in to leave a comment.
Comments
3 comments