Windows下Armadillo配置及测试

Armadillo是一个开源高性能C++线性代数库,提供了和Matlab中常用命令接近的函数接口,可以方便地将Matlab/Octave开发的算法移植到C++中。特别地,我们可以先在Matlab环境中编程进行算法原型验证,待算法充分验证通过之后再利用Armadillo移植到C++中编译为独立的可执行程序。虽然Matlab也支持利用mcc直接将m文件编译生成动态链接库文件或者可执行程序,但是这些代码的运行需要Matlab运行环境(MCR)的支持;而通过Armadillo进行移植则可以完全脱离Matlab环境。
此外,Armadillo是一个利用C++模板技术构建的算法库,只需要在代码中包含Armadillo的头文件就可以使用,不需要连接额外的函数库。同时,Armadillo可以选择采用高效的本地lapackblas库(例如MKL, ACML或者OpenBLAS)对底层线性代数运算进行加速,从而提升运算性能。

首先从Armadillo官网获取源码,本文测试使用的是armadillo-6.600.5.tar.xz。前面提到,如果不需要创建wrapper库文件,则直接将解压后将文件夹下面的include文件夹复制到安装位置即可完成Armadillo的安装。下面我们先来介绍一下Armadillo的配置和使用,最后我会对创建Armadillo的wrapper库文件的方法进行讨论。

我们直接以解压路径下example目录中的example1.cpp为例进行说明。

#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

// Armadillo documentation is available at:
// http://arma.sourceforge.net/docs.html

int main(int argc, char** argv)
{
    cout << "Armadillo version: " << arma_version::as_string() << endl;

    mat A(2,3);  // directly specify the matrix size (elements are uninitialised)

    cout << "A.n_rows: " << A.n_rows << endl;  // .n_rows and .n_cols are read only
    cout << "A.n_cols: " << A.n_cols << endl;

    A(1,2) = 456.0;  // directly access an element (indexing starts at 0)
    A.print("A:");

    A = 5.0;         // scalars are treated as a 1x1 matrix
    A.print("A:");

    A.set_size(4,5); // change the size (data is not preserved)

    A.fill(5.0);     // set all elements to a particular value
    A.print("A:");

    // endr indicates "end of row"
    A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr
      << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr
      << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr
      << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr
      << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr;

    A.print("A:");

    // determinant
    cout << "det(A): " << det(A) << endl;

    // inverse
    cout << "inv(A): " << endl << inv(A) << endl;

    // save matrix as a text file
    A.save("A.txt", raw_ascii);

    // load from file
    mat B;
    B.load("A.txt");

    // submatrices
    cout << "B( span(0,2), span(3,4) ):" << endl << B( span(0,2), span(3,4) ) << endl;

    cout << "B( 0,3, size(3,2) ):" << endl << B( 0,3, size(3,2) ) << endl;

    cout << "B.row(0): " << endl << B.row(0) << endl;

    cout << "B.col(1): " << endl << B.col(1) << endl;

    // transpose
    cout << "B.t(): " << endl << B.t() << endl;

    // maximum from each column (traverse along rows)
    cout << "max(B): " << endl << max(B) << endl;

    // maximum from each row (traverse along columns)
    cout << "max(B,1): " << endl << max(B,1) << endl;

    // maximum value in B
    cout << "max(max(B)) = " << max(max(B)) << endl;

    // sum of each column (traverse along rows)
    cout << "sum(B): " << endl << sum(B) << endl;

    // sum of each row (traverse along columns)
    cout << "sum(B,1) =" << endl << sum(B,1) << endl;

    // sum of all elements
    cout << "accu(B): " << accu(B) << endl;

    // trace = sum along diagonal
    cout << "trace(B): " << trace(B) << endl;

    // generate the identity matrix
    mat C = eye<mat>(4,4);

    // random matrix with values uniformly distributed in the [0,1] interval
    mat D = randu<mat>(4,4);
    D.print("D:");

    // row vectors are treated like a matrix with one row
    rowvec r;
    r << 0.59119 << 0.77321 << 0.60275 << 0.35887 << 0.51683;
    r.print("r:");

    // column vectors are treated like a matrix with one column
    vec q;
    q << 0.14333 << 0.59478 << 0.14481 << 0.58558 << 0.60809;
    q.print("q:");

    // convert matrix to vector; data in matrices is stored column-by-column
    vec v = vectorise(A);
    v.print("v:");

    // dot or inner product
    cout << "as_scalar(r*q): " << as_scalar(r*q) << endl;

    // outer product
    cout << "q*r: " << endl << q*r << endl;

    // multiply-and-accumulate operation (no temporary matrices are created)
    cout << "accu(A % B) = " << accu(A % B) << endl;

    // example of a compound operation
    B += 2.0 * A.t();
    B.print("B:");

    // imat specifies an integer matrix
    imat AA;
    imat BB;

    AA << 1 << 2 << 3 << endr << 4 << 5 << 6 << endr << 7 << 8 << 9;
    BB << 3 << 2 << 1 << endr << 6 << 5 << 4 << endr << 9 << 8 << 7;

    // comparison of matrices (element-wise); output of a relational operator is a umat
    umat ZZ = (AA >= BB);
    ZZ.print("ZZ:");

    // cubes ("3D matrices")
    cube Q( B.n_rows, B.n_cols, 2 );

    Q.slice(0) = B;
    Q.slice(1) = 2.0 * B;

    Q.print("Q:");

    // 2D field of matrices; 3D fields are also supported
    field<mat> F(4,3);

    for(uword col=0; col < F.n_cols; ++col)
        for(uword row=0; row < F.n_rows; ++row) {
            F(row,col) = randu<mat>(2,3);  // each element in field<mat> is a matrix
        }

    F.print("F:");

    return 0;
}

