Doing element wise multiplication for MVar in Python (for a Quadratic program)
AnsweredI want to be able to do an elementwise multiplication in the constraint (bolded) for a quadratic program as follows:
The (y*y) is throwing an error. How do I get that elementwise multiplication to work?
import gurobipy as gp
m = gp.model("model")
x = m.addMVar(shape=(10), name="x")
y = m.addMVar(shape=(5), name="y")
A = np.random.rand(5, 10)
m.addConstr(A @ x  (y*y) <= A[:,0], name="const")
m.setObjective(x.sum()  (y*y).sum()), GRB.MAXIMIZE)
0

The syntax you are using is very reasonable, but unfortunately the expression y*y, which I would interpret as a quadratic expression of shape (5,), is not yet supported by gurobipy (all quadratic expressions must evaluate to a scalar). Extending this initial step towards a matrix friendly API taken in version 9.0 to include more general expressions is on the roadmap.
For now you can resort to the scalar level in your example, i.e.,
import gurobipy as gp
import numpy as np
m = gp.Model("model")
x = m.addMVar(shape=(10), name="x")
y = m.addMVar(shape=(5), name="y")
A = np.random.rand(5, 10)
m.addConstrs((A[i,:] @ x  (y[i]@y[i]) <= A[i,0] for i in range(5)),
name="const")
m.setObjective(x.sum()  y @ y, gp.GRB.MAXIMIZE)It's a bit more cumbersome but it should work.
1
Please sign in to leave a comment.
Comments
1 comment