LoginSignup
1
0

yaml-cppを使って実験パラメータの管理する

Posted at

C++でパラメータの管理をしたい!

卒論でC++を使ってる時、パラメータをヘッダファイルにマクロ定義して動かしていたが、値を変えるたびにコンパイルが必要で、プログラムが大きくなるとコンパイル時間も長くなり困ったので、パラメータをyamlで管理して、引数として渡すことにした。良さげなライブラリがないか探すとyaml-cppを見つけたので、始め方を記録として残す。

ディレクトリ構成

$ tree
.
|-- CMakeLists.txt
|-- build
|-- config
|   |-- conf_1.yaml
|   `-- conf_2.yaml
`-- src
    `-- main.cpp

$

CMakeLists.txtに以下を追加

READMEに従ってCMakeLists.txtを編集する。やってることはリポジトリをクローンしてリンクするようにするよってだけ。

CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(main)

set(CMAKE_CXX_STANDARD 11)

+include(FetchContent)

+FetchContent_Declare(
+  yaml-cpp
+  GIT_REPOSITORY https://github.com/jbeder/yaml-cpp.git
+  GIT_TAG yaml-cpp-0.7.0 # Can be a tag (yaml-cpp-x.x.x), a commit hash, or a branch name (master)
+)
+FetchContent_GetProperties(yaml-cpp)

+if(NOT yaml-cpp_POPULATED)
+  message(STATUS "Fetching yaml-cpp...")
+  FetchContent_Populate(yaml-cpp)
+  add_subdirectory(${yaml-cpp_SOURCE_DIR} ${yaml-cpp_BINARY_DIR})
+endif()

add_executable(main
    src/main.cpp
)

+target_link_libraries(main PUBLIC yaml-cpp::yaml-cpp) # The library or executable that require yaml-cpp library

使ってみる

想定するyamlファイル

以下のようなyamlファイルを読み込んで面積を計算する。

conf_1.yaml
size: 2000
range_x:
  min: -10.0
  max: 10.0
range_y:
  min: 100.0
  max: 200.0

プログラム本体

  • YAML::LoadFile : yamlファイルの読み込み
  • 値の取り出しはoperator[]からのasメソッドでできるみたい(STLにも対応している←嬉しい)
main.cpp
#include <iostream>
#include <vector>
#include <string>
#include <map>

#include "yaml-cpp/yaml.h"

using std::vector;
using std::string;
using std::map;
using std::cout;
using std::endl;

int main(int argc, char** argv)
{
    const auto conf_file = string(argv[1]);
    YAML::Node config = YAML::LoadFile(conf_file);

    // 値を取り出す
    const auto size = config["size"].as<int>();
    const auto range_x = config["range_x"].as<map<string, double>>();
    const auto min_y = config["range_y"]["min"].as<double>();
    const auto max_y = config["range_y"]["max"].as<double>();

    // coutで出力できる
    cout << config << endl;

    const auto width = range_x.at("max") - range_x.at("min");
    const auto height = max_y - min_y;
    const auto s = width * height;

    cout << "------" << endl;
    cout << "Area size: " << s << endl;

    return 0;
}
}

実行結果

$ cd build
$ cmake ..
$ make -j4
$ ./main ../config/conf_1.yaml
size: 2000
range_x:
  min: -10.0
  max: 10.0
range_y:
  min: 100.0
  max: 200.0
------
Area size: 2000
$

まとめ

他にもOpenCVやBoostにも入っているみたいなので、すでにそれらを使っている場合はそちらを使いましょう。今回、どちらも使っていない環境でしたのでyaml-cppを使ってみました。yaml-cppは簡単にはじめられて、使い方もシンプルなので、yamlでパラメータを管理したいけど、今使ってるライブラリには入ってないよ... って人は検討してみてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0