Calculate the determinant of a matrix that includes quadratic expressions.
AnsweredHi,
I'm calculating the determinant of a Gram matrix of a matrix variable using the code in the link below. However, the following error occurs. Is there a way to resolve this issue?
My code
def det(A):
v = m.addVar(lb=-float("inf"))
if A.shape == (2,2):
m.addConstr(v == A[0,0]*A[1,1]-A[1,0]*A[0,1]) # TODO
return v
expr = gp.QuadExpr()
cofactor = 1
for i in range(A.shape[1]):
cols = [c for c in range(A.shape[1]) if c != i]
expr += cofactor * A[0,i] * det(A[1:][:,cols]) # TODO
cofactor = -cofactor
m.addConstr(v == expr)
return v
Xe = m.addMVar((ne,me),lb=0, ub=1, vtype=GRB.CONTINUOUS)
aux5 = det(Xe @ Xe.T)
Error
Traceback (most recent call last):
File "/data/bhli/dspf-parser-0.3.0/gurobi2.py", line 116, in <module>
aux4 = det(Xv @ Xv.T)
File "/data/bhli/dspf-parser-0.3.0/gurobi2.py", line 22, in det
expr += cofactor * A[0,i] * det(A[1:][:,cols]) # TODO
File "/data/bhli/dspf-parser-0.3.0/gurobi2.py", line 22, in det
expr += cofactor * A[0,i] * det(A[1:][:,cols]) # TODO
File "/data/bhli/dspf-parser-0.3.0/gurobi2.py", line 22, in det
expr += cofactor * A[0,i] * det(A[1:][:,cols]) # TODO
[Previous line repeated 38 more times]
File "/data/bhli/dspf-parser-0.3.0/gurobi2.py", line 16, in det
m.addConstr(v == A[0,0]*A[1,1]-A[1,0]*A[0,1].item()) # TODO
TypeError: unsupported operand type(s) for *: 'MQuadExpr' and 'MQuadExpr'
0
-
Hi Bohao,
The code you linked is intended to be used with a matrix of variables (MVar) but you are passing it a matrix of quadratic expressions (MQuadExpr). The easiest solution here is to define a MVar for the gram matrix, e.g.
Xe = m.addMVar((ne,me),lb=0, ub=1, vtype=GRB.CONTINUOUS)
Xe_gram = m.addMVar((ne,ne),lb=0, ub=me, vtype=GRB.CONTINUOUS)
m.addConstr(Xe @ Xe.T == Xe_gram)
aux5 = det(Xe_gram)- Riley
0 -
Thank you very much for your help, Riley. Have a wonderful day!
0
Please sign in to leave a comment.
Comments
2 comments