问题
Somewhat related to this question (and cross-posted here), I'm trying to index a symbolic matrix variable in CasADi. I want to take a vector variable x and populate a matrix A of symbolic function expressions based on the components of x. More specifically, I hope to do something like part (c) below:
from casadi import *
opti = Opti()
n = 3
B = np.random.normal(size=[n, n])
D = np.random.normal(size=[n, n])
D = np.dot(D.T, D)
##(a) variables and expressions
x = opti.variable(n); opti.set_initial(x, x0)
A = opti.variable(n, n) # or would A = MX(n, n) be better?
##(b) objective
opti.minimize(sum(x[i]**2 for i in range(n))) # generic objective
##(c) populate symbolic matrix constraint
yi = MX.sym('yi')
yj = MX.sym('yj')
f_Aij = Function('f_Aij', [yi, yj], [(yi+yj)**2], ['yi', 'yj'], ['Aij'])
for i in range(n):
for j in range(n):
xi = x[i]
xj = x[j]
A[i,j] = f_Aij(xi, xj)
##(d) matrix inverse constraint
opti.subject_to(diag(solve(A,B) @ D @ solve(A, B).T) <= bounds)
##(e) solve
opti.solver('ipopt')
sol = opti.solve()
print(sol.value(x))
but am getting an error:
CasADi - 2019-05-06 23:49:39 WARNING("solver:nlp_jac_g failed: NaN detected for output jac_g_x, at nonzero index 0 (row 0, col 0).") [.../casadi/core/oracle_function.cpp:249]
CasADi - 2019-05-06 23:49:39 WARNING("solver:nlp_g failed: NaN detected for output g, at (row 0, col 0).") [.../casadi/core/oracle_function.cpp:249]
I believe I'm initializing A incorrectly because xi and xj defined as slices of the vector variable x return False for xi.is_symbolic() (though x.is_symbolic() returns True). Is this the proper way to define a matrix-valued function from the components of a symbolic variable, or is the way I'm doing it giving me the NaN error?
来源:https://stackoverflow.com/questions/56015912/casadi-matrix-function-from-symbolic-variable