非线性求解器 Casadi (c++使用例子)

Casadi 是一款非线性求解器,支持多种语言,官方文档:casadi/docs

一. 安装

1. ipopt 安装

自己写个sh脚本安装一下

#!/usr/bin/env bash

# Fail on first error.
set -e

cd "$(dirname "${BASH_SOURCE[0]}")"

sudo apt-get install cppad gfortran 

wget https://www.coin-or.org/download/source/Ipopt/Ipopt-3.12.8.zip -O Ipopt-3.12.8.zip
unzip Ipopt-3.12.8.zip

# Step by step   
pushd Ipopt-3.12.8/ThirdParty/Blas
./get.Blas    
cd ../Lapack
./get.Lapack  
cd ../Mumps  
./get.Mumps  
cd ../Metis  
./get.Metis
cd ../ASL
./get.ASL

cd ..
cd ..

mkdir build  
cd build  
../configure  
make -j4  
make install  

cp -a include/* /usr/include/.  
cp -a lib/* /usr/lib/. 

popd

# Clean up.
cd ..
cd ..
apt-get clean && rm -rf /var/lib/apt/lists/*
rm -rf Ipopt-3.12.8.zip Ipopt-3.12.8

2. Casadi 安装

#!/usr/bin/env bash

# Fail on first error.
set -e

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo -e "\033[40;32m${DIR} \033[0m"

# download
wget https://github.com/casadi/casadi/releases/download/3.5.5/casadi-3.5.5-1.tar.gz
tar -zxvf casadi-3.5.5-1.tar.gz
echo -e "\033[40;32mdownload finish \033[0m"

cd casadi-3.5.5.1
mkdir build && cd build
cmake .. -DWITH_IPOPT=ON -DWITH_EXAMPLES=OFF
make -j4
sudo make install
sudo ldconfig

# Clean up.
sudo apt-get clean && sudo rm -rf /var/lib/apt/lists/*
sudo rm -fr casadi-3.5.5-1.tar.gz casadi-3.5.5.1

举两个c++的非线性求解的栗子吧,没怎么看到过

二. 例子

1. CmakeLists文件

cmake_minimum_required(VERSION 2.8.9)

project(casadi_test)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include_directories(
  # include
  ${catkin_INCLUDE_DIRS}
)

add_executable(${PROJECT_NAME}_node src/casadi_test.cpp )
target_link_libraries(${PROJECT_NAME}_node ${catkin_LIBRARIES} casadi) 

2. 例子1

#include<iostream>
#include<vector>
#include <casadi/casadi.hpp>

using namespace std;
using namespace casadi;

int main(int argc, char * argv[] ){

  cout << "casadi_test" << endl;

  // This is another way to define a nonlinear solver. Opti is new
  /*
   *    min  x1^2 + x2^2 + x3^2
   *    s.t.    6*x1 + 3&x2 + 2*x3 - p0 = 0
   *              p2*x1 + x2 - x3 - 1 = 0
   *              x1, x2, x3 >= 0
   */

  // Optimization variables
  SX x = SX::sym("x", 3);
  std::cout << "x:" << x << std::endl;

  // Parameters
  SX p = SX::sym("p", 2);
  std::cout << "p:" << p << std::endl;

  // Objective
  SX f = x(0) * x(0) + x(1) * x(1) + x(2) * x(2);
  std::cout << "f:" << f << std::endl;

  // Constraints
  SX g = vertcat(6 * x(0) + 3 * x(1) + 2 * x(2) - p(0), p(1) * x(0) + x(1) - x(2) - 1);
  std::cout << "g:" << g << std::endl;

  // Initial guess and bounds for the optimization variables
  vector<double> x0 = { 0.15, 0.15, 0.00 };
  vector<double> lbx = { 0.00, 0.00, 0.00 };
  vector<double> ubx = { inf, inf, inf };

  // Nonlinear bounds
  vector<double> lbg = { 0.00, 0.00 };
  vector<double> ubg = { 0.00, 0.00 };

  // Original parameter values
  vector<double> p0 = { 5.00, 1.00 };

  // NLP
  SXDict nlp = { { "x", x }, { "p", p }, { "f", f }, { "g", g } };

  // Create NLP solver and buffers
  Function solver = nlpsol("solver", "ipopt", nlp);
  std::map<std::string, DM> arg, res;

  // Solve the NLP
  arg["lbx"] = lbx;
  arg["ubx"] = ubx;
  arg["lbg"] = lbg;
  arg["ubg"] = ubg;
  arg["x0"] = x0;
  arg["p"] = p0;
  res = solver(arg);

  // Print the solution
  cout << "--------------------------------" << endl;
  cout << "Optimal solution for p = " << arg.at("p") << ":" << endl;
  cout << setw(30) << "Objective: " << res.at("f") << endl;
  cout << setw(30) << "Primal solution: " << res.at("x") << endl;
  cout << setw(30) << "Dual solution (x): " << res.at("lam_x") << endl;
  cout << setw(30) << "Dual solution (g): " << res.at("lam_g") << endl;

  return 0;
}

