python - 如何在 CVXPY 中指定非线性约束?
问题描述
我是 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_”对象没有属性“变量”
真的希望有人可以向我解释我做错了什么。
提前致谢...
克里斯
解决方案
推荐阅读
- python - Pandas 样式代码在 spyder 的 conda 环境中不起作用,包问题?
- chart.js - 对 Y 轴 + 图表 Js 上的时间单位进行排序
- python - 尝试关闭然后重新打开 Tkinter 'Frame' 小部件时出错
- c - 关于 scanf_s 如何检测 C 中的字符的问题
- laravel - 为什么 Laravel 助手在 5.8 版本中被弃用了?
- kotlin - 为什么 Kotlin/JS 对 === 的返回结果与 Kotlin/JVM 不同?
- docker - 在 docker 服务中,如何公开共享一个端口和私有共享一个端口?
- python - 在 pytest 中使用命令行选项进行非 python 测试
- r - 用 r 中每个月的阈值天数计算平均值
- python - 如何将文本从 txt 文件添加到 pdf python 文件