> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ionworks.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python API

> ionworks-api Python クライアントで UCP シミュレーションを実行し、パラメータ化パイプラインをプログラムから送信します

[`ionworks-api`](https://github.com/ionworks/ionworks-api) Python パッケージを使うと、シミュレーションを実行してパラメータ化パイプラインをプログラムから送信できます。インストールと認証については、[Python API クライアント](/ja/api-client)ページを参照してください。

## シミュレーションの実行

`client.simulation` を使ってシミュレーションを実行します。シミュレーションには[パラメータ化モデル](/ja/build/parameterized-models)と [UCP 形式](/ja/simulate/universal-cycler-protocol)のプロトコルが必要です。

### 単一シミュレーション

```python theme={null}
response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": """
global:
  initial_soc: 1
  temperature: 25
steps:
  - Discharge:
      mode: C-rate
      value: 1
      ends:
        - "Voltage < 2.5"
""",
        "name": "1C Discharge",
    },
})

print(f"Simulation ID: {response.simulation_id}")
print(f"Job ID: {response.job_id}")
```

実験パラメータと設計パラメータも渡せます:

```python theme={null}
response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": """
global:
  initial_soc: input["Initial SOC"]
steps:
  - Discharge:
      mode: C-rate
      value: input["C-rate"]
      ends:
        - "Voltage < 2.5"
""",
        "name": "Parameterized Discharge",
    },
    "experiment_parameters": {
        "Initial SOC": 1.0,
        "C-rate": 0.5,
    },
    "design_parameters": {
        "Positive electrode thickness [m]": 75e-6,
    },
})
```

`design_parameters` は `protocol()` における単一シミュレーション用の便宜的なフィールドです。パラメータのオーバーライドをフラットな `dict[str, float]` で渡すと、クライアントが内部で 1 行の離散 DOE に変換してから送信します。完全な DOE スキーマを書かずに、単一の実行で 1 つ以上の設計パラメータを変えたい場合に使用してください。

<Note>
  `protocol()` では `design_parameters` と `design_parameters_doe` は排他的であり、DOE を渡す場合はちょうど 1 つのシミュレーションに展開される必要があります。両方を同時に渡したり、複数のシミュレーションに展開される DOE を渡したりすると `ValueError` が発生します。複数シミュレーションのスイープには、代わりに [`protocol_batch`](#%E5%AE%9F%E9%A8%93%E8%A8%88%E7%94%BB%E6%B3%95-doe-%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%83%83%E3%83%81%E3%82%B7%E3%83%9F%E3%83%A5%E3%83%AC%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3) を使用してください。
</Note>

### 結果を待機する

`wait_for_completion` を使ってシミュレーションの完了までポーリングします。このメソッドは、タイムアウトを待たずに失敗・キャンセルされたジョブを即座に検出します。

```python theme={null}
result = client.simulation.wait_for_completion(
    response.simulation_id,
    timeout=120,        # seconds (default: 60)
    poll_interval=2,    # seconds between polls (default: 2)
    verbose=True,       # print status updates (default: True)
)
```

シミュレーションが失敗したときに例外を発生させる代わりに結果の dict を取得するには、`raise_on_failure=False` を設定します:

```python theme={null}
result = client.simulation.wait_for_completion(
    response.simulation_id,
    raise_on_failure=False,
)
```

### 実験計画法 (DOE) によるバッチシミュレーション

`protocol_batch` を使ってパラメータスイープにわたる複数のシミュレーションを実行します:

```python theme={null}
responses = client.simulation.protocol_batch({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": "...",
        "name": "C-rate Sweep",
    },
    "design_parameters_doe": {
        "sampling": "grid",
        "rows": [
            {
                "type": "discrete",
                "name": "Positive electrode thickness [m]",
                "values": [50e-6, 75e-6, 100e-6],
            },
        ],
    },
})

# Wait for all simulations
results = client.simulation.wait_for_completion(
    [r.simulation_id for r in responses],
    timeout=300,
)
```

サポートされる DOE 行タイプ:

| タイプ        | フィールド                | 説明                 |
| ---------- | -------------------- | ------------------ |
| `discrete` | `values`             | テストする特定の値          |
| `range`    | `min`、`max`、`count`  | min と max の間の等間隔の値 |
| `normal`   | `mean`、`std`、`count` | 平均周辺でサンプリングされた値    |

サンプリング戦略: `grid`（すべての組み合わせ）、`random`、`latin_hypercube`。

### シミュレーションデータの取得

```python theme={null}
# List all simulations
simulations = client.simulation.list()

# Get a specific simulation
simulation = client.simulation.get(simulation_id)

# Get result data (time series, steps, metrics)
result = client.simulation.get_result(simulation_id)
```

`get_result` は、3 つのフィールドを持つ型付きの `SimulationResult` データクラスを返します。

| フィールド                | 型                | 説明                                                                   |
| -------------------- | ---------------- | -------------------------------------------------------------------- |
| `result.time_series` | `DataFrame`      | 各時点ごとに 1 行。列名は信号名（例: `"Time [s]"`、`"Voltage [V]"`、`"Current [A]"`）。  |
| `result.steps`       | `DataFrame`      | プロトコルのステップごとに 1 行（例: `"Step count"`、`"Step type"`、`"Duration [s]"`）。 |
| `result.metrics`     | `dict[str, Any]` | 実行全体にわたって計算されたスカラーメトリクス（例: サイクルレベルのサマリー）。                            |

`time_series` と `steps` はデフォルトで polars DataFrame として返されます。pandas DataFrame を受け取りたい場合は、セッション開始時に [`set_dataframe_backend("pandas")`](/ja/api-client#dataframe-backend) を一度呼び出してください。

```python theme={null}
from ionworks import Ionworks

client = Ionworks()
simulation_id = "your-simulation-id"  # 例: 送信した実行の response.simulation_id
result = client.simulation.get_result(simulation_id)

# 電圧と時間のプロット。デフォルトの polars バックエンドでは先に pandas へ変換します。
# pandas バックエンド（set_dataframe_backend("pandas")）では result.time_series をそのまま使用できます。
ts = result.time_series.to_pandas()  # pandas バックエンドでは .to_pandas() を省略
ts.plot(x="Time [s]", y="Voltage [V]")

# Inspect protocol steps
print(result.steps)

# Read scalar metrics
print(result.metrics)
```

<Note>
  `time_series` の `Discharge capacity [A.h]` と `Charge capacity [A.h]` は、ステップ境界ごとに 0 にリセットされます。`time_series` と `steps` を結合する場合は `"Step count"` を使用してください。連続した累積容量のトレースが必要な場合は、ステップごとの最終値を累積してください。
</Note>

## パイプラインの実行

パイプラインは、バッテリーモデルパラメータ化のためのデータフィッティング、計算、検証のステップを組み合わせます。`client.pipeline` を使ってパイプラインを送信・管理します。

<Note>
  パイプラインには `project_id` が必要です。[デフォルトプロジェクト](/ja/api-client#default-project)を設定するには、`IONWORKS_PROJECT_ID` 環境変数を設定するか、`Ionworks(...)` に `project_id=` を渡してください。あるいはパイプライン設定に明示的に `project_id` を含めてください。非推奨の `PROJECT_ID` 環境変数も依然としてフォールバックとして受け入れられます。
</Note>

### パイプラインの送信

```python theme={null}
# project_id is auto-injected from IONWORKS_PROJECT_ID or the client default;
# pass it explicitly in the config to override.
pipeline = client.pipeline.create({
    "name": "NMC622 Parameterization",
    "elements": {
        "entry": {
            "element_type": "entry",
            "values": {
                "model": {"type": "SPM"},
                "data": "db:your-measurement-id",
            },
        },
        "data_fit": {
            "element_type": "data_fit",
            "objectives": {"voltage": {"data": "entry.data"}},
            "parameters": {
                "Negative electrode diffusivity [m2.s-1]": {
                    "bounds": [1e-16, 1e-12],
                    "initial_value": 3.3e-14,
                }
            },
        },
    },
})

print(f"Pipeline ID: {pipeline.id}")
print(f"Status: {pipeline.status}")
```

パイプラインの要素は辞書である必要があります（リストではありません）。各キーは要素名で、値はその設定です。

<Tip>
  構築時のバリデーションと IDE の補完が得られる、型付きの
  [`iws.Pipeline` ビルダー](/ja/pipelines/api) の利用を推奨します。ここで示した設定と
  同じ内容にシリアライズされます。生の辞書（上記）も受け付けられます。
</Tip>

### パイプラインの完了を待機する

```python theme={null}
result = client.pipeline.wait_for_completion(
    pipeline.id,
    timeout=600,        # seconds (default: 600)
    poll_interval=2,    # seconds between polls (default: 2)
    verbose=True,
)

print(f"Final status: {result.status}")
```

### パイプライン結果の取得

```python theme={null}
pipeline_result = client.pipeline.result(pipeline.id)

# Access fitted parameter values
for name, element in pipeline_result.element_results.items():
    print(f"{name}: {element}")
```

### パイプライン内のデータ参照

パイプライン設定でデータソースを参照するには、これらのプレフィックスを使用します:

| プレフィックス   | 例                     | 説明                  |
| --------- | --------------------- | ------------------- |
| `db:`     | `"db:measurement-id"` | アップロードされた測定を ID で参照 |
| `file:`   | `"file:data.csv"`     | ローカル CSV ファイルを読み込み  |
| `folder:` | `"folder:data_dir/"`  | ローカルディレクトリから読み込み    |

<Tip>
  パイプライン設定内のインライン DataFrame には 1,000 行の制限があります。より大きなデータセットはまず測定としてアップロードし、`db:measurement-id` で参照してください。
</Tip>

<Note>
  `folder:` スキームは `time_series` ファイルと `steps` ファイルを含むディレクトリを想定しています。`.parquet` と `.csv` の両方がサポートされ、両方が存在する場合は parquet が優先されます。例えば、`time_series.parquet` と `steps.parquet`（または `.csv`）を含むフォルダは正しく読み込まれます。
</Note>

### PyBaMM モデルのサポート

パイプライン設定は PyBaMM モデルオブジェクトを直接受け入れます。クライアントは送信前に自動的にシリアライズします:

```python theme={null}
import pybamm

pipeline = client.pipeline.create({
    "elements": {
        "entry": {
            "element_type": "entry",
            "values": {
                "model": pybamm.lithium_ion.SPM(),
            },
        },
    },
})
```

## シンプルパイプラインの実行

単一のデータフィットまたは単一の検証ステップを含むパイプラインには、`client.pipeline` の代わりに `client.simple_pipeline` を使用します。シンプルパイプラインは、軽量なファイア・アンド・フォーゲットの代替手段です。1 つの設定を送信すると、サーバーはそれをエンドツーエンドで単一のジョブとして実行し、フラットな `parameter_values` 結果を返します。

### シンプルパイプラインの使いどころ

| `client.simple_pipeline` を使う場合                                | `client.pipeline` を使う場合 |
| ------------------------------------------------------------- | ----------------------- |
| 設定に最大 1 つの `data_fit`、`array_data_fit`、または `validation` 要素がある | 設定が複数のフィット、計算、検証を連結する   |
| 単一の結果ペイロードでファイア・アンド・フォーゲット実行が欲しい                              | 要素ごとのステータス追跡と中間結果が必要    |
| フラットな `parameter_values` 辞書が返ってほしい                            | 要素間で累積パラメータを通す必要がある     |

<Note>
  シンプルパイプラインには `project_id` が必要です。[デフォルトプロジェクト](/ja/api-client#default-project)を設定するには、`IONWORKS_PROJECT_ID` 環境変数を設定するか、`Ionworks(...)` に `project_id=` を渡してください。あるいは各呼び出しで `project_id=` を明示的に渡してください。
</Note>

### シンプルパイプラインの送信

```python theme={null}
config = {
    "elements": {
        "initial_params": {
            "element_type": "entry",
            "values": {"Negative particle diffusivity [m2.s-1]": 2e-14},
        },
        "fit": {
            "element_type": "data_fit",
            "objectives": {"voltage": {"data": "db:your-measurement-id"}},
            "parameters": {
                "Negative particle diffusivity [m2.s-1]": {
                    "bounds": [1e-14, 1e-13],
                    "initial_value": 2e-14,
                }
            },
            "cost": {"type": "RMSE"},
            "optimizer": {"type": "DifferentialEvolution", "max_iterations": 10},
        },
    }
}

sp = client.simple_pipeline.create(
    config,
    name="NMC622 diffusivity fit",
    description="Single-parameter fit on the May 14 dataset",
)

print(sp.id, sp.status)  # status starts as "pending"
```

<Tip>
  構築時のバリデーションと IDE の補完が得られる、型付きの
  [`iws.SimplePipeline` 形式](/ja/guide/pipelines/simple-pipelines) の利用を推奨します
  （例: `cost=iws.costs.RMSE()`）。ここで示した設定と同じ内容にシリアライズされます。
</Tip>

`elements` 辞書は最大 1 つの `data_fit`、`array_data_fit`、または `validation` 要素を含むことができます。`entry` 要素のようなヘルパーエントリは許可され、フィットの前に評価されます。

### 実行オプション

`create` に `options` 辞書を渡すことで、送信したパイプラインの実行時の挙動を制御できます。オプションは送信メタデータであり、サーバーがジョブをどのように実行するかに影響しますが、パイプライン設定の一部としては保存されません。

| オプション                   | 型              | デフォルト                              | 効果                                                                                                        |
| ----------------------- | -------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `live_progress_updates` | `bool \| None` | `None`（ジョブタイプに応じてワーカーが適切なデフォルトを選択） | `True` の場合、ワーカーは実行中にチェックポイントの進捗をデータベースに書き込み、途中経過をポーリングできるようにします。`False` の場合、パフォーマンス向上のためチェックポイントをスキップします。 |

```python theme={null}
sp = client.simple_pipeline.create(
    config,
    name="NMC622 diffusivity fit",
    options={"live_progress_updates": False},  # 速度のためチェックポイントをスキップ
)
```

`options`（および `project_id`、`name`、`description`）は設定辞書に直接埋め込むこともできます。`create` は送信前にこれらを設定から取り出します。`create` に明示的に渡された引数は、設定内の値より優先されます。

```python theme={null}
config = {
    "options": {"live_progress_updates": True},
    "elements": { ... },
}

sp = client.simple_pipeline.create(config)
```

### 完了を待機する

`wait_for_completion` は、パイプラインが終端ステータス（`completed`、`failed`、または `canceled`）に達するまでポーリングし、最終レコードを返します。

```python theme={null}
completed = client.simple_pipeline.wait_for_completion(
    sp.id,
    timeout=600,        # seconds (default: 600)
    poll_interval=2,    # seconds between polls (default: 2)
    verbose=True,
    raise_on_failure=True,
)

# Fitted parameter values are returned as a flat dict
print(completed.result["parameter_values"])
# {"Negative particle diffusivity [m2.s-1]": 5.3e-14}
```

検証実行の場合、結果には `parameter_values` と並んで `summary_stats` ブロックも含まれます。

`timeout` 以内にパイプラインが完了しない場合は `TimeoutError` が発生します。`failed` で終了し、`raise_on_failure=True`（デフォルト）の場合、サーバー側のエラーメッセージを含む `IonworksError` が発生します。

### 一覧、フィルタリング、ソート

`list` は `items`、`count`、`total` を含むページ分割されたレスポンスを返します。文字列フィルタは、完全な値または `ilike.%foo%`（大文字小文字を区別しない部分一致）や `in.(completed,failed)`（集合のいずれかに一致）のような演算子プレフィックス付きの式を受け入れます。

```python theme={null}
# Newest 25 simple pipelines in the default project
page = client.simple_pipeline.list(limit=25)

# Only currently active runs
active = client.simple_pipeline.list(status="in.(pending,running)")

# Name contains "diffevo" (case-insensitive)
matches = client.simple_pipeline.list(name="ilike.%diffevo%")

# Created in the last week, oldest first
recent = client.simple_pipeline.list(
    created_at_gt="2026-05-08",
    created_at_lt="2026-05-15",
    order_by="created_at",
    order="asc",
)
```

### 更新、キャンセル、削除

```python theme={null}
# Rename or add a description (PATCH — at least one field is required)
client.simple_pipeline.update(sp.id, name="Renamed", description="notes")

# Cancel a running pipeline
client.simple_pipeline.cancel(sp.id)

# Permanently delete the pipeline, its job, and stored config
client.simple_pipeline.delete(sp.id)
```

### エラー処理

```python theme={null}
from ionworks.errors import IonworksError

try:
    result = client.simple_pipeline.wait_for_completion(sp.id)
except TimeoutError:
    # Still running after the timeout — fetch the latest status to decide
    current = client.simple_pipeline.get(sp.id)
    print(f"Still {current.status}")
except IonworksError as e:
    # Pipeline ended in "failed" — the message includes the server error
    print(e)
```

## スタディの管理

`client.study` を使って[スタディ](/ja/simulate/studies)を作成、一覧、更新、削除します。スタディはプロジェクトにスコープされます。

すべての `client.study.*` メソッドは `project_id` を任意のキーワード引数として受け入れます。省略すると、クライアントに設定された[デフォルトプロジェクト](/ja/api-client#default-project)（または `IONWORKS_PROJECT_ID` から解決されたもの）を使用します。呼び出しごとにオーバーライドするには、`project_id=` を明示的に渡してください。

### スタディの一覧

```python theme={null}
# Uses the default project from the client
studies = client.study.list()
for study in studies:
    print(f"{study.name} (ID: {study.id})")

# Filter by name
studies = client.study.list(name="Discharge")

# Paginate results
studies = client.study.list(limit=10, offset=0)

# Override the project for a single call
studies = client.study.list(project_id="other-project-id")
```

サポートされるフィルター: `name`、`name_exact`、`order_by`、`order`。

### スタディの取得

```python theme={null}
study = client.study.get("your-study-id")
```

### スタディの作成

```python theme={null}
study = client.study.create({
    "name": "1C Discharge Sweep",
    "description": "Comparing discharge curves across temperatures",
})
```

### スタディの更新

```python theme={null}
study = client.study.update("your-study-id", {
    "name": "1C Discharge Sweep v2",
})
```

### シミュレーションと測定の割り当て

```python theme={null}
# Assign a simulation to a study
client.study.assign_simulation("your-study-id", "simulation-id")

# Remove a simulation from a study
client.study.remove_simulation("your-study-id", "simulation-id")

# Assign a measurement to a study
client.study.assign_measurement("your-study-id", "measurement-id")

# List measurements in a study
measurements = client.study.list_measurements("your-study-id")

# Remove a measurement from a study
client.study.remove_measurement("your-study-id", "measurement-id")
```

### スタディの削除

```python theme={null}
client.study.delete("your-study-id")
```

## プロトコルの管理

[UCP プロトコル](/ja/simulate/universal-cycler-protocol)を検証するには `client.protocol` を使用します。

### プロトコルの検証

```python theme={null}
result = client.protocol.validate("""
global:
  initial_soc: 1
  temperature: 25
steps:
  - Discharge:
      mode: C-rate
      value: 1
      ends:
        - "Voltage < 2.5"
""")
print(result["valid"])  # True or False
if not result["valid"]:
    print(result["error"])
```

### 入力参照の検索

プロトコル文字列内の `input[...]` プレースホルダーを検索します。実験パラメータフォームの構築に便利です。

```python theme={null}
refs = client.protocol.find_input_references("""
global:
  initial_soc: input["Initial SOC"]
steps:
  - Discharge:
      mode: C-rate
      value: input["C-rate"]
""")
print(refs)  # ["Initial SOC", "C-rate"]
```

### UCP からベンダープロトコルファイルへの変換

`client.protocol.convert` を使って、UCP YAML プロトコルを商用サイクラーで使用されるネイティブファイル形式に変換します。これは[商用プロトコルのアップロードフロー](/ja/simulate/simulating-commercial-protocols)の逆です。Ionworks で設計されたプロトコルから始め、ハードウェアで実行できるファイルを生成します。

サポートされるターゲット: `maccor`、`arbin`、`neware`、`biologic_bttest`、`novonix`。

```python theme={null}
result = client.protocol.convert(
    protocol="""
global:
  initial_temperature: 25
  initial_state_type: soc_percentage
  initial_state_value: 100
steps:
  - CC Charge:
      - Charge:
          mode: C-rate
          value: 1
          ends:
            - "Voltage > 4.2"
  - CV Charge:
      - Charge:
          mode: Voltage
          value: 4.2
          ends:
            - "Current < 0.05"
  - Discharge:
      - Discharge:
          mode: C-rate
          value: 1
          ends:
            - "Voltage < 2.7"
""",
    target="maccor",
)

# Inspect the converted protocol as text
print(result.text())

# Or write every output file (primary protocol plus any sidecars) to disk
paths = result.save("./converted")
print(paths)  # [PosixPath('converted/protocol.000'), ...]
```

`ConvertResult` は以下を公開します:

* `primary_bytes` — プライマリプロトコルファイルの生のバイト。
* `text(encoding="utf-8")` — `primary_bytes` を文字列にデコードします。
* `save(dir)` — すべての出力ファイル（プライマリと任意のサイドカー）を `dir` に書き込み、書き込んだパスのリストを返します。

<Note>
  ドライブサイクルステップを含む Maccor プロトコルは、プライマリの `.000`
  ファイルに加えて 1 つ以上の `.MWF` 波形ファイルを生成します。すべてのサイドカーがプライマリプロトコルの隣に配置されるよう、`result.save(dir)`
  を使用してください。`primary_bytes` のみを処理すると波形ファイルが失われ、プロトコルはサイクラー上で実行できなくなります。
</Note>

<Note>
  一部の UCP 機能はすべての形式間で明確にマッピングされますが、各ベンダーには独自の構文と制限があります（[商用プロトコル間の違い](/ja/simulate/simulating-commercial-protocols#differences-between-commercial-protocols)を参照）。UCP 構造がターゲット形式で表現できない場合、変換はサポートされていないステップを記述するエラーを返します。実際のサイクラーで実行する前に、[商用プロトコルフロー](/ja/simulate/simulating-commercial-protocols)で再アップロードして出力を検証してください。
</Note>

<Tip>
  どのリソースの ID も、Ionworks Studio Web アプリから確認できます。リソースの詳細ページに移動すると、URL に ID が表示されます。
</Tip>

## 次のステップ

<CardGroup cols={2}>
  <Card title="シミュレーション" icon="play" href="/ja/simulate/simulations">
    Ionworks Studio でのシミュレーションの実行について学びます。
  </Card>

  <Card title="プロトコルリファレンス" icon="scroll" href="/ja/simulate/universal-cycler-protocol">
    Universal Cycler Protocol 形式の完全なリファレンスです。
  </Card>

  <Card title="データのアップロード" icon="database" href="/ja/data/uploading">
    Python API でセルデータをアップロード・管理します。
  </Card>

  <Card title="Build API" icon="wrench" href="/ja/build/api">
    モデルとパラメータ化モデルを一覧・取得します。
  </Card>
</CardGroup>