结果

djq@djq-UX410UQK:~/test/casadi_test/build$ ./casadi_test_node 
casadi_test
x:[x_0, x_1, x_2]
p:[p_0, p_1]
f:((sq(x_0)+sq(x_1))+sq(x_2))
g:[((((6*x_0)+(3*x_1))+(2*x_2))-p_0), ((((p_1*x_0)+x_1)-x_2)-1)]

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

This is Ipopt version 3.12.8, running with linear solver mumps.
NOTE: Other linear solvers might be more efficient (see Ipopt documentation).

Number of nonzeros in equality constraint Jacobian...:        6
Number of nonzeros in inequality constraint Jacobian.:        0
Number of nonzeros in Lagrangian Hessian.............:        3

Total number of variables............................:        3
                     variables with only lower bounds:        3
                variables with lower and upper bounds:        0
                     variables with only upper bounds:        0
Total number of equality constraints.................:        2
Total number of inequality constraints...............:        0
        inequality constraints with only lower bounds:        0
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0

iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
   0  4.5100000e-02 3.63e+00 4.11e-01  -1.0 0.00e+00    -  0.00e+00 0.00e+00   0
   1  5.8681488e-01 8.88e-16 1.95e+00  -1.0 3.91e-01    -  3.37e-01 1.00e+00h  1
   2  5.9327019e-01 8.88e-16 1.00e-06  -1.0 1.32e-02    -  1.00e+00 1.00e+00f  1
   3  5.6004673e-01 0.00e+00 4.92e-02  -2.5 8.93e-02    -  9.26e-01 1.00e+00f  1
   4  5.5264341e-01 1.11e-16 2.83e-08  -2.5 4.42e-02    -  1.00e+00 1.00e+00f  1
   5  5.5114453e-01 2.22e-16 1.50e-09  -3.8 2.36e-02    -  1.00e+00 1.00e+00f  1
   6  5.5102559e-01 8.88e-16 1.50e-09  -3.8 7.16e-03    -  1.00e+00 1.00e+00f  1
   7  5.5102042e-01 8.88e-16 1.84e-11  -5.7 1.77e-03    -  1.00e+00 1.00e+00f  1
   8  5.5102041e-01 8.88e-16 2.51e-14  -8.6 6.77e-05    -  1.00e+00 1.00e+00h  1
   9  5.5102041e-01 0.00e+00 9.06e-15  -9.0 9.29e-08    -  1.00e+00 1.00e+00h  1

Number of Iterations....: 9

                                   (scaled)                 (unscaled)
Objective...............:   5.5102040816326525e-01    5.5102040816326525e-01
Dual infeasibility......:   9.0609642761140061e-15    9.0609642761140061e-15
Constraint violation....:   0.0000000000000000e+00    0.0000000000000000e+00
Complementarity.........:   9.0911698984221084e-10    9.0911698984221084e-10
Overall NLP error.......:   9.0911698984221084e-10    9.0911698984221084e-10


Number of objective function evaluations             = 10
Number of objective gradient evaluations             = 10
Number of equality constraint evaluations            = 10
Number of inequality constraint evaluations          = 0
Number of equality constraint Jacobian evaluations   = 10
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations             = 9
Total CPU secs in IPOPT (w/o function evaluations)   =      0.011
Total CPU secs in NLP function evaluations           =      0.001

EXIT: Optimal Solution Found.
      solver  :   t_proc      (avg)   t_wall      (avg)    n_eval
       nlp_f  |  42.00us (  4.20us)  42.45us (  4.24us)        10
       nlp_g  |  96.00us (  9.60us)  88.33us (  8.83us)        10
    nlp_grad  |   9.00us (  9.00us)   8.45us (  8.45us)         1
  nlp_grad_f  |  84.00us (  7.64us)  79.88us (  7.26us)        11
  nlp_hess_l  |  52.00us (  5.78us)  48.97us (  5.44us)         9
   nlp_jac_g  |  61.00us (  5.55us)  64.10us (  5.83us)        11
       total  |  13.08ms ( 13.08ms)  13.08ms ( 13.08ms)         1
