Doing element wise multiplication for MVar in Python (for a Quadratic program)
AnsweredI want to be able to do an element-wise multiplication in the constraint (bolded) for a quadratic program as follows:
The (y*y) is throwing an error. How do I get that element-wise 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
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
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 -
Hi Himank,
Gurobi 10.0 was recently released. Included in this release is an improved Python Matrix API which allows to perform pointwise multiplication of two MVar variables.
Your original code snippet runs fine with Gurobi 10.0.Checkout the Matrix-friendly Modeling with Gurobipy webinar if you would like to learn more about this new functionality.
Please continue submitting new community posts for any bugs you might encounter in the future or for any comments/questions you might have. Users like you help to make Gurobi better!Best regards,Maliheh0
Post is closed for comments.
Comments
3 comments