管理员 发布的文章

CMake教程一: 介绍、安装、基本使用


CMake 介绍

CMake 是一种跨平台的免费开源软件工具,用于使用与编译器无关的方法来管理软件的构建过程。
通过编写CMakeLists.txt,可以控制生成的Makefile,从而控制编译过程。CMake自动生成的Makefile不仅可以通过make命令构建项目生成目标文件,还支持安装(make install)、测试安装的程序是否能正确执行(make test,或者ctest)、生成当前平台的安装包(make package)、生成源码包(make package_source)、产生Dashboard显示数据并上传等高级功能,只要在CMakeLists.txt中简单配置,就可以完成很多复杂的功能,包括写测试用例。
如果有嵌套目录,子目录下可以有自己的CMakeLists.txt。
CMake是一个非常强大的编译自动配置工具,支持各种平台,KDE也是用它编译的,感兴趣的可以试用一下。

安装

下载地址:CMake官网下载页面

Windows

下载地址:cmake-3.22.0-rc3-windows-x86_64.msi

linux

下载地址:cmake-3.22.0-rc3-linux-x86_64.tar.gz

基本使用

Windows

运行GUI的cmake界面:

微信图片编辑_20211118220355.jpg

Linux

待添加


HDF5: C 用例(创建、写入操作)


介绍

官网很多用例测试,但是全英的优点费劲,这里就将示例总结一下,提高用例的可读性,希望能帮助大家快速上手HDF5.

相关函数及作用

函数名作用
H5Fcreate创建HDF5文件
H5Gcreate创建组

用例代码及说明

#include <iostream>
#include <string>
#include "H5Cpp.h"

#pragma execution_character_set("utf-8")

#define FILE            "h5ex_t_cmpd.h5"
#define DATASET         "DS1"
#define DIM0            10

using namespace std;

struct sensor_r{
    string  location1;
    string  location2;
    string  location3;
    string  location4;
    string  location5;
    string  location6;
    string  location7;
    int     serial_no;
    string  location;
    double  temperature;
    double  pressure;
};

typedef struct {
    char    *location1;
    char    *location2;
    char    *location3;
    char    *location4;
    char    *location5;
    char    *location6;
    char    *location7;
    int     serial_no;
    char    *location;
    double  temperature;
    double  pressure;
} sensor_t;                                 /* Compound type */

