# Artefacts ツールキットの設定ヘルパー

Site [llms.txt](/ja/llms.txt)

---

Artefacts ツールキットの設定ヘルパーは、 `artefacts.yaml` Artefacts ツールキットの設定ヘルパーは、

インポート方法：
```python
from artefacts_toolkit.config import get_artefacts_param
```

## 関数
* [`get_artefacts_param`](#get_artefacts_param)
* [`get_artefacts_params`](#get_artefacts_params)
* [`merge_ros_params_files`](#merge_ros_params_files)

## 関数リファレンス

### `get_artefacts_param`

`artefacts.yaml` ファイルで設定されたパラメータを返します。 `param_type` が `launch`に設定されている場合、ROS の起動引数として使用できるように  `string` 型で返されます。

この関数はパラメトリックテストに特に役立ちます。 `artefacts.yaml` ファイルでパラメータ値のリストを定義すると（例：`launch/world: ["empty.sdf", "bookstore.sdf", "restaurant.sdf"]`)、 `artefacts run` コマンドはリスト内の各値に対して1回ずつ、テストを複数回実行します。各テスト実行中、 `get_artefacts_param("launch", "world")` は自動的にその特定のテスト実行に対する現在のパラメータ値を返します。

これはグリッドベースのテストに特に強力です！それぞれ3つの可能な値を持つ3つのパラメータがある場合、Artefacts は自動的にテストを27回（3 × 3 × 3）実行しますが、起動ファイルのコードは変更されません。

```python
get_artefacts_param(
    param_type,
    param_name,
    default=None,
    is_ros=True
)
```

#### パラメータ

| **パラメータ** | **型** | **説明**                                                            | **デフォルト** |
| ------------- | -------- | -------------------------------------------------------------------------- | ----------- |
| `param_type`  | `str`    | パラメータの名前空間/カテゴリ（例：「launch/world」の「launch」） | 必須    |
| `param_name`  | `str`    | T特定のパラメータ名（例：「launch/world」の「world」）              | 必須    |
| `default`     | `any`    | artefacts.yamlでパラメータが見つからない場合に返す値            | `None`      |
| `is_ros`      | `bool`   |パラメータをROS パラメータ形式に変換するかどうか        | `True`      |

#### 戻り値

この関数は次の動作でパラメータ値を返します：

- `param_type` が `"launch"` で `is_ros` が `True`の場合: `artefacts.yaml` ファイルの元の型に関係なく、値を  `str`として返します。これはROS起動引数として使用できるようにするためです。
- `default` が`None` 以外に設定されている場合、artefacts が要求されたパラメータを見つけられない場合に値が返されます。これは（例えば） `artefacts run` の代わりに `launch_test` を使用しているがコード変更を行いたくない場合に便利です。また、 `KeyError` 例外を防ぎます。
- その他のすべての場合：YAMLファイルの元の型（例： `list`、 `dict`、 `int`、 `float`、 `str`など)で値を返します。

> [!NOTE]
> * 現在はROS パラメータ / ROS起動引数のみをサポートしています。
> * パラメトリックテストは、artefactsをローカルで実行する場合、順次実行されます。プラットフォーム上で実行する場合、並行して実行されます（同時実行テストの最大数はサブスクリプションプランによって決まります）。

#### 例

以下の設定が設定された `artefacts.yaml` ファイルがある場合：

```yaml
scenarios:
  defaults:
    output_dirs: ["output"]
    metrics:
        - /odometry_error
    params:
      launch/world: ["bookstore.sdf", "empty.sdf"]
```

テスト起動ファイルでパラメータを次のように取得します：

```python
def generate_test_description():
    try:
        world = get_artefacts_param("launch", "world")
    except FileNotFoundError:
        world = "empty.world"

    run_headless = LaunchConfiguration("run_headless")
    launch_navigation_stack = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            [
                os.path.join(
                    get_package_share_directory("sam_bot_nav2_gz"),
                    "launch",
                    "complete_navigation.launch.py"
                ),
            ]
        ),
        launch_arguments=[("run_headless", run_headless), ("world_file", world)],
    )

...# Rest of launch test file   
```

---

これにより、同じテストが2回実行されます - 1回は空のワールドで、1回は書店のワールドで - 実行間で起動ファイルのコードを変更することなく実行されます。

### `get_artefacts_params`

指定された実行に対して `artefacts.yaml` で設定されたすべてのパラメータを読み込み、それらを `dict` として提供します。`.get()` などの通常の辞書メソッドと組み合わせて使用できます。

```python
get_artefacts_params()
```

#### パラメータ

なし

#### 戻り値

この関数は、指定された実行のすべてのパラメータを `dict` 型として返します。

> [!NOTE]
> 返される内容は、`artefacts.yaml` ファイルでテストファイルを指すために `launch_test_file` または `run` のどちらを使用しているかによって異なります。`launch_test_file` を使用している場合、パラメータは「ROS化」されますが、`run` を使用している場合はされません。例として：
>
> ```yaml
> scenarios:
>   defaults:
>     output_dirs: ["output"]
>     metrics:
>         - /odometry_error
>     params:
>       my_test_node/parameter_1: [0.1, 0.2]
>       my_test_node/parameter_2: ["a", "b"]
> ```
>
> `launch_test_file` を使用している場合、以下を返します：
>
> ```python
> # Run 1
> {
>     'my_test_node': {
>         'ros__parameters': {
>             'parameter_1': 0.1,
>             'parameter_2': 'a'
>         }
>     }
> }
>
> # Run 2
> {
>     'my_test_node': {
>         'ros__parameters': {
>             'parameter_1': 0.2,
>             'parameter_2': 'b'
>         }
>     }
> }
> ```
>
> `run` を使用している場合、以下を返します：
>
> ```python
> # Run 1
> {
>     'my_test_node/parameter_1': 0.1,
>     'my_test_node/parameter_2': 'a'
>
> }
>
> # Run 2
> {
>     'my_test_node/parameter_1': 0.2,
>     'my_test_node/parameter_2': 'b'
>
> }
> ```

#### 例

以下の設定が設定された `artefacts.yaml` ファイルがある場合：

```yaml
scenarios:
    defaults:
        params:
            headless: "True"
```

ヘッドレスシミュレーション用の launch_description にフラグを次のように設定できます：

```python
@launch_pytest.fixture(scope="module")
def launch_description(rosbag_recording):
    pkg_path = Path(get_package_share_directory("my_package"))
    try:
        headless = get_artefacts_params().get("headless", "False")
    except RuntimeError:
        # artefacts パラメータが利用できない場合、デフォルトで False に設定
        headless = "False"

    start_launch = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            str(pkg_path / "launch" / "mytestfile.launch.py")
        ),
        launch_arguments={
            "headless": headless,
        }.items(),
    )
```

---

### `merge_ros_params_files`

2つの ROS2 yaml パラメータファイルを1つにマージし、最初のファイル（`source`）の値を `override` の値で上書きします。

```python
merge_ros_params_files(
    source,
    override,
    destination,
    rosify=False
)
```

#### パラメータ

| **パラメータ** | **型** | **説明**                                               | **デフォルト** |
| ------------- | -------- | ------------------------------------------------------------- | ----------- |
| `source`      | `str`    | 上書き _される_ 元のパラメータファイルへのパス            | 必須    |
| `override`    | `str`    | 上書き _する_ パラメータを含むパラメータファイルへのパス    | 必須    |
| `destination` | `str`    | 新しいパラメータファイルを保存する場所へのパス              | 必須    |
| `rosify`      | `bool`   | `True` の場合、パラメータを ros2 パラメータファイルのネスト形式に変換    | `False`     |


#### 戻り値

`None`: 新しく作成されたマージ済みパラメータファイルは `destination` で指定されたパスで利用可能になります。

#### 例

以下の `source` と `override` yaml ファイルがある場合：

```yaml
# source
outer:
    inner1: 1
    inner2: 
        leaf: keep
flat: src

# override
outer:
    inner2:
        leaf: replaced
        new_leaf: 321
    inner3: added
flat: override
```

以下のような新しい yaml ファイルが `destination` に保存されます：

```yaml
# rosify=False (デフォルト)
outer:
    inner1: 1
    inner2:
        leaf: replaced
        new_leaf: 321
    inner3: added
flat: override
```

`rosify=True` の場合、パラメータは適切なノードの `ros__parameters` の下にネストされます：

```yaml
#source
controller_server:
    ros__parameters:
        enable_stamped_cmd_vel: true
        controller_frequency: 20.0
        min_x_velocity_threshold: 0.001

#override
controller_server/controller_frequency: 30
controller_server/min_x_velocity_threshold: 0.005
controller_server/min_y_velocity_threshold: 0.5   
    
#destination
controller_server:
    ros__parameters:
        enable_stamped_cmd_vel: true
        controller_frequency: 30
        min_x_velocity_threshold: 0.005
        min_y_velocity_threshold: 0.5
```
