python,matlab,C++ 凸優化庫——anaconda spyder->cvxpy,matlab->cvx,C++->qpOASES
阿新 • • 發佈:2018-12-23
python:
使用spyder安裝所需庫,包時需要在控制檯輸入命令
!pip install xxxx
但是有可能源不太好,導致安裝失敗
因此最好去官網下載,然後將下載包放置到工作空間,使用!pip install xxx檔名
下面以cvxpy凸優化包為例
下載對應版本包
將包移至工作空間,使用在控制檯輸入命令!pip install cvxpy-1.0.10-cp36-cp36m-win_amd64.whl
ok
簡單示例:
import cvxpy as cvx #定義優化變數 x = cvx.Variable() y = cvx.Variable() # 定義約束條件 constraints = [x + y == 1, x - y >= 1] # 定義優化問題 obj = cvx.Minimize((x - y)**2) # 定義優化問題 prob = cvx.Problem(obj, constraints) #求解問題 prob.solve() #返回最優值 print("status:", prob.status)#求解狀態 print("optimal value", prob.value) #目標函式優化值 print("optimal var", x.value, y.value) #優化變數的值,相應變數加.value
matlab:
matlab凸優化工具箱下載處
m = 20; n = 10; p = 4;
A = randn(m,n); b = randn(m,1);
C = randn(p,n); d = randn(p,1); e = rand;
cvx_begin
variable x(n)
minimize( norm( A * x - b, 2 ) )
subject to
C * x == d
norm( x, Inf ) <= e
cvx_end
C++ :
qpOASES採用可行集策略,規模越大耗時越長
示例、
#include "include\qpOASES.hpp" int main() { USING_NAMESPACE_QPOASES /* Setup data of first QP. */ real_t H[2 * 2] = { 1.0, 0.0, 0.0, 0.5 }; real_t A[1 * 2] = { 1.0, 1.0 }; real_t g[2] = { 1.5, 1.0 }; real_t lb[2] = { 0.5, -2.0 }; real_t ub[2] = { 5.0, 2.0 }; real_t lbA[1] = { -1.0 }; real_t ubA[1] = { 2.0 }; /* Setup data of second QP. */ real_t g_new[2] = { 1.0, 1.5 }; real_t lb_new[2] = { 0.0, -1.0 }; real_t ub_new[2] = { 5.0, -0.5 }; real_t lbA_new[1] = { -2.0 }; real_t ubA_new[1] = { 1.0 }; /* Setting up QProblem object. */ QProblem example(2, 1); /* Solve first QP. */ int_t nWSR = 10; example.init(H, g, A, lb, ub, lbA, ubA, nWSR); /* Solve second QP. */ nWSR = 10; example.hotstart(g_new, lb_new, ub_new, lbA_new, ubA_new, nWSR); /* Get and print solution of second QP. */ real_t xOpt[2]; example.getPrimalSolution(xOpt); printf("\n xOpt = [ %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], example.getObjVal()); return 0; }
後續增加 :
由於python又方便可用的cvxpy包,是否可以用c/c++呼叫python的包cvxpy