int
main (void)
{
    hid_t       file, filetype, memtype, strtype, space, dset;
                                            /* Handles */
    herr_t      status;
    hsize_t     dims[1] = {DIM0};
    int         ndims,
                i;

    sensor_r rdata[DIM0];
    for (int i = 0; i < DIM0; i++)
    {
        rdata[i].location1 = "test";
        rdata[i].location2 = "test中文";
        rdata[i].location3 = "test";
        rdata[i].location4 = "test";
        rdata[i].location5 = "test";
        rdata[i].location6 = "test";
        rdata[i].location7 = "test";
        rdata[i].serial_no = i;
        rdata[i].location = "test123中文";
        rdata[i].temperature = i;
        rdata[i].pressure = 2.0;
    }

    sensor_t * wdata = new sensor_t[DIM0];
    
    for (int i = 0; i < DIM0; i++)
    {
        wdata[i].location1 = (char*)rdata[i].location1.c_str();
        wdata[i].location2 = (char*)rdata[i].location2.c_str();
        wdata[i].location3 = (char*)rdata[i].location3.c_str();
        wdata[i].location4 = (char*)rdata[i].location4.c_str();
        wdata[i].location5 = (char*)rdata[i].location5.c_str();
        wdata[i].location6 = (char*)rdata[i].location6.c_str();
        wdata[i].location7 = (char*)rdata[i].location7.c_str();
        wdata[i].serial_no = i;
        wdata[i].location = (char*)rdata[i].location.c_str();
        wdata[i].temperature = i;
        wdata[i].pressure = 2.0;
        cout << wdata[i].location2 << endl;
    }
    

    /*
     * Create a new file using the default properties.
     */
    file = H5Fcreate (FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create variable-length string datatype.
     */
    strtype = H5Tcopy (H5T_C_S1);
    status = H5Tset_size (strtype, H5T_VARIABLE);

    /*
     * Create the compound datatype for memory.
     */
    memtype = H5Tcreate (H5T_COMPOUND, sizeof (sensor_t));
    status = H5Tinsert (memtype, "Location1", HOFFSET (sensor_t, location1),strtype);
    status = H5Tinsert (memtype, "Location2", HOFFSET (sensor_t, location2),strtype);
    status = H5Tinsert (memtype, "Location3", HOFFSET (sensor_t, location3),strtype);
    status = H5Tinsert (memtype, "Location4", HOFFSET (sensor_t, location4),strtype);
    status = H5Tinsert (memtype, "Location5", HOFFSET (sensor_t, location5),strtype);
    status = H5Tinsert (memtype, "Location6", HOFFSET (sensor_t, location6),strtype);
    status = H5Tinsert (memtype, "Location7", HOFFSET (sensor_t, location7),strtype);
    status = H5Tinsert (memtype, "Serial number",HOFFSET (sensor_t, serial_no), H5T_NATIVE_INT);
    status = H5Tinsert (memtype, "Location", HOFFSET (sensor_t, location),strtype);
    status = H5Tinsert (memtype, "Temperature (F)", HOFFSET (sensor_t, temperature), H5T_NATIVE_DOUBLE);
    status = H5Tinsert (memtype, "Pressure (inHg)", HOFFSET (sensor_t, pressure), H5T_NATIVE_DOUBLE);

    /*
     * Create dataspace.  Setting maximum size to NULL sets the maximum
     * size to be the current size.
     */
    space = H5Screate_simple (1, dims, NULL);

    /*
     * Create the dataset and write the compound data to it.
     */
    dset = H5Dcreate (file, DATASET, memtype, space, H5P_DEFAULT, H5P_DEFAULT,
                H5P_DEFAULT);
    status = H5Dwrite (dset, memtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, wdata);

    /*
     * Close and release resources.
     */
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Tclose (memtype);
    status = H5Fclose (file);

    return 0;
}

HDF5: 介绍


一、HDF5简介

HDF 是用于存储和分发科学数据的一种自我描述、多对象文件格式。HDF 是由美国国家超级计算应用中心(NCSA)创建的,以满足不同群体的科学家在不同工程项目领域之需要。HDF 可以表示出科学数据存储和分布的许多必要条件。HDF 被设计为:

  1. 自述性:对于一个HDF 文件里的每一个数据对象,有关于该数据的综合信息(元数据)。在没有任何外部信息的情况下,HDF 允许应用程序解释HDF文件的结构和内容。
  2. 通用性:许多数据类型都可以被嵌入在一个HDF文件里。例如,通过使用合适的HDF 数据结构,符号、数字和图形数据可以同时存储在一个HDF 文件里。
  3. 灵活性:HDF允许用户把相关的数据对象组合在一起,放到一个分层结构中,向数据对象添加描述和标签。它还允许用户把科学数据放到多个HDF 文件里。
  4. 扩展性:HDF极易容纳将来新增加的数据模式,容易与其他标准格式兼容。
    跨平台性:HDF 是一个与平台无关的文件格式。HDF 文件无需任何转换就可以在不同平台上使用。

1. HDF5的组织结构

  • File 文件。相当于根目录
  • Groups 组。类似于文件夹
  • Datasets 数据集。数据的集合
  • Dataspace 数据空间给出原始数据的秩 (Rank) 和维度 (dimension)
  • Datatype 数据类型
  • Properties 说明该 dataset 的分块储存以及压缩情况
  • Chunked: 待摸索
  • Chunked & Compressed: 待摸索
  • Attributes 为该 file/gourps/dataset 的其他自定义属性

hdf5_1.jpg
hdf5_2.jpg
hdf5_3.jpg

2. 相关网站

HDF5官网
HDF5 View 下载地址
HDF5 相关下载地址
官方文档地址

二、HDF5下载与安装

1. cmake形式引入

待完善

2. window下安装

下载官方安装包直接安装或下载下方压缩包(官网下载需要登录,内陆访问很慢)

hdf5-1.12.1-Std-win10_64-vs16.zip

3. linux下安装

待完善


C++: 利用eigen来做Matlab转C++代码


引入Eigen

#include <Eigen/Dense>
using namespace Eigen;

定义变量

矩阵

方式说明
Matrix<double, 2, 3> M;定义M为2行3列(2x3)矩阵
Matrix3d M; 或 Matrix<double, 3, 3> M;定义M为3行3列(3x3)矩阵
MatrixXi M; 或 Matrix<int, Dynamic, Dynamic> M;定义M为动态int矩阵
MatrixXf M;定义M为动态float矩阵
MatrixXd M;定义M为动态double矩阵

向量

方式说明
Vector3d V;定义M为3行向量(默认列)(3x1矩阵)
RowVector3d V;定义V为3列向量(一行)(1x3矩阵)

运算

运算符matlab表达方式Eigen表达方式说明
+C=A+BM3 = M1.array() + M2.array()矩阵相加
-C=A-BM3 = M1.array() - M2.array()矩阵相减
*C=A*BM3 = M1.array() * M2.array()矩阵相乘
/C=A/BM3 = M1.array() / M2.array()矩阵相除

特殊运算

向量左除: A = [2,4,6] B = [1,2,3] A\B = A.ldlt().solve(B)
向量右除:A = [2,4,6] B = [1,2,3] A/B = SUM(A.*B)/SUM(B^2) = 2

// A simple quickref for Eigen. Add anything that's missing.
// Main author: Keir Mierle

include <Eigen/Dense>

Matrix<double, 3, 3> A; // Fixed rows and cols. Same as Matrix3d.
Matrix<double, 3, Dynamic> B; // Fixed rows, dynamic cols.
Matrix<double, Dynamic, Dynamic> C; // Full dynamic. Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E; // Row major; default is column-major.
Matrix3f P, Q, R; // 3x3 float matrix.
Vector3f x, y, z; // 3x1 float matrix.
RowVector3f a, b, c; // 1x3 float matrix.
VectorXd v; // Dynamic column vector of doubles
double s;

// Basic usage
// Eigen // Matlab // comments
x.size() // length(x) // vector size
C.rows() // size(C,1) // number of rows
C.cols() // size(C,2) // number of columns
x(i) // x(i+1) // Matlab is 1-based
C(i,j) // C(i+1,j+1) //

A.resize(4, 4); // Runtime error if assertions are on.
B.resize(4, 9); // Runtime error if assertions are on.
A.resize(3, 3); // Ok; size didn't change.
B.resize(3, 9); // Ok; only dynamic cols changed.

A << 1, 2, 3, // Initialize A. The elements can also be

 4, 5, 6,     // matrices, which are stacked along cols
 7, 8, 9;     // and then the rows are stacked.

B << A, A, A; // B is three horizontally stacked A's.
A.fill(10); // Fill A with all 10's.

// Eigen // Matlab
MatrixXd::Identity(rows,cols) // eye(rows,cols)
C.setIdentity(rows,cols) // C = eye(rows,cols)
MatrixXd::Zero(rows,cols) // zeros(rows,cols)
C.setZero(rows,cols) // C = zeros(rows,cols)
MatrixXd::Ones(rows,cols) // ones(rows,cols)
C.setOnes(rows,cols) // C = ones(rows,cols)
MatrixXd::Random(rows,cols) // rand(rows,cols)*2-1 // MatrixXd::Random returns uniform random numbers in (-1, 1).
C.setRandom(rows,cols) // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high) // linspace(low,high,size)'
v.setLinSpaced(size,low,high) // v = linspace(low,high,size)'
VectorXi::LinSpaced(((hi-low)/step)+1, // low:step:hi

                low,low+step*(size-1))  //

// Matrix slicing and blocks. All expressions listed here are read/write.
// Templated size versions are faster. Note that Matlab is 1-based (a size N
// vector is x(1)...x(N)).
//
/ PLEASE HELP US IMPROVING THIS SECTION /
/ Eigen 3.4 supports a much improved API for sub-matrices, including, /
/ slicing and indexing from arrays: /
/ http://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html /
//
// Eigen // Matlab
x.head(n) // x(1:n)
x.head<n>() // x(1:n)
x.tail(n) // x(end - n + 1: end)
x.tail<n>() // x(end - n + 1: end)
x.segment(i, n) // x(i+1 : i+n)
x.segment<n>(i) // x(i+1 : i+n)
P.block(i, j, rows, cols) // P(i+1 : i+rows, j+1 : j+cols)
P.block<rows, cols>(i, j) // P(i+1 : i+rows, j+1 : j+cols)
P.row(i) // P(i+1, :)
P.col(j) // P(:, j+1)
P.leftCols<cols>() // P(:, 1:cols)
P.leftCols(cols) // P(:, 1:cols)
P.middleCols<cols>(j) // P(:, j+1:j+cols)
P.middleCols(j, cols) // P(:, j+1:j+cols)
P.rightCols<cols>() // P(:, end-cols+1:end)
P.rightCols(cols) // P(:, end-cols+1:end)
P.topRows<rows>() // P(1:rows, :)
P.topRows(rows) // P(1:rows, :)
P.middleRows<rows>(i) // P(i+1:i+rows, :)
P.middleRows(i, rows) // P(i+1:i+rows, :)
P.bottomRows<rows>() // P(end-rows+1:end, :)
P.bottomRows(rows) // P(end-rows+1:end, :)
P.topLeftCorner(rows, cols) // P(1:rows, 1:cols)
P.topRightCorner(rows, cols) // P(1:rows, end-cols+1:end)
P.bottomLeftCorner(rows, cols) // P(end-rows+1:end, 1:cols)
P.bottomRightCorner(rows, cols) // P(end-rows+1:end, end-cols+1:end)
P.topLeftCorner<rows,cols>() // P(1:rows, 1:cols)
P.topRightCorner<rows,cols>() // P(1:rows, end-cols+1:end)
P.bottomLeftCorner<rows,cols>() // P(end-rows+1:end, 1:cols)
P.bottomRightCorner<rows,cols>() // P(end-rows+1:end, end-cols+1:end)

// Of particular note is Eigen's swap function which is highly optimized.
// Eigen // Matlab
R.row(i) = P.col(j); // R(i, :) = P(:, j)
R.col(j1).swap(mat1.col(j2)); // R(:, [j1 j2]) = R(:, [j2, j1])

// Views, transpose, etc;
//
/ PLEASE HELP US IMPROVING THIS SECTION /
/ Eigen 3.4 supports a new API for reshaping: /
/ http://eigen.tuxfamily.org/dox-devel/group__TutorialReshape.html /
//
// Eigen // Matlab
R.adjoint() // R'
R.transpose() // R.' or conj(R') // Read-write
R.diagonal() // diag(R) // Read-write
x.asDiagonal() // diag(x)
R.transpose().colwise().reverse() // rot90(R) // Read-write
R.rowwise().reverse() // fliplr(R)
R.colwise().reverse() // flipud(R)
R.replicate(i,j) // repmat(P,i,j)

// All the same as Matlab, but matlab doesn't have *= style operators.
// Matrix-vector. Matrix-matrix. Matrix-scalar.
y = Mx; R = PQ; R = P*s;
a = bM; R = P - Q; R = sP;
a *= M; R = P + Q; R = P/s;

               R *= Q;          R  = s*P;
               R += Q;          R *= s;
               R -= Q;          R /= s;

// Vectorized operations on each element independently
// Eigen // Matlab
R = P.cwiseProduct(Q); // R = P .* Q
R = P.array() s.array(); // R = P . s
R = P.cwiseQuotient(Q); // R = P ./ Q
R = P.array() / Q.array(); // R = P ./ Q
R = P.array() + s.array(); // R = P + s
R = P.array() - s.array(); // R = P - s
R.array() += s; // R = R + s
R.array() -= s; // R = R - s
R.array() < Q.array(); // R < Q
R.array() <= Q.array(); // R <= Q
R.cwiseInverse(); // 1 ./ P
R.array().inverse(); // 1 ./ P
R.array().sin() // sin(P)
R.array().cos() // cos(P)
R.array().pow(s) // P .^ s
R.array().square() // P .^ 2
R.array().cube() // P .^ 3
R.cwiseSqrt() // sqrt(P)
R.array().sqrt() // sqrt(P)
R.array().exp() // exp(P)
R.array().log() // log(P)
R.cwiseMax(P) // max(R, P)
R.array().max(P.array()) // max(R, P)
R.cwiseMin(P) // min(R, P)
R.array().min(P.array()) // min(R, P)
R.cwiseAbs() // abs(P)
R.array().abs() // abs(P)
R.cwiseAbs2() // abs(P.^2)
R.array().abs2() // abs(P.^2)
(R.array() < s).select(P,Q ); // (R < s ? P : Q)
R = (Q.array()==0).select(P,R) // R(Q==0) = P(Q==0)
R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P) // with: scalar func(const scalar &x);

