我是CVXPY软件包的新手,正在尝试将使用具有非线性约束的fmincon(x)的传统Matlab优化代码移植到CVXPY。这样,我继续获得各种错误异常。当我使用cp.Variable()和cp.Parameter()的各种组合时。
因此,我对我做错的事情不知所措,因此我希望有人可以为我提供有关如何实现目标的建议。
最后,请注意,我没有设计或实现原始的Matlab代码,而是继承了代码库,并被要求将其转换为Python。下面是MATLAB代码和相应的CVXPY代码:
Matlab代码段:
% Third: define the nonlinear constraint function:
function [cin, ceq] = nonlcon(x)
cin = -1;
ceq = x'*H*x - sd.^2; % where H and sd are global.
end
...
[O(4:k+3, i), fval, O(k+4, i)] = ...
fmincon(@objfun, O(4:k+3, i-1), ABar, uBar, PHI, Nu, cBar, bBar, @nonlcon, options);
CVXPY代码段:
def nonlcon(x, H, sd):
# Algorithmic definition of the nonlinear constraint function
cin = -1.
ceq = (x.T @ H @ x) - sd**2 # where H and sd are global.
out_params = (cin, ceq)
return(out_params)
...
if callable(nonlcon):
if len(nonlcon_args) == 2:
(H, sd) = nonlcon_args
cin = lambda x: np.negative(nonlcon(x, H, sd)[0])
ceq = lambda x: nonlcon(x, H, sd)[1]
else:
cin = lambda x: np.negative(nonlcon(x)[0])
ceq = lambda x: nonlcon(x)[1]
...
if callable(nonlcon):
c_in = cp.Variable()
c_in.value = np.array(cin(x_hat))
c_eq = cp.Variable()
c_eq.value = np.array(ceq(x_hat))
constraints += [c_in <= 0,
c_eq == 0]
prob = cp.Problem(cp.Minimize(obj_f(x_hat)),
constraints)
最新的CVXPY错误消息:
TypeError:abs()的操作数类型错误:“ AddExpression”
指定非线性约束的各种实现组合的结果以及产生的错误消息:
观察到的CVXPY非线性约束误差:
使用实现:
c_in = cp.Parameter()
c_in.value = cin(x_hat)
c_eq = cp.Variable((1,))
c_eq.value = ceq(x_hat)
TypeError:不是常量值的有效类型。
使用实现:
c_in = cp.Variable((1,))
c_in.value = cin(x_hat)
c_eq = cp.Variable((1,))
c_eq.value = ceq(x_hat)
ValueError:变量值的尺寸()无效。
使用实现:
c_in = cp.Parameter()
c_in.value = cin(x_hat)
c_eq = cp.Parameter()
c_eq.value = ceq(x_hat)
TypeError:不是常量值的有效类型。
使用实现:
c_in = cp.Parameter()
c_in.value = cin(x_hat)
c_eq = cp.Variable()
c_eq.value = ceq(x_hat)
TypeError:不是常量值的有效类型。
使用实现:
c_in = cp.Variable()
c_in.value = cin(x_hat)
c_eq = cp.Variable()
c_eq.value = ceq(x_hat)
TypeError:不是常量值的有效类型。
使用实现:
c_in = cp.Variable()
c_in.value = np.array(cin(x_hat))
c_eq = cp.Variable()
c_eq.value = np.array(ceq(x_hat))
TypeError:abs()的操作数类型错误:“ AddExpression”
使用实现:
c_in = cp.Parameter()
c_in.value = cin(x_hat)
# c_eq = cp.Variable()
# c_eq.value = ceq(x_hat)
constraints += [c_in <= 0,
ceq(x_hat) == 0]
DCPError:问题不遵循DCP规则。特别: 以下约束不是DCP:
使用实现:
# c_in = cp.Parameter()
# c_in.value = cin(x_hat)
# c_eq = cp.Variable()
# c_eq.value = ceq(x_hat)
constraints += [cin(x_hat) <= 0,
ceq(x_hat) == 0]
AttributeError:'numpy.bool_'对象没有属性'variables'
真的希望有人可以向我解释我做错了什么。
预先感谢...
克里斯