从上面的代码可以看出,Armadillo的使用很简单:首先引入Armadillo的头文件armadillo,然后导入Armadillo的命名空间arma,之后即可使用Armadillo提供的函数接口了。
现在唯一需要做的就是在编译器中指定Armadillo的Include路径,从而让编译器能够找到Armadillo的头文件。以mingw为例,我们只需在构建命令中增加-I<path_to_arma_include_base>选项,path_to_arma_include_base即Armadillo安装路径ARMAROOT下面的include文件夹,该路径下应该有一个名称为armadillo的C++头文件和一个名称为armadillo_bits文件夹。

ls -l ${ARMAROOT}/include
g++ -g -I${ARMAROOT}/include example1.cpp -o armademo.exe

接下来,我们需要配置Armadillo是否使用本地lapackblas库进行加速。打开ARMAROOT/armadillo_bits/config.hpp文件,找到以下两个宏:

  • ARMA_USE_LAPACK
  • ARMA_USE_BLAS

若不使用本地lapack库或者blas库,只需要将#define ARMA_USE_LAPACK语句注释掉,或者在#define ARMA_USE_LAPACK之后加上#undef ARMA_USE_LAPACK使其失效;针对blas的配置方法类似。相反,若要使用本地lapack库或者blas库,则需要确保这两个宏被定义,同时在连接时需要指定本地lapack库或blas库的路径并进行连接。

但是,这种方法每次配置Armadillo时都要打开config.hpp重新进行操作,比较繁琐。有没有一种更加方便的配置方法呢?答案是肯定的。
首先,将config.hpp中的ARMA_USE_LAPACKARMA_USE_BLAS宏定义语句注释掉或者利用#undef取消这两个宏定义。既然配置是否使用lapack或者blas的关键是配置这两个宏,那么我们可以
采用以下两种处理方法:

第一种方法,在源码中#include <armadillo>语句下面添加:

#ifndef ARMA_USE_LAPACK
#define ARMA_USE_LAPACK
#endif
#ifdef ARMA_USE_BLAS
#undef ARMA_USE_BLAS
#endif

以上方法仍然略显麻烦。另一种更简单的办法是在构建命令中动态添加宏定义,如下所示:

g++ -g -I${ARMAROOT} example1.cpp -o armademo.exe -DARMA_USE_LAPACK -UARMA_USE_BLAS

注意:以上命令只是用作示意,使用以上命令并不能成功构建armademo.exe

至此,我们完成了Armadillo的安装和配置。最后一步,我们来构建armademo。要成功构建上面的代码,需要要配置使用本地lapack库和blas库,因为代码中矩阵求行列式det和矩阵求逆inv两个函数调用依赖于本地lapack库和blas库的支持。这里我们的本地线性代数库选用openblas,则对应的构建命令为:

g++ -g -I${ARMAROOT} -L${OPENBLASROOT}/lib example1.cpp -o armademo.exe -DARMA_USE_LAPACK -DARMA_USE_BLAS -lopenblas