// Reductions.
int r, c;
// Eigen // Matlab
R.minCoeff() // min(R(:))
R.maxCoeff() // max(R(:))
s = R.minCoeff(&r, &c) // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);
s = R.maxCoeff(&r, &c) // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);
R.sum() // sum(R(:))
R.colwise().sum() // sum(R)
R.rowwise().sum() // sum(R, 2) or sum(R')'
R.prod() // prod(R(:))
R.colwise().prod() // prod(R)
R.rowwise().prod() // prod(R, 2) or prod(R')'
R.trace() // trace(R)
R.all() // all(R(:))
R.colwise().all() // all(R)
R.rowwise().all() // all(R, 2)
R.any() // any(R(:))
R.colwise().any() // any(R)
R.rowwise().any() // any(R, 2)

// Dot products, norms, etc.
// Eigen // Matlab
x.norm() // norm(x). Note that norm(R) doesn't work in Eigen.
x.squaredNorm() // dot(x, x) Note the equivalence is not true for complex
x.dot(y) // dot(x, y)
x.cross(y) // cross(x, y) Requires #include <Eigen/Geometry>

//// Type conversion
// Eigen // Matlab
A.cast<double>(); // double(A)
A.cast<float>(); // single(A)
A.cast<int>(); // int32(A)
A.real(); // real(A)
A.imag(); // imag(A)
// if the original type equals destination type, no work is done