--------------------------------
Optimal solution for p = [5, 1]:
                   Objective: 0.55102
             Primal solution: [0.632653, 0.387755, 0.0204082]
           Dual solution (x): [-1.43695e-09, -2.3445e-09, -4.45467e-08]
           Dual solution (g): [-0.163265, -0.285714]

3. 例子2

#include<iostream>
#include<vector>
#include <casadi/casadi.hpp>

using namespace std;
using namespace casadi;

int main(int argc, char * argv[] ){

  cout << "casadi_test" << endl;

// This is another way to define a nonlinear solver. Opti is new
/*
  *    min  x1*x4*(x1 + x2 + x3) + x3
  *    s.t.    x1*x2*x3*x4 >=25
                  x1^2 + x2^2 + x3^2 + x4^2 = 40
                  1 <= x1, x2, x3, x4 <= 5
*/

  // Optimization variables
  SX x = SX::sym("x", 4);
  std::cout << "x:" << x << std::endl;

  // Objective
  SX f = x(0)*x(3)*(x(0) + x(1) + x(2)) + x(2);
  // SX f = x(0) * x(0)*x(3) + x(0)*x(1)*x(3) + x(0)*x(2)*x(3)+ x(2);
  std::cout << "f:" << f << std::endl;

  // Constraints
  // SX g = vertcat(6 * x(0) + 3 * x(1) + 2 * x(2) - p(0), p(1) * x(0) + x(1) - x(2) - 1);
  SX g = vertcat(x(0)*x(1)*x(2)*x(3), pow(x(0),2) + pow(x(1),2) + pow(x(2),2) + pow(x(3),2));
  std::cout << "g:" << g << std::endl;

  // Initial guess and bounds for the optimization variables
  vector<double> x0 = { 0.0, 0.0, 0.0, 0.0 };
  vector<double> lbx = { 1, 1, 1, 1 };
  vector<double> ubx = {5, 5, 5, 5 };

  // Nonlinear bounds
  vector<double> lbg = { 25, 40 };
  vector<double> ubg = { inf, 40 };

  // NLP
  SXDict nlp = { { "x", x }, { "f", f }, { "g", g } };

  // Create NLP solver and buffers
  Function solver = nlpsol("solver", "ipopt", nlp);
  std::map<std::string, DM> arg, res;

  // Solve the NLP
  arg["lbx"] = lbx;
  arg["ubx"] = ubx;
  arg["lbg"] = lbg;
  arg["ubg"] = ubg;
  arg["x0"] = x0;
  res = solver(arg);

  // Print the solution
  cout << "--------------------------------" << endl;
  // std::cout << res << std::endl;
  cout << "objective: " << res.at("f") << endl;
  cout << "solution: " << res.at("x") << endl;

  return 0;
}

结果:

djq@djq-UX410UQK:~/test/casadi_test/build$ ./casadi_test_node 
casadi_test
x:[x_0, x_1, x_2, x_3]
f:(((x_0*x_3)*((x_0+x_1)+x_2))+x_2)
g:[(((x_0*x_1)*x_2)*x_3), (((sq(x_0)+sq(x_1))+sq(x_2))+sq(x_3))]

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

This is Ipopt version 3.12.8, running with linear solver mumps.
NOTE: Other linear solvers might be more efficient (see Ipopt documentation).

Number of nonzeros in equality constraint Jacobian...:        4
Number of nonzeros in inequality constraint Jacobian.:        4
Number of nonzeros in Lagrangian Hessian.............:       10

Total number of variables............................:        4
                     variables with only lower bounds:        0
                variables with lower and upper bounds:        4
                     variables with only upper bounds:        0
Total number of equality constraints.................:        1
Total number of inequality constraints...............:        1
        inequality constraints with only lower bounds:        1
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0

iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
   0  4.1009029e+00 3.59e+01 1.54e+00  -1.0 0.00e+00    -  0.00e+00 0.00e+00   0
   1  6.3052937e+00 3.43e+01 2.33e+01  -1.0 5.89e+00    -  2.21e-03 4.20e-02h  1
   2  5.3929003e+00 3.42e+01 7.45e+02  -1.0 3.89e+00   2.0 6.10e-06 3.54e-03F  1
   3  6.6372159e+01 6.01e+00 2.27e+05  -1.0 3.78e+00   4.2 9.48e-04 4.80e-01h  2
   4  9.6419121e+01 4.30e-01 5.82e+04  -1.0 7.23e+01    -  1.59e-02 1.00e+00h  1
   5  9.4884972e+01 1.15e-03 3.12e+02  -1.0 1.47e+00    -  1.00e+00 1.00e+00h  1
   6  8.7460064e+01 8.24e-02 1.95e+01  -1.0 6.98e-01    -  1.00e+00 1.00e+00f  1
   7  8.9880566e+01 9.69e-03 3.14e+02  -1.0 7.37e-02   3.8 1.00e+00 1.00e+00h  1
   8  8.9330308e+01 3.71e-04 1.71e+01  -1.0 2.19e-01    -  1.00e+00 1.00e+00f  1
   9  8.9331900e+01 1.73e-06 4.10e+00  -1.0 2.16e-03   3.3 1.00e+00 1.00e+00h  1
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
  10  8.0133699e+01 1.20e-01 1.86e+01  -1.0 2.30e+00    -  1.00e+00 1.00e+00f  1
  11  8.2219265e+01 7.59e-03 3.27e+01  -1.0 6.41e-02   2.8 1.00e+00 1.00e+00h  1
  12  7.5619844e+01 5.78e-02 1.78e+01  -1.0 2.89e+00    -  1.00e+00 1.00e+00f  1
  13  7.6383207e+01 1.10e-03 4.23e+00  -1.0 2.53e-02   2.3 1.00e+00 1.00e+00h  1
  14  5.6773756e+01 5.44e-01 1.90e+01  -1.0 1.15e+01    -  1.00e+00 1.00e+00f  1
  15  6.0190720e+01 2.74e-02 5.29e+00  -1.0 1.24e-01   1.8 1.00e+00 1.00e+00h  1
  16  2.8936531e+01 1.69e+00 2.27e+01  -1.0 3.26e+01    -  1.00e+00 1.00e+00f  1
  17  3.1904315e+01 6.64e-02 1.11e+00  -1.0 1.93e-01   1.4 1.00e+00 1.00e+00h  1
  18  2.0735088e+01 3.84e-01 1.76e+00  -1.0 9.22e+01    -  1.00e+00 1.99e-01f  1
  19  1.7114152e+01 5.20e-01 8.02e+00  -1.0 4.71e+01    -  1.00e+00 1.30e-01f  1
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
  20  1.7278457e+01 3.55e-02 1.54e-02  -1.0 4.07e-01    -  1.00e+00 1.00e+00h  1
  21  1.7045230e+01 8.77e-03 6.88e-03  -1.7 4.41e-01    -  1.00e+00 1.00e+00h  1
  22  1.7017006e+01 2.40e-03 2.52e-03  -2.5 3.47e-02    -  1.00e+00 1.00e+00h  1
  23  1.7014119e+01 1.90e-04 1.03e-04  -3.8 6.30e-03    -  1.00e+00 1.00e+00h  1
  24  1.7014020e+01 2.57e-07 3.19e-07  -5.7 3.46e-04    -  1.00e+00 1.00e+00h  1
  25  1.7014017e+01 1.96e-11 2.80e-11  -8.6 3.31e-06    -  1.00e+00 1.00e+00h  1

Number of Iterations....: 25

                                   (scaled)                 (unscaled)
Objective...............:   1.7014017145174137e+01    1.7014017145174137e+01
Dual infeasibility......:   2.7976011905469220e-11    2.7976011905469220e-11
Constraint violation....:   1.9618084934336366e-11    1.9618084934336366e-11
Complementarity.........:   2.5297906848701540e-09    2.5297906848701540e-09
Overall NLP error.......:   2.5297906848701540e-09    2.5297906848701540e-09


Number of objective function evaluations             = 30
Number of objective gradient evaluations             = 26
Number of equality constraint evaluations            = 30
Number of inequality constraint evaluations          = 30
Number of equality constraint Jacobian evaluations   = 26
Number of inequality constraint Jacobian evaluations = 26
Number of Lagrangian Hessian evaluations             = 25
Total CPU secs in IPOPT (w/o function evaluations)   =      0.011
Total CPU secs in NLP function evaluations           =      0.001

EXIT: Optimal Solution Found.
      solver  :   t_proc      (avg)   t_wall      (avg)    n_eval
       nlp_f  |  89.00us (  2.97us)  87.07us (  2.90us)        30
       nlp_g  | 175.00us (  5.83us) 163.31us (  5.44us)        30
  nlp_grad_f  | 110.00us (  4.07us) 105.52us (  3.91us)        27
  nlp_hess_l  | 101.00us (  4.04us)  95.68us (  3.83us)        25
   nlp_jac_g  |  84.00us (  3.11us)  81.43us (  3.02us)        27
       total  |  21.84ms ( 21.84ms)  21.84ms ( 21.84ms)         1
--------------------------------
objective: 17.014
solution: [1, 4.743, 3.82115, 1.37941]

和用 CppAD 求解出来一样:ipopt CppAD 非线性规划

三. github:casadi_test

github:casadi_test

看到这里,点个赞吧!

  • 17
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值