此时即可成功生成armademo.exe。将openblas.dll所在路径加入PATH环境变量中或者复制到armademo.exe所在目录,运行armademo.exe,程序就可以正常运行了。
如果注释掉源代码中调用detinv的代码,则此时可以不使用本地线性代数库,对应的构建命令为:

g++ -g -I${ARMAROOT} example1.cpp -o armademo.exe

最后再说一下如何创建Armadillo的wrapper库文件。该库文件名称一般为armadillo.dll(VS)或者libarmadillo.dll(mingw),封装了对底层lapack库和blas库的调用,以后需要使用本地库进行加速时只需要在连接选项中连接此armadillo库即可。

首先将源码包解压到用户的工作路径,参照README.txt说明进行构建。由于需要使用CMake进行build,故首先需要安装CMake,要求版本2.8或者以上。

这里使用mingw构建Armadillo库,根据文档指示,要求使用版本4.7.2以上的编译器,否则编译时会报错。

在Armadillo解压文件夹下新建build文件夹,在CMake GUI中进行配置。source路径选择Armadillo解压文件夹,build路径选择该文件夹下面新建的build。点击”Configure”进行配置,选择Makefile类型为”Mingw Makefile”,并选择”Specify native compilers”,单击”next”。分别设置gcc/g++/gfortran所在的路径,单击”Finish”退出即可。需要注意版本必须高于4.7.2,否则构建过程中会出错。单击”Configure”右边的”Generate”按钮即可在build文件夹下生成Makefile文件,之后cd到build文件夹下分别执行makemake install即可。

对应的构建命令为:

g++ -g -I${ARMAROOT}/inlucde -L-I${ARMAROOT}/lib example1.cpp -o armademo.exe -DARMA_USE_LAPACK \\
    -DARMA_USE_BLAS -DARMA_USE_WRAPPER -larmadillo

但我在实际测试时发现不能正常build,经常会报undefined reference to 'wrapper_dgetri_'之类的错误,这说明本地线性代数库没有完全配置好,导致有些符号在连接时找不到。这很可能是在创建wrapper时配置不正确造成的,因为在创建wrapper之前必须确保本机已经安装了本地lapackblas库并正确配置。这有一定的难度,构建成功的可能性也会小很多。所以建议不要使用wrapper,而是在需要使用本地库进行加速时直接连接相应的本地库。例如

CXXFLAGS = -I${ARMAROOT}/include -L${ARMAROOT}/lib -L${OPENBLASROOT}
g++ ${CXXFLAGS} example1.cpp -o example.exe -lopenblas

这样就能正常构建了,不会有找不到符号的问题。

所以,我的建议是不要使用wrapper,在config.hpp#define ARMA_USE_WRAPPER语句注释掉,只有在需要使用本地库加速时再连接本地库。

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
对于 Armadillo 的 VSCode 配置,你可以按照以下步骤进行设置: 1. 打开 VSCode,并在扩展商店中搜索并安装 "C/C++" 扩展。 2. 在项目文件夹中创建一个名为 ".vscode" 的文件夹(如果没有),然后在该文件夹中创建一个名为 "c_cpp_properties.json" 的文件。 3. 在 "c_cpp_properties.json" 文件中,添加以下内容: ```json { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include", "/usr/local/include", "/path/to/armadillo/include" // 替换为你的 Armadillo 头文件路径 ], "defines": [], "compilerPath": "/usr/bin/gcc", // 替换为你的 GCC 编译器路径 "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "linux-gcc-x64" } ], "version": 4 } ``` 请确保将 `/path/to/armadillo/include` 替换为你实际的 Armadillo 头文件路径。 4. 接下来,你可以创建一个名为 "tasks.json" 的文件,用于设置构建任务。在 ".vscode" 文件夹中创建该文件,并添加以下内容: ```json { "version": "2.0.0", "tasks": [ { "label": "Build", "type": "shell", "command": "/usr/bin/g++", // 替换为你的 g++ 编译器路径 "args": [ "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "group": { "kind": "build", "isDefault": true } } ] } ``` 请确保将 `/usr/bin/g++` 替换为你实际的 g++ 编译器路径。 5. 然后,你可以在 VSCode 的菜单栏中选择 "Terminal" -> "Run Build Task",或使用快捷键 Ctrl+Shift+B 来构建你的 Armadillo 项目。 这样就完成了 Armadillo 的 VSCode 配置。你可以根据自己的需要进行进一步的设置和调整。希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值