// Note that for most operations Eigen requires all operands to have the same type:
MatrixXf F = MatrixXf::Zero(3,3);
A += F; // illegal in Eigen. In Matlab A = A+F is allowed
A += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)

// Eigen can map existing memory into Eigen matrices.
float array[3];
Vector3f::Map(array).fill(10); // create a temporary Map over array and sets entries to 10
int data[4] = {1, 2, 3, 4};
Matrix2i mat2x2(data); // copies data into mat2x2
Matrix2i::Map(data) = 2mat2x2; // overwrite elements of data with 2mat2x2
MatrixXi::Map(data, 2, 2) += mat2x2; // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)

// Solve Ax = b. Result stored in x. Matlab: x = A b.
x = A.ldlt().solve(b)); // A sym. p.s.d. #include <Eigen/Cholesky>
x = A.llt() .solve(b)); // A sym. p.d. #include <Eigen/Cholesky>
x = A.lu() .solve(b)); // Stable and fast. #include <Eigen/LU>
x = A.qr() .solve(b)); // No pivoting. #include <Eigen/QR>
x = A.svd() .solve(b)); // Stable, slowest. #include <Eigen/SVD>
// .ldlt() -> .matrixL() and .matrixD()
// .llt() -> .matrixL()
// .lu() -> .matrixL() and .matrixU()
// .qr() -> .matrixQ() and .matrixR()
// .svd() -> .matrixU(), .singularValues(), and .matrixV()

// Eigenvalue problems
// Eigen // Matlab
A.eigenvalues(); // eig(A);
EigenSolver<Matrix3d> eig(A); // [vec val] = eig(A)
eig.eigenvalues(); // diag(val)
eig.eigenvectors(); // vec
// For self-adjoint matrices use SelfAdjointEigenSolver<>