CasADi:来自符号变量

时间:2019-05-07 05:13:22

标签: python optimization nonlinear-optimization

this问题有关(并交叉发布了here),我正在尝试为CasADi中的符号矩阵变量建立索引。我想使用向量变量x,并根据A的组成部分填充符号函数表达式的矩阵x。更具体地说,我希望做类似下面的(c)部分:

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))

但出现错误:

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]

我认为我错误地初始化了A,因为定义为向量变量xi的切片的xjx返回了{{1}的False }(尽管xi.is_symbolic()返回x.is_symbolic())。这是从符号变量的组件定义矩阵值函数的正确方法,还是我的操作方式给我带来True错误?

0 个答案:

没有答案