Incorrect calculation of the sum of squares of the product of matrix and value(Cannot multiply with an MLinExpr from the left)
AnsweredHello, friends:
I recently encountered some problems in solving the optimal value of the objective function. I hope to get your help. My objective function is:
Where x is a 01 matrix that needs to be optimized, and the optimal x value is required to minimize the objective function.
B = np.array([0.3, 0.4, 0.3])
c=np.array([0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1])
N is calculated according to the normal distribution expression according to the sample points
My code is as follows, always reporting the error "Cannot multiply with an MLinExpr from the left":
from gurobipy import*
import numpy as np
X=np.array([4.83808086,3.9419967 ,6.23521488,4.9490249 ,0.30451898,0.59213485,1.23900585,0.3817953 ,1.14119574,0.32998153])
cov_=np.array([2.38607056,4.28441872])
m_=np.array([0.45005995,4.10724346])
B = np.array([0.3, 0.4, 0.3])
c=np.array([0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1])
n=10
N = []
for i in range(n):
N.append((1 / (np.sqrt(2 * math.pi) * cov_) * np.exp(
1 / (2 * cov_ ** 2) * (X[i]  m_) ** 2)))
print(N)
N=np.array(N)
N.reshape(10,2)
print(N)
model = Model()
x = model.addMVar((3,2), vtype=GRB.BINARY)
model.update()
obj_func= QuadExpr()
for i in range(10):
it=[]
for j in range(2):
it.append(N[i,j]*B@x[:,j])
obj_func+=(np.sum(it)c[i])@(np.sum(it)c[i])
model.setObjective(obj_func,sense=GRB.MINIMIZE)
model.addConstrs(np.sum(x[i, k] for k in range(2)) == 1 for i in range(3))
model.optimize()
a = model.getVars()

It's not currently possible to multiply two MLinExpr objects together like this. As a workaround, you can create auxiliary variable \( y \in \mathbb{R}^{10} \) such that \( y_i \) equals \( \texttt{np.sum(it)  c[i]} \), then set the objective function equal to \( y^\top y \):
y = model.addMVar(10, lb=GRB.INFINITY)
for i in range(10):
model.addConstr(y[i] == sum(N[i,j] * B @ x[:,j] for j in range(2))  c[i])
model.setObjective(y @ y, sense=GRB.MINIMIZE)For more information, see the article How do I multiply two MLinExpr objects together with the matrixfriendly Python API?.
Please sign in to leave a comment.
Comments
2 comments