# Fixstars Amplify SDK documentation > Fixstars Amplify SDK (以下 Amplify SDK) は、 組合せ最適化問題の定式化および外部の最適化ソルバーの実行を行うための Python ライブラリです。 このファイルはドキュメントの全ページを、 の目次の順に持ちます。各ページの前にはそのページの URL をコメントで置き、ページの区切りは水平線です。 --- # Fixstars Amplify SDK documentation これはドキュメントの Markdown 版です。HTML 版 と同じ内容を持ちます。AI エージェントが Web ページのマークアップを介さずにドキュメントを読むためのものです。 以下のページは全て Markdown ファイルであり、ページ中のリンクも別の Markdown ファイルを指します。`llms.txt` はこの目次を絶対 URL で持ち、`llms-full.txt` は全ページを 1 つのファイルに持ちます。 [![Fixstars Amplify](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/amplify-logo.svg)](https://amplify.fixstars.com/) [![Fixstars Amplify](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/amplify-logo-dark.svg)](https://amplify.fixstars.com/) [![Fixstars Amplify](https://img.shields.io/badge/-Fixstars%20Amplify-333333.svg)](https://amplify.fixstars.com/) [![PyPI](https://img.shields.io/pypi/v/amplify)](https://pypi.org/project/amplify/) [![Downloads](https://static.pepy.tech/personalized-badge/amplify?period=total&units=international_system&left_color=grey&right_color=orange&left_text=Downloads)](https://pepy.tech/project/amplify) *Fixstars Amplify SDK* (以下 Amplify SDK) は、 組合せ最適化問題の定式化および外部の最適化ソルバーの実行を行うための Python ライブラリです。 Amplify SDK を用いることにより、組合せ最適化問題の定式化をシンプルかつ直感的に行うことができます。 また、定式化を行ったあとは、[量子アニーリングマシン](https://en.wikipedia.org/wiki/Quantum_annealing)、イジングマシン、[量子コンピュータ](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/index.md)、MIPソルバーを含むさまざまなハードウェア・ソフトウェアソルバーを共通のインターフェースを通じて簡単に実行することができるようになります。 --- **Amplify SDK の特長** **🔰 直感的で使いやすい** Amplify SDK の使い方はとても簡単です。シンプルで直感的な手順で組合せ最適化問題の定式化とソルバーの実行が行えます。 インストール不要で利用出来るソルバー [Amplify Annealing Engine](https://amplify.fixstars.com/engine) も無償で提供されます。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#easy-to-use) **🚅 高速な数式処理** Amplify SDK による定式化は非常に高速かつ省メモリで処理するように設計されています。 大規模な組合せ最適化問題を視野に入れたアプリケーションの開発が行えます。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#blazing-fast) **🔱️ 複数のソルバーに対応** Amplify SDK から利用出来るソルバーは、量子アニーリングマシン、イジングマシン、量子コンピュータ、MIP ソルバーなど多岐に渡ります。 ユースケースに合わせたソルバーの選択が可能です。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#multiple-solvers) **🧑‍💻️ 幅広い対象ユーザ** Amplify は組合せ最適化に取り組む幅広いユーザに利用頂けます。アプリケーションソフトウェア開発から学術研究まで、様々なユーザ層を支援できるように設計されています。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#wide-range-users) > [!NOTE] > > **Changed in version 1.0.0** > > *Fixstars Amplify SDK* はバージョン 1.0.0 で大きく生まれ変わり、これまで以上に直感的で使いやすく、対象のモデルを広げ、高い柔軟性と高速な動作の両立を実現しました。以前のバージョンからの移行ガイドは [旧バージョンからの移行](https://amplify.fixstars.com/ja/docs/amplify/v1/migration.md) を参照してください。また、移行がスムーズに行えるように旧バージョンとの互換レイヤも用意しています。 > 以前のバージョンのドキュメントは で参照できます。 --- **Amplify のはじめ方** **🆔 STEP 1** [**ユーザ登録**](https://amplify.fixstars.com/register) ユーザ登録を行うと [Amplify Annealing Engine](https://amplify.fixstars.com/engine) の API トークンを無償で入手できます。 **🛠️ STEP 2** [インストール](https://amplify.fixstars.com/ja/docs/amplify/v1/quickstart.md) Amplify SDK は Windows / Linux / MacOS 環境で pip コマンドを利用してインストールできます。 **🔍 STEP 3** [**デモ&チュートリアル**](https://amplify.fixstars.com/demo) Amplify の使い方を学ぶためのデモやチュートリアルを用意しています。 > [!NOTE] > > **注釈** > > *Fixstars Amplify SDK* はプロプライエタリソフトウェアです。 > 非商用利用や学術利用では無償で利用することができます。詳細は [Fixstars Amplify 利用規約](https://amplify.fixstars.com/termsofuse)を参照してください。 > 学術論文において引用する際は、下記の BibTeX 形式をご使用ください。 > > * Fixstars Amplify SDK > > ``` > @misc{fixstarsamplifysdkdoc, > author = "{Fixstars Amplify Corporation}", > title = {{Fixstars Amplify SDK documentation}}, > howpublished = "\url{https://amplify.fixstars.com/en/docs/amplify/v1/}", > year = {2024}, > note = "[Accessed: 7-March-2024]" > } > ``` > > [Download BibTeX](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/eed8f336eaf8b121a975320d27df34f2/citation_sdk.bib) > * Fixstars Amplify Annealing Engine (AE) > > ``` > @misc{fixstarsamplifyaedoc, > author = "{Fixstars Amplify Corporation}", > title = {{API Reference - Fixstars Amplify Annealing Engine}}, > howpublished = "\url{https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae.html}", > year = {2025}, > note = "[Accessed: 30-September-2025]" > } > ``` > > [Download BibTeX](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/fa40222046f6d5b3cc720832fc4384a9/citation_ae.bib) > * Fixstars Amplify > > Fixstars Amplify SDK, AE の両方をまとめて引用したい場合にお使いください。 > > ``` > @misc{fixstarsamplify, > author = "{Fixstars Amplify Corporation}", > title = {{Fixstars Amplify}}, > howpublished = "\url{https://amplify.fixstars.com/en/}", > year = {2020}, > note = "[Accessed: 7-March-2024]" > } > ``` > > [Download BibTeX](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/586ec087abf5502e07c22b264faf8aeb/citation_amplify.bib) ## 目次 ### 🚀 Get Started * [はじめに](https://amplify.fixstars.com/ja/docs/amplify/v1/index.md) — Fixstars Amplify SDK (以下 Amplify SDK) は、 組合せ最適化問題の定式化および外部の最適化ソルバーの実行を行うための Python ライブラリです。 * [Amplify SDK の特長](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md) — Amplify SDK のゴールは、組合せ最適化問題をシンプルかつ直感的に定式化し、様々なマシンやソルバーを用いて求解を実行することです。そのため、Amplify SDK は以下のような特長を持っています。 * [クイックスタート](https://amplify.fixstars.com/ja/docs/amplify/v1/quickstart.md) — 次のいずれかの方法で Amplify SDK を実行できます。 ### 🌱 Basic * [1. Amplify SDK の全体像](https://amplify.fixstars.com/ja/docs/amplify/v1/overview.md) — 機能の詳細に触れる前に、Amplify SDK の全体像と実行手順をまとめます。 * [2. 決定変数の作り方](https://amplify.fixstars.com/ja/docs/amplify/v1/variables.md) — Amplify SDK を使用して組合せ最適化問題を解くためには、問題の定式化をプログラムコード上で表現することが必要です。 このページでは、定式化の最初のステップとして、決定変数の生成について解説します。 * [3. 多項式と目的関数](https://amplify.fixstars.com/ja/docs/amplify/v1/objective.md) — 目的関数は組合せ最適化問題における目的の達成度を表す数式です。Amplify SDK では最小化したい多項式のことを指します。このページでは、Amplify SDK を用いて多項式を表現する方法について解説します。 * [4. 制約条件の構築](https://amplify.fixstars.com/ja/docs/amplify/v1/constraint.md) — 制約条件 とは、組合せ最適化問題において決定変数の値がみたすべき条件のことです。Amplify SDK では、各変数がとりうる範囲の制約と、多項式がとりうる範囲に関する制約をそれぞれ設定することができます。 * [5. モデルの定式化](https://amplify.fixstars.com/ja/docs/amplify/v1/model.md) — 組合せ最適化問題は、決定変数と目的関数、制約条件からなります。 「2. 決定変数の作り方」、「3. 多項式と目的関数」、「4. 制約条件」では、 決定変数は VariableGenerator を用いて作成することができ、 目的関数と制約条件は Poly と Constraint… * [6. ソルバークライアント](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md) — Amplify SDK からソルバーを実行するには、各ソルバーを抽象化したソルバークライアントを作成して、接続先、API トークン、実行パラメータなどを指定する必要があります。また、ソルバークライアントは対応関係にあるソルバーの扱える変数の種類、制約条件の有無、次数などの機能の情報を持ちます。Amplify SDK… * [7. 組合せ最適化問題の求解](https://amplify.fixstars.com/ja/docs/amplify/v1/solve.md) — このページでは、「モデルの定式化」と「クライアントの作成」で作成したモデル Model およびソルバークライアントを使用して、組合せ最適化問題の求解を行う方法を解説します。 ### 🌻 Advanced * [モデルの変換](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md) — Amplify SDK では、実数変数や整数変数を含むモデルや、任意の次数の多項式を含むモデルを作成できます。一方で、組合せ最適化ソルバーは一般に扱える変数の種類や次数、制約条件の種類や入力の可否に制限があり、また、特定の構造を持った二次の多項式しか受け取れない場合もあります。 * [変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md) — Amplify SDK では、実数変数や整数変数を含むモデルや、任意の次数の多項式を含むモデルを作成できます。一方で、組合わせ最適化ソルバーは一般に扱える変数の種類や次数に制限があります。解きたいモデルをソルバーの扱える変数の種類や多項式の次数に合わせるために Amplify SDK… * [制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md) — Amplify SDK では、任意の変数と多項式の次数を持つ制約条件を含むモデルを作成できます。しかし、組合せ最適化ソルバーごとに、制約条件として扱える変数の種類や次数は異なり、特に QUBO ソルバーでは制約条件そのものを受け取れないものもあります。 * [グラフ埋め込み](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md) — QUBO ソルバーやイジングソルバーの中には、任意の 2 次多項式を受け取れず、入力できる 2 次の項が制限されているものもあります。Amplify SDK は、そのようなソルバーに対して、グラフ埋め込みとよばれる操作を行い、多項式をそのソルバーが受け取れる形に変換します。 * [実行結果の評価](https://amplify.fixstars.com/ja/docs/amplify/v1/evaluation.md) — solve() 関数の実行結果には、解に関する情報やモデル変換の情報・実行時間情報などさまざまな情報が含まれています。このページでは、これらの情報を取得し、活用する方法について説明します。 * [実行時間情報の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/timing.md) — Amplify SDK は、組合せ最適化問題を解く一連のシーケンスにおいて、実行時間に関する情報を取得するインターフェースを提供しています。 * [クライアントの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md) — Amplify SDK には Amplify SDK から実行できるソルバーに対応したクライアントクラスが用意されています。クライアントクラスは各ソルバーの API をラップしたものであり、ソルバーの設定や実行パラメータの設定を行うインターフェースや、API のリクエストを行うメソッドを提供します。 * [Fixstars Amplify](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) — Fixstars Amplify Annealing Engine (以下 Amplify AE) は Fixstars Amplify 社の提供するソルバーです。シミュレーテッドアニーリングをベースとしたヒューリスティックアルゴリズムが GPU 上に実装されており、GPU… * [D-Wave Systems](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md) — D-Wave Systems の提供する量子アニーリングマシン (QPU) です。QUBO あるいは イジング変数の二次多項式で表された組合せ最適化問題を入力できます。 * [東芝](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/toshiba.md) — 東芝 の開発したシミュレーテッド分岐マシンを核とする量子インスパイアード最適化ソリューションです。 * [富士通](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fujitsu.md) — 富士通 の提供する第四世代アニーリングコア (GPU) による QUBO ソルバーです。 * [NEC](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/nec.md) — NEC の提供する QUBO ソルバーです。ベクトル型スーパーコンピュータ SX-Aurora TSUBASA 上で動作します。 * [日立](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/hitachi.md) — 日立 の提供する CMOS アニーリングマシンです。 * [Gurobi](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/gurobi.md) — Gurobi が提供する MIP (混合整数計画問題) ソルバーです。Gurobi Optimizer は QUBO を含む整数変数、実数変数の二次の問題を扱うことができます。 * [量子コンピュータ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) — 量子コンピュータのクライアントでは、QAOA に代表される量子アルゴリズムで最適化計算を実行します。 * [ソルバーの直列実行](https://amplify.fixstars.com/ja/docs/amplify/v1/serial.md) — 性能の評価を行いたい場合、ソルバーを何回か繰り返し実行したい場合があります。また、ソルバーによっては、長時間のタイムアウトを指定して 1 回実行するよりも短時間のタイムアウトで何回か繰り返し実行したほうが良い解を見つける可能性が高くなることもあります。Amplify SDK… * [ソルバーの並列実行](https://amplify.fixstars.com/ja/docs/amplify/v1/parallel.md) — parallel_solve()… * [係数行列による目的関数の作成](https://amplify.fixstars.com/ja/docs/amplify/v1/matrix.md) — 目的関数を表現する方法の 1 つとして、多項式の係数からなる多次元配列を用いる方法が用意されています。 この方法は、目的関数が \(x^\top Q x + p^\top x + c\) と表されるような実数値の 2 次元配列 \(Q\) と実数ベクトル \(p\) がすでに計算されている場合に便利な定式化方法です。… * [定式化の高速化](https://amplify.fixstars.com/ja/docs/amplify/v1/optimization.md) — 大規模な組合せ最適化問題を定式化したい場合、Python の for 文などを用いて定式化すると大きく時間がかかることがあります。 Amplify SDK は大規模な最適化問題を実用的な時間で定式化するための高速な定式化手段を提供しています。 例えば、PolyArray クラスの Numpy-like… * [モデルのファイル入出力](https://amplify.fixstars.com/ja/docs/amplify/v1/file_io.md) — LP ファイルもしくは QPLIB ファイルから Amplify SDK の Model を作成する機能と、逆に Amplify SDK の Model を保存して LP ファイルもしくは QPLIB ファイルを出力する機能が提供されます。 ### 🧩 Examples * [部分和問題](https://amplify.fixstars.com/ja/docs/amplify/v1/subset_sum.md) — このページでは、Amplify SDK を用いた定式化と求解の簡単な例として、部分和問題を扱います。 * [Max-Cut (最大カット) 問題](https://amplify.fixstars.com/ja/docs/amplify/v1/maxcut.md) — Max-Cut (最大カット) 問題は、代表的な組合せ最適化問題の一つです。ここでは、問題の定義から、Amplify SDK を用いた求解までを解説します。 * [巡回セールスマン問題](https://amplify.fixstars.com/ja/docs/amplify/v1/tsp.md) — Amplify の使用例として、巡回セールスマン問題を Amplify を用いて解く方法を解説します。 巡回セールスマン問題とは、いくつかの都市の集合が与えられたとき、ある都市から出発してすべての都市を 1 回ずつ訪れたあと最初の都市に戻ってくる巡回路のうち、最も長さが短いものを求める組合せ最適化問題です。 * [二次割当問題](https://amplify.fixstars.com/ja/docs/amplify/v1/qap.md) — 二次割当問題は、以下のような問題です。 ### 💡 Tips * [型ヒントサポート](https://amplify.fixstars.com/ja/docs/amplify/v1/type_hint.md) — Amplify SDK は全ての関数、メソッド、アトリビュートに型アノテーションを定義しています。これにより、Visual Studio Code 等の IDE や Google Colaboratory において、コードの補完や型チェックによるコードのエラーを検出することができます。 * [プロキシサーバの設定](https://amplify.fixstars.com/ja/docs/amplify/v1/proxy.md) — インターネット接続を行う際にプロキシサーバを経由する場合、Amplify SDK からクラウドサービスを実行するプログラムコード上でプロキシサーバを設定する必要があります。 * [数式の整形表示](https://amplify.fixstars.com/ja/docs/amplify/v1/pprint.md) — Jupyter Notebook, Visual Studio Code など、LaTeX による数式表示に対応した IPython のフロントエンド環境では Amplify SDK の数式は自動的に LaTeX で描画されます。 * [旧バージョンからの移行](https://amplify.fixstars.com/ja/docs/amplify/v1/migration.md) — Amplify SDK v1 は v0 とは一部の互換性が失われています。これまで旧バージョンを使っていた場合に、今後も動作し続けるようにコードを維持するための方法について説明します。 * [定式化ベンチマーク](https://amplify.fixstars.com/ja/docs/amplify/v1/benchmark.md) — Python のライブラリとして提供される数理最適化モデルについて、Amplify SDK との比較として定式化のベンチマークを取得しています。ここでは QUBO ソルバーの実行を前提として、巡回セールスマン問題の定式化 を例にモデルの作成し QUBO として出力するまでの実行時間を計測しました。 ### 🎺 Cloud Solvers * [Fixstars Amplify AE](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae.md) — Fixstars Amplify Annealing Engine (以下 Amplify AE) は Fixstars Amplify 社の提供するソルバーです。シミュレーテッドアニーリングをベースとしたヒューリスティックアルゴリズムが GPU 上に実装されており、GPU… * [最新バージョンの紹介](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/summary.md) — このページでは、Amplify AE の最新バージョン (v1.0系) における主な改良点と新機能について説明します。最新版は従来の Amplify AE (v0.9系) と比較して、次の主要な点で大幅な性能向上を実現しています。 * [求解のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/algorithm.md) — Fixstars Amplify Annealing Engine (Amplify AE) は、シミュレーテッドアニーリング (焼きなまし法) 法をベースにした最適化アルゴリズムで実行されます。 このページでは、Amplify AE のアルゴリズムの概要と、ソルバー内部の処理ステップについて説明します。 * [高度な利用方法](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/advanced.md) — レスポンスデータから取得できる情報を活用することで、Amplify AE の利用をより効果的に行えます。このセクションでは Amplify AE の高度な利用方法について説明します。 * [Amplify AE の性能評価](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/benchmark.md) — Amplify AE の性能を評価するため、(1) 求解性能、(2) アニーリング速度という 2 つの観点でベンチマークを取得しています。 * [Changelog](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/changelog.md) — Improve performance for linear problems containing only integer-coefficient constraints. * [API Reference](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/api_reference.md) ### ⚗️ Quantum * [Amplify Quantum](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/index.md) — Amplify SDK では量子コンピュータを利用した組合せ最適化計算を研究・検証するための機能を提供しています。 * [クイックスタート](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/quickstart.md) — 量子コンピュータを活用する機能は Amplify SDK のアドオンとして提供されています。利用するには次のコマンドで追加のパッケージを含めてインストールして下さい。 * [対応デバイス一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/index.md) — Amplify SDK で対応している量子コンピュータ及びそのシミュレータの一覧を示します。どのクライアントも共通のインターフェースで利用でき、対応アルゴリズム を初期化時に指定するだけで実行する最適化手法を切り替え可能です。 * [IBM Quantum](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ibm.md) — IBM QuantumのQPUを回路の評価に利用します。 * [Qiskit Aer Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aer.md) — Qiskit Aer Simulatorを回路の評価に利用します。 * [Qulacs Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qulacs.md) — Qulacs を回路の評価に利用するローカルシミュレータです。 * [Amazon Braket Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aws.md) — Amazon Braket のシミュレータを回路の評価に利用します。ローカルシミュレータとクラウドシミュレータの両方をサポートします。 * [AQT](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aqt.md) — AQT (Alpine Quantum Technologies) のイオントラップ型量子コンピュータを Amazon Braket 経由で回路の評価に利用します。 * [IonQ](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ionq.md) — IonQ のイオントラップ型量子コンピュータを回路の評価に利用します。 * [IQM](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/iqm.md) — IQM の超伝導型量子コンピュータを Amazon Braket 経由で回路の評価に利用します。 * [Rigetti](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/rigetti.md) — Rigetti の超伝導型量子コンピュータを Amazon Braket 経由で回路の評価に利用します。 * [QUDORA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qudora.md) — QUDORA のイオントラップ型量子コンピュータ及びそのクラウドシミュレータを回路の評価に利用します。 * [OQTOPUS Cloud](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/oqtopus.md) — OQTOPUS Cloud 経由で利用可能なクラウド量子コンピュータ及びシミュレータを回路の評価に利用します。 * [対応アルゴリズム一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/index.md) — Amplify SDK で対応している量子コンピュータを利用するアルゴリズムの一覧を示します。量子コンピュータを扱うクライアントは、初期化時にここで挙げるアルゴリズムクラスを指定して使用します。 * [QAOA / 制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) — QAOA (Quantum Approximate Optimization Algorithm) は量子コンピュータによる量子回路の実行と古典最適化を交互に繰り返す量子古典ハイブリッドアルゴリズムです。イジング変数で \(N\) 次多項式の目的関数の最適化問題を求解できます。 * [Recursive QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) — QAOA をサブルーチンとして繰り返し実行し、段階的に問題サイズを縮小しながら最適解を特定する量子古典ハイブリッドアルゴリズムです。各ステップで浅い回路による QAOA の測定結果から削減する変数を決定し、問題が十分小さくなった段階で総当たりにより厳密解を求めます。通常の QAOA… * [アルゴリズムの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/index.md) — Amplify SDK で対応している量子最適化アルゴリズムについてその理論的な枠組みを紹介します。 * [QAOAのアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md) — 本ページでは、QAOA (Quantum Approximate Optimization Algorithm)[1] の数理的な枠組みを説明します。 * [制約付き QAOA のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) — 最適化問題の中には、変数にある種の制約を課した下での最適値を求める、というものがあります。 * [Recursive QAOA のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md) — Recursive QAOA[1](以下、RQAOA)は、深さの浅い Ansatz 回路による QAOA を繰り返し実行し、段階的に問題サイズを縮小しながら最適解を特定する手法です。通常の QAOA で問題となる回路の深さの制約を緩和し、大規模な問題への適用を目指します。通常の QAOA の理論についての解説は… ### 🔌 Black-Box 最適化 * [Amplify-BBOpt](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_bbopt.md) — Amplify SDK の機能を活用して ブラックボックス最適化 (BBO) を実行するための拡張ライブラリです。 ### 📖 Reference * [Changelog](https://amplify.fixstars.com/ja/docs/amplify/v1/changelog.md) — Support quantum computers via the Amplify Quantum extension. * [API Reference](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/index.md) * [Algebra](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/algebra.md) — amplify.Poly * [Poly](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md) — The polynomial class used for representing objective functions and constraints. * [PolyArray](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md) — A NumPy-like multidimensional array of polynomials. Supports indexing, slicing, broadcast-compatible arithmetic, and utility methods for building optimization… * [Matrix](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md) — This class represents a quadratic objective in coefficient-matrix form, expressed as \(x^\top Q x + p^\top x + c\). * [Variable](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md) — Class for variable information. Instances are typically obtained via as_variable() or variables. * [VariableGenerator](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md) — Provides functionality to generate a decision variable or an array of decision variables. * [sum](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md) — Sum elements of a polynomial array, sequence, or iterator. Sum a sequence or iterator efficiently. Sum a sequence or iterator of constraints. Deprecated… * [einsum](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md) — Einstein summation for polynomial arrays and NumPy arrays. * [dot](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.dot.md) — Compute dot product for polynomial arrays and NumPy arrays. * [matmul](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.matmul.md) — Matrix multiplication for polynomial arrays and NumPy arrays. * [newaxis](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.newaxis.md) * [VariableType](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md) — ベースクラス: Enum * [Dim](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md) — Base class for PolyArray dimension types. * [Dim0](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim0.md) — ベースクラス: Dim * [Dim1](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md) — ベースクラス: Dim * [Dim2](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim2.md) — ベースクラス: Dim * [Dim3](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim3.md) — ベースクラス: Dim * [Dim4](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim4.md) — ベースクラス: Dim * [Constraint](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/constraint.md) — amplify.Constraint * [Constraint](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md) — Constraint class representing equality or inequality conditions on polynomial expressions. * [ConstraintList](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md) — List-like container of Constraint objects. * [equal_to](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md) — Create an equality constraint. * [one_hot](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md) — Create a one-hot constraint. * [less_equal](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md) — Create a less-than-or-equal constraint. * [greater_equal](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md) — Create a greater-than-or-equal constraint. * [clamp](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md) — Create a range constraint. * [domain_wall](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md) — Create domain wall constraints for a variable array. * [PenaltyFormulation](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md) — ベースクラス: Enum * [Model](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/model.md) — amplify.Model * [Model](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md) — Combinatorial optimization model containing objective and constraints. * [IntegerEncodingMethod](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md) — ベースクラス: Enum * [RealEncodingMethod](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md) — ベースクラス: Enum * [QuadratizationMethod](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md) — ベースクラス: Enum * [Graph Embedding](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/graph.md) — amplify.Graph * [Graph](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md) — Physical graph information used by graph-embedding solvers. * [embed](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md) — Perform graph embedding and return embedding information. * [to_edges](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.to_edges.md) — Convert a polynomial to its graph edge list. * [EmbeddingMethod](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md) — ベースクラス: Enum * [Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/client.md) — amplify.BaseClient * [BaseClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md) — Base class of all clients in the Amplify SDK * [AmplifyAEClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md) — ベースクラス: BaseClient * [FixstarsClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md) — ベースクラス: BaseClient * [DWaveSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md) — ベースクラス: BaseClient * [LeapHybridSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md) — ベースクラス: BaseClient * [LeapHybridCQMSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md) — ベースクラス: BaseClient * [FujitsuDA4Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md) — ベースクラス: BaseClient * [FujitsuDA3cClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md) — ベースクラス: FujitsuDA4Client * [ToshibaSQBM2Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md) — ベースクラス: BaseClient * [GurobiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md) — ベースクラス: BaseClient * [NECVA2Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md) — ベースクラス: NECVA2Client * [HitachiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md) — ベースクラス: BaseClient * [AcceptableDegrees](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md) — Container of acceptable polynomial degrees by variable type for objective and constraints. * [Degree](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Degree.md) — ベースクラス: Enum * [Solve](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/solve.md) — amplify.Result * [Result](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md) — Container of optimization solutions and conversion/runtime metadata. * [Values](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md) — Mapping from variables to numeric values in a solution. * [solve](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md) — Solve a combinatorial optimization problem. * [parallel_solve](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md) — Solve multiple problems in parallel. * [Misc.](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/misc.md) — amplify.set_num_threads * [set_num_threads](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.set_num_threads.md) — Set the number of threads used for parallel computation. * [load_lp](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_lp.md) — Load an LP file and construct a model. * [save_lp](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_lp.md) — Save a model to an LP file. * [load_qplib](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_qplib.md) — Load a QPLIB file and construct a model. * [save_qplib](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_qplib.md) — Save a model to a QPLIB file. * [set_seed](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.set_seed.md) — Set the seed for random number generation. * [__version__](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.__version__.md) — The version of the SDK. * [Quantum](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/index.md) * [Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/client.md) — QuantumBaseClient * [QuantumBaseClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md) — ベースクラス: _QuantumBaseClient[AlgoType], Generic[AlgoType, SamplingMeta_co, CircType_co] * [AerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md) — ベースクラス: QuantumBaseClient[AlgoType, QiskitJobMeta, QiskitCircuit] * [AQTClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md) — ベースクラス: QuantumBaseClient[AlgoType, BraketJobMeta, QiskitCircuit] * [BraketSimulatorClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md) — ベースクラス: QuantumBaseClient[AlgoType, BraketJobMeta, QiskitCircuit] * [IBMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md) — ベースクラス: QuantumBaseClient[AlgoType, QiskitJobMeta, QiskitCircuit], Generic[AlgoType] * [IonQClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md) — ベースクラス: QuantumBaseClient[AlgoType, BraketJobMeta | IonQJobMeta, QiskitCircuit] * [IQMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md) — ベースクラス: QuantumBaseClient[AlgoType, BraketJobMeta, QiskitCircuit] * [QulacsClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md) — ベースクラス: QuantumBaseClient[AlgoType, QulacsJobMeta, QulacsCircuit] * [RigettiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md) — ベースクラス: QuantumBaseClient[AlgoType, BraketJobMeta, QiskitCircuit] * [QUDORAClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md) — ベースクラス: QuantumBaseClient[AlgoType, _QudoraJobMeta, QiskitCircuit] * [OqtopusClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md) — ベースクラス: QuantumBaseClient[AlgoType, OqtopusJobMeta, QiskitCircuit] * [Algorithm](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md) — QAOA * [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md) — Quantum Approximate Optimization Algorithm (QAOA). * [QAOAType](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md) — ベースクラス: Enum * [QAOAResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAResult.md) — ベースクラス: Generic[SamplingMeta_co] * [QAOADurations](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md) — Total timing breakdown for a QAOA run. * [QAOAHistoryItem](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md) — ベースクラス: Generic[SamplingMeta_co] * [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md) — Recursive Quantum Approximate Optimization Algorithm (RQAOA). * [RQAOAType](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md) — ベースクラス: Enum * [RQAOAResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAResult.md) — ベースクラス: Generic[SamplingMeta_co] * [RQAOADurations](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md) — Total timing breakdown for an RQAOA run. * [RQAOAHistoryItem](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md) — ベースクラス: Generic[SamplingMeta_co] * [NormalElimination](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NormalElimination.md) — Record of a variable explicitly eliminated during an RQAOA iteration. * [UnintentionalElimination](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.UnintentionalElimination.md) — Record of a variable eliminated as a side effect of another variable's elimination. * [QuantumAlgoProtocol](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md) — ベースクラス: Protocol * [Minimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/minimize.md) — ScipyMinimize * [ScipyMinimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md) — Classical optimizer for QAOA circuit parameters using scipy.optimize.minimize(). * [ScipyMinimizeOptions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md) — ベースクラス: TypedDict * [ScipyMinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md) — Result of a ScipyMinimize optimization run. * [NoOpMinimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md) — Classical optimizer that evaluates the objective at a fixed set of parameters. * [NoOpMinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md) — Result of a NoOpMinimize run. * [MinimizeProtocol](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md) — ベースクラス: Protocol * [MinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md) — ベースクラス: Protocol * [Sampler](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/sampler.md) — SamplerProtocol * [SamplerProtocol](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md) — ベースクラス: Protocol, Generic[SamplingMeta_co, CircType_co] * [SamplingDurations](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md) — Timing breakdown for a single quantum circuit sampling call. * [AerDeviceType](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md) — Literal['CPU', 'GPU', 'Thrust'] の別名です。 * [QiskitJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md) — Metadata for a single Qiskit quantum job. * [QulacsJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md) — Metadata for a single Qulacs simulation run. * [BraketJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md) — Metadata for a single Braket quantum job. * [Circuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/circuit.md) — QiskitCircuit * [QiskitCircuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md) — Qiskit-based quantum circuit implementation. * [QulacsCircuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md) — Qulacs-based quantum circuit implementation. * [Misc.](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/misc.md) — IsingSeqFreqList * [IsingSeqFreqList](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md) — list[tuple[list[int], int]] の別名です。 * [Deprecated](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/deprecated.md) — amplify.BinaryPoly * [BinaryPoly](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md) — ベースクラス: Poly * [IsingPoly](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPoly.md) — ベースクラス: Poly * [BinaryPolyArray](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md) — ベースクラス: PolyArray * [IsingPolyArray](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md) — ベースクラス: PolyArray * [BinarySymbolGenerator](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md) — __init__ * [IsingSymbolGenerator](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md) — __init__ * [IsingSymbolGenerator](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md) — __init__ * [BinaryMatrix](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md) — ベースクラス: Matrix * [IsingMatrix](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md) — ベースクラス: Matrix * [QuadraticModel](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md) — ベースクラス: ABC * [BinaryQuadraticModel](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md) — ベースクラス: QuadraticModel * [IsingQuadraticModel](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md) — ベースクラス: QuadraticModel * [Solver](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Solver.md) — __init__ * [SolverResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverResult.md) — ベースクラス: UserList * [SolverSolution](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverSolution.md) — __init__ * [SymbolGenerator](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md) * [sum_poly](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum_poly.md) * [decode_solution](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.decode_solution.md) * [penalty](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.constraint.penalty.md) — alias of constructor of Constraint * [InequalityFormulation](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.InequalityFormulation.md) — ベースクラス: Enum ### その他のページ * [quantum_algorithm_table](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/quantum_algorithm_table.md) — 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 --- # Amplify SDK の特長 Amplify SDK のゴールは、**組合せ最適化問題をシンプルかつ直感的に定式化し、様々なマシンやソルバーを用いて求解を実行する**ことです。そのため、Amplify SDK は以下のような特長を持っています。 ## 🔰 直感的で使いやすい Amplify SDK は、組合せ最適化問題の中でも主に二次計画問題 (Quadratic Programming) に焦点を当てています。実数変数、整数変数、バイナリ変数 (0-1 変数)、イジング変数 ($\pm 1$ 変数) による多変数多項式で記述される数理最適化モデルの構築および求解が簡単かつ直感的に行えます。 一方で、各マシンやソルバーが対象とする最適化モデル (扱える変数の種類や多項式の次数、問題の種類) はマシンによって異なります。例えば、[量子アニーリングマシン](https://en.wikipedia.org/wiki/Quantum_annealing) は、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) と呼ばれるバイナリ変数 (またはイジング変数) による制約条件無しの二次計画問題を対象とします。また、Gurobi などの MIP ソルバーは実数変数や整数変数を扱うことができます。 Amplify SDK の持つユニークな特徴として、このようなマシンやソルバーの違いを可能な限り吸収し、**変数変換**、**次数下げ**、**制約条件の実装**、**ハードウェアトポロジーへの埋め込み** などの [**モデル変換**](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md)を**自動** で行うことで、直感的に組合せ最適化問題を定式化できることが挙げられます。ユーザはモデルの変換処理の詳細やマシンやソルバーの仕様について意識する必要がありません。特に、QUBO ソルバーを一般の数理最適化ソルバーのように扱うために豊富な機能が実装されていることは注目に値する点です。 ## 🚅 高速な数式処理 二次計画問題 (あるいはそれより高次) では、多項式の項数が変数の数のべき乗に比例して大きくなり得ます。一方で、最近のイジングマシンは求解可能な問題が10万変数規模にまで拡大しています。このような大規模な問題は数ギガバイトものデータ量が要求されることになり、数式処理の高速化とメモリ効率の向上が必須となります。 Amplify SDK は同種の定式化ソフトウェアと比較しても、**非常に高速**かつ**省メモリ**で処理するように設計されています。ベンチマーク結果は[定式化ベンチマーク](https://amplify.fixstars.com/ja/docs/amplify/v1/benchmark.md)を参照してください。これは、多項式の数式処理、モデル変換、マシンに送信するデータ構築などの Amplify SDK のコア機能が C++ で実装された高速なアルゴリズムと高度なチューニングによって提供されているためです。特に、Amplify SDK は多項式配列に対して [NumPy](https://numpy.org/doc/stable/index.html) と互換性のある配列プログラミング機能を提供しています。これらの機能を活用することにより非常に高速な数式処理が実現されます。 ## 🔱 複数のソルバーに対応 Amplify は以下のマシンとソルバーに対応しています。今後も対応マシンは増えていく見込みです。ソルバー開発者との連携や追加対応のリクエストを歓迎しますので是非ご連絡ください。 * [量子アニーリングマシン](https://en.wikipedia.org/wiki/Quantum_annealing) * [D-Wave](https://www.dwavesys.com/) * D-Wave Advantage2 * Leap's Hybrid BQM Solver * Leap's Hybrid CQM Solver * [Future Release] 量子モンテカルロ法によるソフトウェアシミュレータ (同梱) * イジングマシン・アニーリングマシン * [Fixstars Amplify](https://amplify.fixstars.com/) * [Amplify Annealing Engine](https://amplify.fixstars.com/engine/) * [Fujitsu Digital Annealer](https://www.fujitsu.com/global/services/business-services/digital-annealer/) * Fujitsu DA4 Solver * Fujitsu DA3c Solver * [TOSHIBA SQBM+](https://www.global.toshiba/jp/products-solutions/ai-iot/sbm.html) * TOSHIBA SQBM+ V2 * [NEC Vector Annealing Service](https://jpn.nec.com/nec-vector-annealing-service/) * NEC Vector Annealing 2.0 * [量子コンピュータ](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/index.md) * [AQT](https://www.aqt.eu/) * [IBM Quantum](https://quantum.cloud.ibm.com/) * [IonQ](https://ionq.com/) * [IQM](https://www.meetiqm.com/) * [Rigetti](https://www.rigetti.com/) * [QUDORA](https://qudora.com/) * [OQTOPUS](https://oqtopus-cloud.readthedocs.io/) * [Amazon Braket Simulator](https://aws.amazon.com/braket/) * [Qiskit Aer Simulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) * [Qulacs Simulator](http://docs.qulacs.org/) * MIP ソルバー * [Gurobi](https://www.gurobi.com/) ## 🧑‍💻️ 幅広い対象ユーザ Amplify は、組合せ最適化を利用するアプリケーション開発から定式化やマシンに対する学術研究利用まで、様々なユーザ層向けに設計されています。Amplify を組合せ最適化問題を求解するミドルウェアとして活用することで、短時間で組合せ最適化問題を実装することができます。 また、Amplify の特長である高レベルな **モデル変換機能** (変数変換、次数下げ、制約条件の実装など) は最先端の知見に基づいており、処理内容やアルゴリズムは全てドキュメントに記述されています。さらに、モデル変換処理のアルゴリズムやパラメータの変更、モデル変換の結果や処理時間の確認、低レベルインターフェースを利用したデバッグなども行えるように設計されています。そのため、組合せ最適化問題の定式化やマシンに対する学術研究を行うユーザは、Amplify の提供する機能を活用することで、自身の新たな定式化アルゴリズムの開発やソルバーの性能調査などを効率的に行うことができます。 ## 🐲 進化し続ける Fixstars Amplify Amplify の最初のバージョンは 2020年 7月にリリースされました。当初の Amplify は、D-Wave に代表される[量子アニーリングマシン](https://en.wikipedia.org/wiki/Quantum_annealing) とそれにインスパイアされた[イジングマシン](https://en.wikipedia.org/wiki/Quantum_annealing)のクラウドサービスを便利に使うソフトウェアとして、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) を前提とした数理モデルの構築を行うように設計されていました。 継続的に開発が進められる中で、Amplify がサポートとするマシンの拡大やマシンのアップデートによる機能拡充には、必ずしも [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) の枠組みにとらわれない、より柔軟な定式化への対応が行われてきました。また、数理最適化ソルバーとして代表的な Gurobi のサポートを追加したことや、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) であっても整数変数や実数変数を取り扱いたいという要望もあり、Amplify にはより一般的な数理計画モデルへの対応が求められるようになりました。 2024年にリリースした Amplify の新しいバージョン (v1系) では全ての仕様が見直され、より一般的な数理計画モデルの構築を行えるように再設計されました。もちろん、これまでのように Amplify SDK で [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) の定式化を行うことも可能ですが、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) の枠組みを超えた変数タイプや制約条件であっても、マシンやソルバーの有する求解機能に合わせ、自動的に最大限に性能を引き出せるようなモデル変換・パラメータチューニングが行われます。これにより、Amplify はより幅広いユーザや問題に対応できるようになりました。 --- # クイックスタート 次のいずれかの方法で Amplify SDK を実行できます。 **💻 自身のPCにインストールして実行する** この手順では自身のPCに Amplify SDK をインストールしてサンプルコードを実行します。 * PC に Python のインストールが必要です。 * ソルバーの実行には **Amplify Annealing Engine** の API トークンが必要です。 **☁️ BinderHub で試してみる** Amplify のチュートリアルページでサンプルコードを試すことができます。 * **Amplify Annealing Engine** の API トークンが無くても実行できます。 * ページの有効期限 (20分程度) が切れると、入力した内容や実行結果が破棄されます。 > [!NOTE] > > **注釈** > > サンプルコードの実行には *Amplify Annealing Engine* の API トークンが必要です。 > Amplify の[ユーザ登録](https://amplify.fixstars.com/register)を行うことで、誰でも無償で API トークンを取得できます。 ## インストール Amplify SDK は次の環境において動作を確認しています。 **Python バージョン** * 3.10 * 3.11 * 3.12 * 3.13 * 3.14 **サポート OS** * Windows 10/11 * Linux * Ubuntu 22.04/24.04/26.04, Rocky Linux 9.6/10.0 * x86_64, ARM64 * macOS * x86_64 (Monterey 以降) * ARM64 (Monterey 以降) 最初に、お使いの Python のバージョンが上記のリストに含まれることを確認してください。 ```bash $ python3 --version ``` Amplify SDK は [PyPI](https://pypi.org/project/amplify/) からインストールできます。次のコマンドで自身の環境にインストールされます。 ```bash $ python3 -m pip install -U amplify ``` > [!TIP] > > **ヒント** > > D-Wave のマシンを使う場合や Amplify Quantum を使う場合は、次のコマンドで追加のパッケージを含めてインストールしてください。 > > 詳細は [D-Wave Systems](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md) および [量子コンピュータ対応](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/index.md)を参照して下さい。 > > ```bash > # D-Wave のマシンを使う場合 > $ python3 -m pip install -U 'amplify[dwave]' > # Amplify Quantum を使う場合 > $ python3 -m pip install -U 'amplify[quantum]' > # すべての追加パッケージをインストールする場合 > $ python3 -m pip install -U 'amplify[full]' > ``` > > > [!WARNING] > > > > **注意** > > > > Python のバージョン, OSによっては追加パッケージが対応していないことがあります。 Amplify SDK が正しくインストールされると、次のようにしてインストールされたバージョンを確認できます。 ```python >>> import amplify >>> amplify.__version__ 1.6.3 ``` ## サンプルコードの実行 インストールが完了したら、Amplify を用いて簡単な QUBO の問題を解いてみましょう。ここではソルバーとして [Fixstars Amplify Annealing Engine](https://amplify.fixstars.com/engine) (以下 Amplify AE) を使います。Amplify AE のアカウントを持っていない場合は、[こちら](https://amplify.fixstars.com/register)から登録して、API トークンを取得してください。 サンプル問題として次を考えます。 **Sample QUBO Problem** **目的関数** $$ \text{minimize:} \quad f = q_0 q_1 + q_0 - q_1 + 1 $$ **決定変数** $$ q_0, q_1 \in \{0, 1\} $$ **制約条件** $$ \text{None} $$ 少し考えると、関数 $f$ は $q_0 = 0$, $q_1 = 1$ のときに最小値 $f = 0$ となることがわかります。この問題を Amplify で解いて正しい答えが得られるか確認しましょう。 ### 1. 変数配列の作成 組合せ最適化問題の解を Amplify SDK で得るためには **目的関数**、**決定変数**、**制約条件** をプログラムコード内で定義する必要があります。 まずは決定変数を定義します。上記のサンプル問題では 0 または 1 の値をとるバイナリ変数 $q_0$, $q_1$ が決定変数です。次のように、決定変数を発行する [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスを用いて、長さ 2 の変数配列 `q` を定義します。 ```pycon >>> from amplify import VariableGenerator >>> gen = VariableGenerator() # 決定変数のジェネレータを作成 >>> q = gen.array("Binary", 2) # 2つのバイナリ変数を持つ変数配列を作成 >>> print(q) [q_0, q_1] ``` ### 2. 目的関数の作成 次に、定義した変数を用いて目的関数を作成します。サンプル問題の目的関数 $f = q_0 q_1 + q_0 - q_1 + 1$ は、変数配列 `q` を用いて次のように定義できます。変数 $q$ の添え字が配列のインデックスに対応することに注意してください。 ```pycon >>> f = q[0] * q[1] + q[0] - q[1] + 1 >>> print(f) q_0 q_1 + q_0 - q_1 + 1 ``` 今回のサンプル問題には制約条件がないため、以上で定式化は完了です。 ### 3. ソルバークライアントの作成 今回はソルバーとして Amplify AE を使用するため、ソルバークライアントとして Amplify AE のクライアントクラス ([`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)) を作成します。 定式化した問題を Amplify AE に送信するために API トークンを設定する必要があります。これは、[`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) の [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.token) プロパティに API トークンを与えることで設定できます。加えて、ここではソルバーの実行時間を 1秒に設定しておきます。 ```pycon >>> from amplify import AmplifyAEClient >>> client = AmplifyAEClient() >>> client.token = "***input your token***" >>> client.parameters.time_limit_ms = 1000 # 実行時間を 1000 ミリ秒に設定 ``` ### 4. ソルバーの実行 ソルバーの実行は [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を用いて行います。この関数は定式化した問題とソルバークライアントを引数として受け取り、ソルバーの実行結果を返します。 ```pycon >>> from amplify import solve >>> result = solve(f, client) ``` ### 5. 結果の確認 実行結果は [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのインスタンスとして返されます。このインスタンスにはソルバーを実行した結果や行われたモデルの変換情報などが含まれます。使用するソルバーやパラメータの設定によって複数の解が含まれることがありますが、[`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) プロパティを呼び出すことで得られた解のうち最も良い解を [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスのインスタンスとして取得できます。[`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスには変数の値や目的関数の値が格納されています。 ```pycon >>> result.best.objective # 目的関数の値 0.0 >>> result.best.values # 変数の値 Values({Poly(q_0): 0, Poly(q_1): 1}) ``` 変数の値は決定変数とその値をキーと値に設定した辞書として扱える [`Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) クラスのインスタンスとして得られます。解を見やすくするために、変数配列の [`evaluate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドを用いて、配列要素の変数を [`Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) クラスの値で置き換えた配列が得られます。 ```pycon >>> print(f"{q} = {q.evaluate(result.best.values)}") [q_0, q_1] = [0. 1.] ``` 以上より、今回のサンプル問題の解が $q_0 = 0$, $q_1 = 1$ であることがわかりました。 ## 次のステップ 以上が Amplify SDK を用いた定式化とソルバー実行の流れです。ここでは非常に簡単な2変数の問題を扱いましたが、上記の手順はより複雑な問題に対しても同様に適用できます。 次のステップとして、Amplify で問題を解きながら学ぶ [チュートリアル](https://amplify.fixstars.com/ja/demo) を実行しましょう。 Amplify SDK の機能について詳しく知りたい方は引き続き [Amplify SDK の全体像](https://amplify.fixstars.com/ja/docs/amplify/v1/overview.md) に進んでください。 **☁️ 具体的な問題を解きたい** [**チュートリアルに進む**](https://amplify.fixstars.com/demo) **⏩ 機能を詳しく知りたい** [**Amplify SDK の全体像に進む**](https://amplify.fixstars.com/ja/docs/amplify/v1/overview.md) --- # 1. Amplify SDK の全体像 機能の詳細に触れる前に、Amplify SDK の全体像と実行手順をまとめます。 Amplify SDK では以下の (1) から (6) までの 6 つのステップに従って組合せ最適化問題の定式化を行い最適化を実行します。 ```mermaid %%{init:{'theme':'neutral'}}%% flowchart TB node_1("VariableGenerator") node_2("PolyArray") node_3("Poly") node_4("Constraint/ConstraintList") node_5("Model") node_6("Matrix") node_7("Result") node_8{{"solve(model, client)"}} node_20("ClientA / ClientB / ...") node_1 --> |"array()"| node_2 node_1 --> |"scalar()"| node_3 node_2 --> |"sum(),
(arithmetics)"| node_3 node_1 --> |"matrix()"| node_6 node_3 --> |"equal_to(),
less_equal(),
..."|node_4 node_3 --> node_5 node_4 --> node_5 node_6 --> node_5 node_5 --> node_8 node_20 ------> node_8 node_8 --> node_7 ``` **(1) 決定変数の生成** 最初に決定変数を生成するジェネレータ ([`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)) を作成します。 次に、変数ジェネレータから変数 ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) あるいは変数配列 ([`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)) を生成します。 定式化したい問題が二次計画問題である場合は、二次計画問題の係数行列 ([`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) を作ることもできます。 **(2) 目的関数の定義** 変数ジェネレータで生成した変数から目的関数を作成します。 多項式 ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) あるいは係数行列 ([`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) の形式で定義できます。 **(3) 制約条件の定義** 制約条件を作成するための関数を用いて多項式から制約条件 ([`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) を構築します。 複数の制約条件が必要である場合は、制約条件のリスト ([`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) にまとめます。 **(4) 最適化モデルの作成** 作成した目的関数と制約条件から最適化モデル ([`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) を作成します。 **(5) ソルバークライアントの作成** 実行するマシンまたはソルバーを指定し、ソルバークライアント (例: [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)) を作成します。 **(6) 最適化の実行** 最適化モデルとソルバークライアントを指定し、[`solve`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を通じて最適化を実行します。 実行結果は [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) として返され、最適解の値や最適解の変数の値を取得できます。 各ステップの詳細は以下のページで説明します。 **2. 決定変数の作り方** 定式化の最初のステップとして決定変数の作り方について解説します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/variables.md) **3. 多項式と目的関数** 目的の達成度を表す目的関数を表現する方法について解説します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/objective.md) **4. 制約条件の構築** 決定変数がとりうる範囲の制約の設定方法と多項式を用いた制約条件オブジェクトの構築を説明します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/constraint.md) **5. モデルの定式化** 組合せ最適化問題の定式化をプログラムコード上で表現する方法について解説します [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/model.md) **6. ソルバークライアント** 各ソルバーを抽象化したソルバークライアントの作成について解説します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md) **7. 組合せ最適化問題の求解** モデルとソルバークライアントを用いて組合せ最適化問題を求解する手順について解説します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/solve.md) --- # 2. 決定変数の作り方 Amplify SDK を使用して組合せ最適化問題を解くためには、問題の定式化をプログラムコード上で表現することが必要です。 このページでは、定式化の最初のステップとして、決定変数の生成について解説します。 > [!NOTE] > > **参考** > > 変数を発行する方法としては、このページで解説する [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスの [`scalar()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) および [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) メソッドのほかに [`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) メソッドが提供されています。 > 二次の目的関数を係数行列形式で作成したい場合はこのメソッドを用いることができます。詳細は「[係数行列による目的関数の作成](https://amplify.fixstars.com/ja/docs/amplify/v1/matrix.md)」を参照してください。 ## 2.1. 変数ジェネレータの作成 組合せ最適化問題の定式化を行うには、最初に [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスのインスタンスを作成することが必要です。このクラスは決定変数を発行するためのメソッドを提供します。 ```python from amplify import VariableGenerator gen = VariableGenerator() ``` ## 2.2. 変数の生成 [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスの [`scalar()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) メソッドを使うと、変数の種類を指定して新しい変数が発行できます。Amplify SDK で指定できる変数の種類は以下の表の通りです。 | 変数種別 | 詳細 | | --- | --- | | [`Binary`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Binary) | 0 または 1 の値をとる変数 | | [`Ising`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Ising) | -1 または 1 の値をとる変数 | | [`Integer`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Integer) | 整数値をとる変数 | | [`Real`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Real) | 実数値をとる変数 | 次のようにして新しくバイナリ変数を発行します。 変数は変数の多項式を表す [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスとして返されます。 ```pycon >>> q = gen.scalar("Binary") >>> print(q) q_0 ``` 発行される変数には自動で名前がつきますが、名前を指定することもできます。 ```pycon >>> i = gen.scalar("Ising", name="i") >>> print(i) i ``` 整数変数または実数変数には取り得る値の範囲を指定できます。 ```pycon >>> x = gen.scalar("Real", bounds=(2.0, 3.0)) >>> print(x) x_0 ``` ## 2.3. 変数配列の作成 複数個の変数を一括で生成したい場合、[`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) の [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) メソッドを使うことができます。 このメソッドは、NumPy-like な多次元配列形式で変数の配列を返します。 次のようにして 3 個のバイナリ変数からなる配列を作成します。新たに 3 個の変数が発行され、変数名には自動で配列のインデックスを表す文字列が付きます。 ```pycon >>> gen = VariableGenerator() >>> q = gen.array("Binary", 3) >>> print(q) [q_0, q_1, q_2] ``` Python の [`list`](https://docs.python.org/3/library/stdtypes.html#list) や 1 次元 NumPy 配列と同様にして要素やスライスを取得することができます。 ```pycon >>> print(q[0]) q_0 ``` ```pycon >>> print(q[:2]) [q_0, q_1] ``` [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) の [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) メソッドは多次元の配列も作成することができます。以下の例では、 $2 \times 3$ の 2 次元変数配列を作成します。 ```pycon >>> gen = VariableGenerator() >>> q = gen.array("Binary", shape=(2, 3)) >>> print(q) [[q_{0,0}, q_{0,1}, q_{0,2}], [q_{1,0}, q_{1,1}, q_{1,2}]] ``` 2 次元の [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) と同様にして要素やスライスを取得することができます。取得される要素やスライスは、もとの配列のビューとなります。 ```pycon >>> print(q[0, 0]) q_{0,0} ``` ```pycon >>> print(q[0, :]) [q_{0,0}, q_{0,1}, q_{0,2}] ``` ```pycon >>> print(q[:, 0]) [q_{0,0}, q_{1,0}] ``` 変数の下限値と上限値は発行時に一括で指定することができます。 ```pycon >>> n = gen.array("Integer", shape=(5,), bounds=(1, 3)) >>> print(n) [n_0, n_1, n_2, n_3, n_4] ``` > [!NOTE] > > **参考** > > [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) メソッドは多項式配列を表す [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスのインスタンスを返します。 > [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスには要素の取得やスライス以外にも [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) と互換性のあるさまざまなメソッドが提供されています。 > 詳細は[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスの[リファレンス](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)を参照してください。 ## 2.4. 変数情報の取得 発行した変数から変数の情報を取得するには、[`as_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) メソッドを使います。 ```python gen = VariableGenerator() q = gen.scalar("Binary") i = gen.scalar("Ising", name="i") x = gen.scalar("Real", bounds=(2.0, 3.0)) ``` ```pycon >>> print(q.as_variable()) {name: q_0, id: 0, type: Binary} ``` 変数の情報は [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) クラスのインスタンスとして提供されます。[`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) クラスの持つアトリビュートは以下の通りです。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`name`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.name) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 変数名 | | [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) | [`int`](https://docs.python.org/3/library/functions.html#int) | 変数の識別番号 発行された順に0 から始まる整数値が割り当てられます | | [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.type) | [`VariableType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) | 変数の種類 | | [`lower_bound`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.lower_bound) | [`float`](https://docs.python.org/3/library/functions.html#float) | [整数変数または実数変数のみ] 変数の下限値 [`None`](https://docs.python.org/3/library/constants.html#None) は $- \inf$ を意味する | | [`upper_bound`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.upper_bound) | [`float`](https://docs.python.org/3/library/functions.html#float) | [整数変数または実数変数のみ] 変数の上限値 [`None`](https://docs.python.org/3/library/constants.html#None) は $+ \inf$ を意味する | [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) クラスから [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスに逆変換することも可能です。 ```pycon >>> from amplify import Poly >>> v = x.as_variable() >>> print(Poly(v)) x_0 ``` また、[`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスが発行した変数の情報は [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.variables) プロパティで取得できます。 ```pycon >>> vars = gen.variables >>> vars [Variable({name: q_0, id: 0, type: Binary}), Variable({name: i, id: 1, type: Ising}), Variable({name: x_0, id: 2, type: Real, lower_bound: 2, upper_bound: 3})] ``` 変数の名前、下限値、上限値については後から変更することも可能です。 ```python vars[2].name = "r" vars[2].lower_bound = 0.0 vars[2].upper_bound = 1.0 ``` ```pycon >>> print(vars[2]) {name: r, id: 2, type: Real, lower_bound: 0, upper_bound: 1} ``` > [!WARNING] > > **注意** > > [`scalar()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) メソッドなどにより発行される変数は [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスです。 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスは単一の変数だけでなく一般の多項式も表現できますが、[`as_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) メソッドは [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスが単項の変数を表すときのみ成功することに注意してください。 > [!TIP] > > **Tip** > > 簡便のために、[`is_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) メソッドが [`True`](https://docs.python.org/3/library/constants.html#True) を返す場合 ([`as_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) メソッドが成功する場合) は、[`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) クラスのアトリビュートに直接アクセスできます。 > > ```pycon > >>> q.is_variable() > True > >>> q.name > 'q_0' > >>> q.id > 0 > >>> print(q.type) > Binary > ``` > [!TIP] > > **Tip** > > 任意の [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスに対して、そのインスタンスに含まれるすべての変数の情報を [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) プロパティにより取得することができます。[`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスの詳細は「[多項式と目的関数](https://amplify.fixstars.com/ja/docs/amplify/v1/objective.md)」を参照してください。 > > ```pycon > >>> q.variables > [Variable({name: q_0, id: 0, type: Binary})] > ``` > > なお、各クラスのインスタンスから [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) クラスを取得するメソッドまたはアトリビュートは以下のようなものがあります。 > > * [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) > > * [`get_variables()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.get_variables) > * [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.variables) > * [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) > > * [`as_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) > * [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) > * [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) > > * [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.variables) --- # 3. 多項式と目的関数 目的関数は組合せ最適化問題における目的の達成度を表す数式です。Amplify SDK では**最小化したい多項式**のことを指します。このページでは、Amplify SDK を用いて多項式を表現する方法について解説します。 > [!TIP] > > **Tip** > > 多項式を**最大化**したい組合せ最適化問題を解きたい場合は、その目的関数を -1 倍することで最小化問題に変換することができ、 Amplify SDK による最適化が可能となります。 > [!NOTE] > > **参考** > > 目的関数を表現する別の方法として、多項式の係数からなる多次元配列を用いる方法も用意されています。 > この方法は、目的関数が $x^\top Q x + p^\top x + c$ と表されるような実数値の 2 次元配列 $Q$ と実数ベクトル $p$ がすでに計算されている場合などに便利となります。詳細は「[係数行列による目的関数の作成](https://amplify.fixstars.com/ja/docs/amplify/v1/matrix.md)」を参照してください。 ## 3.1. 多項式の構築 組合せ最適化問題の目的関数や制約条件式を表現するために、多項式クラス [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) が用意されています。 前節で [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) クラスを使って発行した変数も、[`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) のインスタンスとなっています。 [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) により作成した変数に対して四則演算や冪乗を行うことで、簡単に任意の多項式を作成することができます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", 6) p = -q[0] + 2.3 * q[1] * q[2] - (q[3] + q[4]) ** 2 * q[5] ``` ```pycon >>> print(p) - 2 q_3 q_4 q_5 + 2.3 q_1 q_2 - q_3 q_5 - q_4 q_5 - q_0 ``` > [!TIP] > > **Tip** > > 以下で定義される論理演算子も実装されています。これは、単一のバイナリ変数など、0 または 1 の値しかとらないことが分かっている多項式から制約条件を作る場合に便利です。 > > | 演算子 | 効果 | > | --- | --- | > | `&` (論理積) | `x & y` は `x * y` と等価 | > | `|` (論理和) | `x | y` は `-x * y + x + y` と等価 | > | `^` (排他的論理和) | `x ^ y` は `-2 * x * y + x + y` と等価 | 同じ [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) から作成された変数であれば、異なる変数配列の変数や、種類の異なる変数を同じ多項式に含めることもできます。 ```python gen = VariableGenerator() q = gen.array("Binary", 3) s = gen.array("Ising", 2) n = gen.scalar("Integer", bounds=(-1, 2)) p = q[0] + s[1] - 2 * n ``` ```pycon >>> print(p) q_0 + s_1 - 2 n_0 ``` > [!WARNING] > > **注意** > > 異なる [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) のインスタンスから発行された変数同士を組み合わせて目的関数や制約条件を作成することはできません。 > 1つの定式化には、共通の [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) のインスタンスから発行された変数を使用する必要があります。 作成した多項式は、そのまま目的関数として利用することができます。したがって、たとえば目的関数が $q_0 q_1 - q_2$ であるとき、目的関数は以下のように表現できます。 ```python gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] ``` ## 3.2. 多項式配列を用いた多項式の構築 > [!NOTE] > > **注釈** > > この節で解説する内容は、 NumPy ライブラリにある程度なじみがある方を対象としています。 > > 多項式配列クラスの持つ配列演算を用いると多項式の生成が高速になり、NumPy ライブラリに慣れ親しんでいる方にとっては直感的になります。ただし、上記で解説した方法で既に任意の多項式を作成することができるため、この節は必要に応じて読み飛ばしても構いません。 多項式の構築をより簡単で高速にするために、多項式の配列を表すクラスとして [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスが用意されています。 [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスは NumPy-like な多次元配列であり、NumPy の [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) 配列と互換性のある多くのメソッドが実装されています。 前節で [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) の [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) により作成された変数配列は[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) のインスタンスです。 次の例では 3x3 の変数配列を作成します。NumPy の多次元配列と全く同様にして、変数配列の形状 [`shape`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.shape) や次元数 [`ndim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.ndim) を表すアトリビュートが取得できます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", shape=(3, 3)) ``` ```pycon >>> q.shape (3, 3) >>> q.ndim 2 ``` 配列要素を取得するには、NumPy 配列と同様にインデックスを指定します。 ```pycon >>> print(q[0, 0]) q_{0,0} ``` スライスを活用した部分配列の取得も可能です。部分配列はコピーではなくビューを返します。 ```pycon >>> print(q[1:3, 0:2]) [[q_{1,0}, q_{1,1}], [q_{2,0}, q_{2,1}]] >>> print(q[0, ::-1]) [q_{0,2}, q_{0,1}, q_{0,0}] >>> print(q[..., 0]) [q_{0,0}, q_{1,0}, q_{2,0}] ``` [`sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.sum) は多項式配列から多項式を作成する際に便利なメソッドの1つです。 * 全ての変数の和を計算する: ```pycon >>> print(q.sum()) q_{0,0} + q_{0,1} + q_{0,2} + q_{1,0} + q_{1,1} + q_{1,2} + q_{2,0} + q_{2,1} + q_{2,2} ``` * 行ごとに和を計算する: ```pycon >>> print(q.sum(axis=1)) [q_{0,0} + q_{0,1} + q_{0,2}, q_{1,0} + q_{1,1} + q_{1,2}, q_{2,0} + q_{2,1} + q_{2,2}] ``` * 列ごとに和を計算する: ```pycon >>> print(q.sum(axis=0)) [q_{0,0} + q_{1,0} + q_{2,0}, q_{0,1} + q_{1,1} + q_{2,1}, q_{0,2} + q_{1,2} + q_{2,2}] ``` 数値や numpy 配列との四則演算も可能です。 ```pycon >>> print(2 * q) [[2 q_{0,0}, 2 q_{0,1}, 2 q_{0,2}], [2 q_{1,0}, 2 q_{1,1}, 2 q_{1,2}], [2 q_{2,0}, 2 q_{2,1}, 2 q_{2,2}]] ``` ```pycon >>> import numpy as np >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> print(q * a) [[ q_{0,0}, 2 q_{0,1}, 3 q_{0,2}], [4 q_{1,0}, 5 q_{1,1}, 6 q_{1,2}], [7 q_{2,0}, 8 q_{2,1}, 9 q_{2,2}]] ``` > [!NOTE] > > **参考** > > 上記以外にも、[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスには、ブロードキャストや行列積、[`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) 関数など様々な機能やメソッドが用意されています。 > 全ての機能については [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスの[リファレンス](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md)を参照してください。 > NumPy 互換のメソッドの効果については、[`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) を参照してください。 ## 3.3. 多項式のプロパティとメソッド この節では、多項式の情報の取得や変更のための [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのメソッドやプロパティを紹介します。 多項式の次数を知るには [`degree()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.degree) メソッドを用います。 また、[`is_number()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_number), [`is_linear()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_linear), [`is_quadratic()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_quadratic) メソッドを使用することで、 多項式が特定の次数以下であるかどうかを判定できます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", 4) ``` ```pycon >>> p = q[0] * q[1] >>> p.degree() 2 >>> p.is_number() False >>> p.is_linear() False >>> p.is_quadratic() True ``` [`is_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) メソッドにより、多項式が 1 つの変数と見なせるかどうか、つまり、係数が 1 の 1 次元単項式であるかどうかをチェックすることができます。特に、[`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) により生成されたスカラー変数や変数配列の要素に対して、[`is_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) は [`True`](https://docs.python.org/3/library/constants.html#True) を返します。 ```pycon >>> q[0].is_variable() True >>> (q[0] + 1).is_variable() False >>> (2 * q[0]).is_variable() False ``` [`is_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) が [`True`](https://docs.python.org/3/library/constants.html#True) を返すとき、変数の名前 [`name`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.name) や種類 [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.type) といったプロパティが有効になります。 ```pycon >>> q[0].name 'q_0' >>> print(q[0].type) Binary ``` > [!NOTE] > > **参考** > > [`name`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.name) や [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.type) など、多項式に含まれる変数の詳細情報に関する解説は「[変数情報の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/variables.md#variable-info)」を参照してください。 多項式に含まれるすべての変数の情報は、 [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) プロパティにより得ることができます。 ```pycon >>> (q[0] + 2 * q[1]).variables [Variable({name: q_0, id: 0, type: Binary}), Variable({name: q_1, id: 1, type: Binary})] ``` [`substitute()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.substitute) メソッドを使うと、多項式の変数に数値や別の多項式を代入した結果を得ることができます。 このメソッドは 1 つの [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) を引数にとり、[`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスを返します。引数のキーは 1 つの変数と見なせる [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) または [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) である必要があり、値は [`float`](https://docs.python.org/3/library/functions.html#float) または [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) である必要があります。 ```pycon >>> p = q[0] + q[1] >>> print(p.substitute({q[0]: 1, q[1]: 0})) 1 >>> print(p.substitute({q[0]: 1})) q_1 + 1 >>> print(p.substitute({q[1]: q[2] * q[3]})) q_2 q_3 + q_0 >>> v = p.variables >>> print(p.substitute({v[0]: 1, v[1]: 0})) 1 ``` > [!TIP] > > **Tip** > > 多項式配列に含まれるすべての多項式に対して一括で代入を行いたい場合は、多項式配列 [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) の [`substitute()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.substitute) メソッドを用いることができます。 > > ```pycon > >>> print(q) > [q_0, q_1, q_2, q_3] > >>> print(q.substitute({q[0]: 1, q[1]: 0})) > [ 1, 0, q_2, q_3] > >>> print(q.substitute({q[1]: q[2] * q[3]})) > [ q_0, q_2 q_3, q_2, q_3] > ``` --- # 4. 制約条件の構築 **制約条件** とは、組合せ最適化問題において決定変数の値がみたすべき条件のことです。Amplify SDK では、各変数がとりうる範囲の制約と、多項式がとりうる範囲に関する制約をそれぞれ設定することができます。 このページでは、決定変数への制約の設定方法と、多項式を用いた制約条件オブジェクトの構築を説明します。 ## 4.1. 変数の値を固定する 定式化において一部の決定変数の値が事前に決まっている場合など、決定変数の値を固定しておきたいことがあります。以下のように事前に変数配列の一部を数値で置き換えることで、実質的に変数の値を固定することができます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", shape=(3, 3)) q[0, :] = 0 q[:, 0] = 0 q[0, 0] = 1 ``` > [!NOTE] > > **Alternative** > > 上記の `q` に数値を代入する部分は以下のように書いても同じ効果があります。ただし、上記の書き方のほうが一般に高速です。 > > ```python > for i in range(3): > q[i, 0] = 0 > for j in range(3): > q[0, j] = 0 > q[0, 0] = 1 > ``` ```pycon >>> print(q) [[ 1, 0, 0], [ 0, q_{1,1}, q_{1,2}], [ 0, q_{2,1}, q_{2,2}]] ``` その後、`q` を用いて多項式を組み立てることで、固定された変数の値を含む多項式を作成できます。 ```pycon >>> p = q.sum() >>> print(p) q_{1,1} + q_{1,2} + q_{2,1} + q_{2,2} + 1 ``` ある変数が別の変数を用いた多項式で表されるという制約も、変数配列を多項式で置き換えることで実現できます。たとえば、$q_{1, 1} = q_{2, 2}$ という制約を表現したい場合、以下のようにします。 ```pycon >>> q[2, 2] = q[1, 1] >>> print(q) [[ 1, 0, 0], [ 0, q_{1,1}, q_{1,2}], [ 0, q_{2,1}, q_{1,1}]] ``` > [!TIP] > > **Tip** > > 書き換え前の変数配列 `q` を再利用する場合はコピーしておくと良いでしょう。 > > ```python > gen = VariableGenerator() > q_org = gen.array("Binary", shape=(3, 3)) > q = q_org.copy() > > q[0, :] = 0 > q[:, 0] = 0 > q[0, 0] = 1 > ``` > > ```pycon > >>> print(q_org) > [[q_{0,0}, q_{0,1}, q_{0,2}], > [q_{1,0}, q_{1,1}, q_{1,2}], > [q_{2,0}, q_{2,1}, q_{2,2}]] > ``` ## 4.2. 変数の値の範囲を設定する 整数変数と実数変数では、変数の値の取りうる範囲を [`float`](https://docs.python.org/3/library/functions.html#float) または [`None`](https://docs.python.org/3/library/constants.html#None) で設定できます。[`None`](https://docs.python.org/3/library/constants.html#None) が指定された場合、非有界であることを表します。 変数を発行する際にまとめて範囲を設定するには、[`scalar()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar), [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array), [`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) の各メソッドの `bounds` パラメータに変数の値の取りうる範囲を設定します。 ```pycon >>> n = gen.array("Integer", shape=(5,), bounds=(1, 3)) >>> print(n[0].as_variable()) {name: n_0, id: 9, type: Integer, lower_bound: 1, upper_bound: 3} ``` 個別の変数に範囲を指定する場合は、[`lower_bound`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.lower_bound), [`upper_bound`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.upper_bound) アトリビュートに指定します。 ```pycon >>> n[0].lower_bound = 0 >>> n[0].upper_bound = None >>> print(n[0].as_variable()) {name: n_0, id: 9, type: Integer, lower_bound: 0, upper_bound: inf} ``` ## 4.3. 多項式の値を制約する Amplify SDK では多項式の値がとりうる範囲の制約を表す等式・不等式などを [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) クラスの制約条件オブジェクトとして管理します。制約条件オブジェクトを利用することで、マシンやソルバーの実行結果から制約条件を満たす解を抽出したり、制約条件を満たさない場合にはどの制約条件が守れなかったのかを判定できます。 また、制約条件オブジェクトは、 [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーのような制約条件を直接扱えないソルバー向けに、ペナルティ関数を生成する機能も備えています。ペナルティ関数とは、制約条件を持つ組合せ最適化問題をペナルティ法という方法を用いて制約条件のない問題に変換するときに、それぞれの制約条件に対して計算される多項式のことです。 制約条件の構築には制約条件の種類ごとに提供されるヘルパー関数を用いると便利です。自動で制約条件式を解析し、最適化されたペナルティ関数が生成されます。 > [!NOTE] > > **注釈** > > ペナルティ関数の生成が必要ない場合についても、ヘルパー関数を使うことによるデメリットはありませんので、ヘルパー関数をお使いください。 > [!NOTE] > > **参考** > > 生成されるペナルティ関数の詳細や重みの調整に関しては「[制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md)」を参照してください。また、ヘルパー関数を使わずに自身でペナルティ関数を指定する方法は「[ペナルティ関数の指定](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#specify-penalty)」を参照してください。 ### 4.3.1. 等式制約 等式を表す制約条件オブジェクトの作成には、次のヘルパー関数が利用できます。 | ヘルパー関数 | 効果 | | --- | --- | | [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) | 多項式が右辺と等しいことを制約する | | [`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) | 多項式が 1 と等しいことを制約する | 与えられた多項式を等式で制約するには、[`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) 関数を用います。次の例では、二次元の変数配列 $q$ に対して、$q_{0,0} + q_{1,1} + q_{2,2} = 1$ を満たすような制約条件オブジェクトを作成しています。 ```python from amplify import VariableGenerator, equal_to, one_hot gen = VariableGenerator() q = gen.array("Binary", shape=(3, 3)) c = equal_to(q[0, 0] + q[1, 1] + q[2, 2], 1) ``` ```pycon >>> print(c) q_{0,0} + q_{1,1} + q_{2,2} == 1 (weight: 1) ``` 制約条件にはラベルを付けることができます。ラベルを付けておくと後に制約条件の評価結果を確認する際の識別に役立ちます。後から変更することも可能です。 ```pycon >>> c = equal_to(q[0, 0] + q[1, 1] + q[2, 2], 1, label="diagonal sum") >>> print(c) diagonal sum: q_{0,0} + q_{1,1} + q_{2,2} == 1 (weight: 1) >>> c.label = "diagonal sum (I should give a long name to this!)" >>> print(c) diagonal sum (I should give a long name to this!): q_{0,0} + q_{1,1} + q_{2,2} == 1 (weight: 1) ``` ヘルパー関数に多項式配列 [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) を渡すことで、配列要素の和が制約されます。 ```pycon >>> c = equal_to(q[0], 1, label="1st row sum") >>> print(c) 1st row sum: q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1) ``` これは以下と等価です。 ```python c = equal_to(q[0].sum(), 1, label="1st row sum") ``` [`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数は右辺が 1 の等式制約を作成します。それ以外は [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) 関数と同じです。 ```pycon >>> c = one_hot(q[0], label="1st row one-hot") >>> print(c) 1st row one-hot: q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1) ``` これは以下と等価です。 ```python c = equal_to(q[0], 1, label="1st row one-hot") ``` > [!NOTE] > > **注釈** > > 実数変数や実数係数を含む多項式に対する等式制約は数値誤差の影響を受け、充足判定を誤る可能性があります。 > > 特に、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーなど実数変数を扱えないソルバーでは、実数変数を少数のバイナリ変数に変換するために、本質的に正しく等式制約を表現できないことがあります (実数変数からバイナリ変数への変換については「[実数変数からバイナリ変数への変換](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md#encode-real)」を参照してください)。 > > このような場合、等式制約の代わりに、許容できる誤差を与えて不等式制約で表現することを検討してください。 ### 4.3.2. 不等式制約 不等式を表す制約条件オブジェクトの作成には、次のヘルパー関数が利用できます。 | ヘルパー関数 | 効果 | | --- | --- | | [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) | 多項式が右辺より小さいか等しいことを制約する | | [`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) | 多項式が右辺より大きいか等しいことを制約する | | [`clamp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) | 多項式が範囲に含まれることを制約する | [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) と [`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) は [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) と同様に、第一引数には多項式または多項式配列を与え、第二引数には右辺を与えます。 ```python from amplify import less_equal, greater_equal c_le = less_equal(q[0], 2) c_ge = greater_equal(q[0], 2) ``` ```pycon >>> print(c_le) q_{0,0} + q_{0,1} + q_{0,2} <= 2 (weight: 1) >>> print(c_ge) q_{0,0} + q_{0,1} + q_{0,2} >= 2 (weight: 1) ``` [`clamp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) は多項式が範囲に含まれることを制約します。範囲は [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple) で指定します。 ```python from amplify import clamp c_bw = clamp(q[0], (1, 2)) ``` ```pycon >>> print(c_bw) 1 <= q_{0,0} + q_{0,1} + q_{0,2} <= 2 (weight: 1) ``` 範囲の下限と上限が等しい場合は等式制約として扱われます。 ```pycon >>> c_bw = clamp(q[0], (2, 2)) >>> print(c_bw) q_{0,0} + q_{0,1} + q_{0,2} == 2 (weight: 1) ``` これは以下と等価です。 ```python c_bw = equal_to(q[0], 2) ``` 下限または上限が [`None`](https://docs.python.org/3/library/constants.html#None) の場合はそれぞれ [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) と [`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) と等価です。 ```pycon >>> c_le = clamp(q[0], (None, 2)) >>> print(c_le) q_{0,0} + q_{0,1} + q_{0,2} <= 2 (weight: 1) ``` ```pycon >>> c_ge = clamp(q[0], (2, None)) >>> print(c_ge) q_{0,0} + q_{0,1} + q_{0,2} >= 2 (weight: 1) ``` > [!WARNING] > > **注意** > > [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーにおける不等式制約のペナルティ関数の生成には補助変数が必要となるため、非効率なことや厳密な定式化が出来ないことがあります。詳細は「[制約条件とペナルティ関数 - 不等式制約](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#ineq-penalty)」を参照してください。 ### 4.3.3. 制約条件リスト 複数の制約条件を扱いたい場合、制約条件リスト [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) を用います。制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) 同士を加算することで、制約条件リストにすることができます。 ```python from amplify import VariableGenerator, equal_to gen = VariableGenerator() q = gen.array("Binary", shape=(3, 3)) ``` ```pycon >>> c0 = equal_to(q[0], 1) >>> c1 = equal_to(q[1], 1) >>> clist = c0 + c1 >>> print(clist) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1)] ``` また、[`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) を作成した後に、`+` または `+=` 演算子で制約条件オブジェクトを追加することもできます。 ```pycon >>> clist += equal_to(q[2], 1) >>> print(clist) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1), q_{2,0} + q_{2,1} + q_{2,2} == 1 (weight: 1)] ``` 多項式の配列に対して、複数の制約条件オブジェクトを一気に作成することもできます。ヘルパー関数に `axis` パラメータを与えると、多項式配列の軸に沿った和が計算され、各計算結果に対して制約条件オブジェクトを作成します。 次の例は各行の和がそれぞれ 1 であるような制約条件リスト [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) を作成しています。ラベルが指定された場合、指定された文字列の後ろに自動で数字がつきます。 ```pycon >>> clist = equal_to(q, 1, axis=1, label="row sum") >>> print(clist) [row sum0: q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1), row sum1: q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1), row sum2: q_{2,0} + q_{2,1} + q_{2,2} == 1 (weight: 1)] ``` > [!TIP] > > **ヒント** > > 可能な限り `axis` パラメータを用いた制約条件の一括作成を行うと効率的です。 ### 4.3.4. 制約条件の重みを設定する [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) 関数や [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) 関数などを用いて作成した制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) には、重みを設定することができます。これは主に QUBO ソルバーまたはイジングソルバーで有効なパラメータで、重みが強ければ強いほど制約条件を満たす解が見つかりやすくなります。ただし、制約条件の重みが強すぎる場合、目的関数の値が小さな解を見つけにくくなる傾向があります。 > [!NOTE] > > **参考** > > 制約条件の重みの設定は、ペナルティ関数を用いて制約条件を表現するソルバーを用いる場合に必要です。ペナルティ関数と重みの調整方法に関しては [ペナルティ関数の重み](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-weight) を参照してください。 制約条件の重みは、[`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) プロパティにより取得・設定できます。デフォルト値は 1 です。 ```python from amplify import VariableGenerator, equal_to gen = VariableGenerator() q = gen.array("Binary", shape=(3, 3)) c = equal_to(q[0, 0] + q[1, 1] + q[2, 2], 1) ``` ```pycon >>> c.weight 1.0 >>> c.weight = 3 >>> c.weight 3.0 ``` 制約条件オブジェクトに数値を掛けると、[`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) に乗算されます。 ```pycon >>> c.weight 3.0 >>> c *= 2 >>> c.weight 6.0 ``` 制約条件リスト [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) オブジェクトに対しても数値との乗算が定義されています。 ```python c1 = equal_to(q[0], 1) c2 = equal_to(q[1], 1) clist = c1 + c2 ``` ```pycon >>> print(clist) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1)] >>> clist *= 2 >>> print(clist) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 2), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 2)] ``` ### 4.3.5. ドメインウォール制約 Amplify SDK では一部の特殊な制約条件の作成をヘルパー関数でサポートしています。 > [!NOTE] > > **注釈** > > 多くの場合、定式化には上記で解説した等式・不等式制約を作成する機能を使用すれば十分です。以下で解説する機能は、特殊な制約条件の定式化が必要な人が利用してください。 ドメインウォール制約は、一次元のバイナリ変数またはイジング変数の変数配列に対して、左から 0 (イジング変数の場合は -1) が 0 個以上続いたあと 1 が 0 個以上続くように制約します。例えば、バイナリ変数配列 `q = [q_0, q_1, q_2, q_3]` に対して、`q = [0, 0, 0, 0]` や `q = [0, 1, 1, 1]` は制約を満たしますが、`q = [0, 1, 1, 0]` は制約を満たしません。 ドメインウォール制約を作成するには、[`domain_wall()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) 関数に変数配列を渡します。 ```python from amplify import domain_wall gen = VariableGenerator() q = gen.array("Binary", 4) dw = domain_wall(q) ``` 変数配列がバイナリ変数の場合、ドメインウォール制約の制約条件式は、 $$ \sum_{i=0}^{n-2} q_i - q_i q_{i+1} = 0 $$ となります。これは、隣り合う変数の間で $1 \rightarrow 0$ と変化する変数の個数が 0 となる制約と解釈できるからです。プログラムコード上では以下のようにして確認できます。 ```pycon >>> print(dw) - q_0 q_1 - q_1 q_2 - q_2 q_3 + q_0 + q_1 + q_2 == 0 (weight: 1) ``` > [!NOTE] > > **注釈** > > ドメインウォール制約の制約条件式は等式で表されますが、[`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) 関数にこの制約条件式の両辺を与えて構築される制約条件と [`domain_wall()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) 関数を用いて構築される制約条件は等価ではありません。これは、制約条件が生成するペナルティ関数が異なるためであり、[`domain_wall()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) 関数を用いて構築された制約条件の方が効率的です。ペナルティ関数の詳細については、[制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md) を参照してください。 イジング変数配列の場合、隣り合う変数の間で $+1 \rightarrow -1$ と変化する変数の個数が 0 となる制約が生成されます。 ```python gen = VariableGenerator() s = gen.array("Ising", 4) dw = domain_wall(s) ``` 制約条件式は、 $$ \frac{1}{4} \sum_{i=0}^{n-2} s_i - s_{i + 1} - s_i s_{i+1} + 1 = 0 $$ となります。これは次の通り確認されます。 ```pycon >>> print(dw) - 0.25 s_0 s_1 - 0.25 s_1 s_2 - 0.25 s_2 s_3 + 0.25 s_0 - 0.25 s_3 + 0.75 == 0 (weight: 1) ``` > [!TIP] > > **Tip** > > 値の変化の方向を逆にするには [`domain_wall()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) 関数の `ascending` パラメータに [`False`](https://docs.python.org/3/library/constants.html#False) を設定します。この場合は、バイナリ変数配列 `q = [q_0, q_1, q_2, q_3]` に対して、`q = [0, 0, 0, 0]` や `q = [1, 1, 1, 0]` は制約を満たしますが、`q = [0, 0, 1, 1]` は制約を満たさないことになります。 --- # 5. モデルの定式化 組合せ最適化問題は、決定変数と目的関数、制約条件からなります。 「[2. 決定変数の作り方](https://amplify.fixstars.com/ja/docs/amplify/v1/variables.md)」、「[3. 多項式と目的関数](https://amplify.fixstars.com/ja/docs/amplify/v1/objective.md)」、「[4. 制約条件](https://amplify.fixstars.com/ja/docs/amplify/v1/constraint.md)」では、 決定変数は [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) を用いて作成することができ、 目的関数と制約条件は [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) と [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) によって表現することができることを解説しました。 このページでは、これらを組み合わせて、組合せ最適化問題をプログラムコード上で表現する方法について解説します。 > [!NOTE] > > **参考** > > [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのほかに係数行列形式 [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスのインスタンスも目的関数として使用することができます。 目的関数が [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) として表現されている場合も、このページで解説する内容と全く同様に使用することができます。 > > 係数行列形式についての詳細は「[係数行列による目的関数の作成](https://amplify.fixstars.com/ja/docs/amplify/v1/matrix.md)」を参照してください。 ## 5.1. モデルの構築 Amplify SDK において、組合せ最適化問題は [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) クラスのインスタンスとして表現されます。 目的関数と制約条件が両方ある組合せ最適化問題を表現するには、目的関数を表す [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) と制約条件を表す [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) または [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) を加算するのが簡単な方法です。 ```python from amplify import VariableGenerator, Model, equal_to, one_hot gen = VariableGenerator() q = gen.array("Binary", shape=(2, 3)) objective = q[0, 0] * q[0, 1] - q[0, 2] constraint1 = equal_to(q[0, 0] + q[0, 1] - q[0, 2], 0) constraint2 = one_hot(q[1, :]) constraint_list = constraint1 + constraint2 ``` * 目的関数と制約条件を足してモデルを構築する: ```pycon >>> model = objective + constraint1 >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) ``` * 目的関数と制約条件リストを足してモデルを構築する: ```pycon >>> model = objective + constraint_list >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1) ``` 目的関数のみまたは制約条件のみからなる組合せ最適化問題を表現するには、 [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) クラスのコンストラクタに、目的関数を表す [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) (または [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) のインスタンス、あるいは制約条件を表す [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) または [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) のインスタンスを渡します。 * 目的関数 ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) からモデルを構築する: ```pycon >>> model = Model(objective) >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} ``` * 単一の制約条件オブジェクト ([`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) からモデルを構築する: ```pycon >>> model = Model(constraint1) >>> print(model) minimize: 0 subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) ``` * 複数の制約条件オブジェクト ([`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) からモデルを構築する: ```pycon >>> model = Model(constraint_list) >>> print(model) minimize: 0 subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1) ``` モデルを構築したあとで、制約条件 ([`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) または [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) を追加することもできます。 ```pycon >>> model = Model(objective) >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} >>> model += constraint1 >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) ``` モデルが目的関数を多項式 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのインスタンスで持つ場合には、目的関数の加算と減算も可能です。 ```pycon >>> model += q[0, 0] * q[0, 1] >>> print(model) minimize: 2 q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) ``` ```pycon >>> model -= q[0, 0] >>> print(model) minimize: 2 q_{0,0} q_{0,1} - q_{0,0} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) ``` ## 5.2. モデルのアトリビュート [`objective`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.objective) プロパティにより、[`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) クラスが持っている目的関数を取得することができます。 ```python from amplify import VariableGenerator, equal_to gen = VariableGenerator() q = gen.array("Binary", 2, 3) objective = q[0,0] * q[0,1] - q[0,2] constraint = equal_to(q[0,0] + q[0,1] - q[0,2], 0) model = objective + constraint ``` ```pycon >>> print(model.objective) q_{0,0} q_{0,1} - q_{0,2} ``` [`constraints`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.constraints) プロパティにより、[`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) クラスが保持している制約条件を取得することができます。このプロパティは [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) クラスのインスタンスを返します。 ```pycon >>> print(model.constraints) [q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1)] ``` > [!NOTE] > > **注釈** > > モデルは目的関数と制約条件をコピーせずに格納します。そのため、モデルに含まれる目的関数や制約条件を変更すると、構築前の変数も変更されることに注意してください。 > > ```pycon > model = Model(objective) > model += q[0, 0] > assert model.objective == objective > ``` ## 5.3. モデルに含まれる制約条件の重みを変更する モデルの構築後に、モデルが含んでいる制約条件の重みを変更したい場合があります。 > [!NOTE] > > **注釈** > > 制約条件の重みの調整に関しては「[ペナルティ関数の重み](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-weight)」を参照してください。 以下の例では、特定の制約条件の重みを 2 倍にします。 ```pycon >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1) >>> model.constraints[0] *= 2 >>> print(model) minimize: q_{0,0} q_{0,1} - q_{0,2} subject to: q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 2) ``` --- # 6. ソルバークライアント Amplify SDK からソルバーを実行するには、各ソルバーを抽象化したソルバークライアントを作成して、接続先、API トークン、実行パラメータなどを指定する必要があります。また、ソルバークライアントは対応関係にあるソルバーの扱える変数の種類、制約条件の有無、次数などの機能の情報を持ちます。Amplify SDK はこれを利用して **変数変換**、**次数下げ**、**制約条件の実装**、**ハードウェアトポロジーへの埋め込み** などの **モデル変換** を自動で行います。 ## 6.1. ソルバークライアントの構成 Amplify Annealing Engine (AE) を例として、クライアント [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を次のように作成します。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` > [!TIP] > > **Tip** > > Amplify AE は[ユーザ登録](https://amplify.fixstars.com/register)を行うと無償の API トークンを入手できます。 クライアントクラスのほとんどのパラメータは、構築後はソルバーのデフォルト値で初期化 (または未設定) されているため、クライアントごとの必須パラメータを設定すればすぐに使えるようになります。設定が必須のパラメータはクライアントによって異なりますが、多くのクラウド型ソルバーでは `token` アトリビュートに API トークンを設定する必要があります。 ```python client.token = "YOUR_API_TOKEN" ``` 全てのクライアントにおいて、ソルバーの実行パラメータの取得と設定は `parameters` プロパティ内のアトリビュートに設定します。設定項目は可能な限りソルバーの API に即しているため、詳細は下記の各ソルバーのリファレンスを参照してください。 たとえば Amplify AE では、実行時間を次のように設定します。 ```python from datetime import timedelta client.parameters.time_limit_ms = timedelta(milliseconds=1000) # 1000 ミリ秒 ``` > [!TIP] > > **Tip** > > 各クライアントのパラメータごとに時間の単位や時刻のフォーマットが異なるため、Amplify SDK では [`datetime`](https://docs.python.org/3/library/datetime.html#module-datetime) モジュールを利用して入出力できるようになっています。 クライアントクラスに設定したパラメータは、[`str`](https://docs.python.org/3/library/stdtypes.html#str) や [`print()`](https://docs.python.org/3/library/functions.html#print) 関数によって文字列として表示することができます。 ```pycon >>> print(client) {"url":"https://optigan.fixstars.com","token":"***","compression":true,"solver":"Constraint","parameters":{"time_limit_ms":1000.0}} ``` > [!NOTE] > > **注釈** > > トークンなどの認証情報は、意図せずに漏洩することを防ぐため `***` として表示されます。表示だけが隠されるので、値自体は [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.token) で従来通り取得できます。 一部のパラメータでは [`None`](https://docs.python.org/3/library/constants.html#None) を設定すると、未設定つまりソルバーのデフォルト値が使用されます。 ```python client.parameters.time_limit_ms = None # ソルバーのデフォルト値にリセット ``` ## 6.2. ソルバークライアントの一覧 Amplify SDK は下記のソルバー・マシンに対応しています。 [amplify.AmplifyAEClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) **Fixstars Amplify Annealing Engine** PCBO-4th PUBO-4th QUBO GPU ☁️ Cloud [📖 Documents](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md#clients-amplifyaeclient) [amplify.DWaveSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) **D-Wave Advantage2** QUBO Ising QPU Annealing-Superconducting ☁️ Cloud Pegasus Graph Zephyr Graph [📖 Parameter Reference](https://docs.dwavequantum.com/en/latest/quantum_research/solver_parameters.html#qpu-solver-parameters) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md#clients-dwavesamplerclient) [amplify.LeapHybridSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) **Leap's Hybrid BQM Solver** QUBO Ising Hybrid Annealing-Superconducting ☁️ Cloud [📖 Parameter Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_bqm_parameters.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md#clients-leaphybridsamplerclient) [amplify.LeapHybridCQMSamplerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient) **Leap's Hybrid CQM Solver** MIP QUBO Ising Hybrid Annealing-Superconducting ☁️ Cloud [📖 Parameter Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_cqm_parameters.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md#clients-leaphybridcqmsamplerclient) [amplify.FujitsuDA4Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) **Fujitsu DA4 Solver** QUBO GPU ☁️ Cloud [📖 API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v4-ja.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fujitsu.md#clients-fujitsuda4client) [amplify.FujitsuDA3cClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient) **Fujitsu DA3c Solver** QUBO GPU ☁️ Cloud [📖 API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v3c-ja.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fujitsu.md#clients-fujitsuda3cclient) [amplify.ToshibaSQBM2Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client) **TOSHIBA SQBM+ V2** QUBO PUBO-4th GPU [📖 User Guide (v2.0.3)](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/7e21cdf718c667d7e3b709b4d6413bbd/User_Manual-SQBM%2B_for_On-premises.pdf) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/toshiba.md#clients-toshibasqbm2client) [amplify.NECVA2Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) **NEC Vector Annealing サービス 2.0** QUBO VE ☁️ Cloud [📖 User Guide](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/f90ee151bb5d360d5b6dadd8db400663/nec_vector_annealing_service_2.0_user_guide_v4.pdf) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/nec.md#clients-necva2client) [amplify.HitachiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) **Hitachi Annealing Cloud Web** Ising GPU ☁️ Cloud King Graph [📖 API Reference](https://annealing-cloud.com/ja/web-api/reference/v2.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/hitachi.md#clients-hitachiclient) [amplify.GurobiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) **Gurobi Optimization** MIP CPU 💻 Local [📖 Reference Manual](https://www.gurobi.com/documentation/current/refman/index.html) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/gurobi.md#clients-gurobiclient) [amplify.AerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) **Aer Simulator** PUBO-Nth Ising CPU GPU Gate-Simulator 💻 Local [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aer.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.AQTClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) **AQT** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aqt.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.BraketSimulatorClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) **Amazon Braket Simulator** PUBO-Nth Ising CPU GPU Gate-Simulator 💻 Local ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aws.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IBMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) **IBM Quantum** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ibm.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IonQClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) **IonQ** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ionq.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IQMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) **IQM** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/iqm.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.QulacsClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) **Qulacs Simulator** PUBO-Nth Ising Hybrid Gate-Simulator 💻 Local [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qulacs.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.RigettiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) **Rigetti** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/rigetti.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.QUDORAClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) **QUDORA** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qudora.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.OqtopusClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) **OQTOPUS** PUBO-Nth Ising Hybrid Gate-Superconducting Gate-Simulator ☁️ Cloud [📖 Document](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/oqtopus.md) [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md) --- **PCBO-Nth PUBO-Nth QUBO Ising MIP** ソルバーが直接扱える問題の種類を表します。 * PCBO-Nth バイナリ変数の $N$ 次多項式の目的関数と $N$ 次多項式の制約条件を扱えるソルバーです。 * PUBO-Nth バイナリ変数の $N$ 次多項式の目的関数を求解できるソルバーです。制約条件は扱えません。 * QUBO バイナリ変数の二次多項式の目的関数を求解できるソルバーです。基本的には制約条件は扱えませんが、ソルバーによっては等式制約、不等式制約の入力に対応しています。 * Ising イジング変数の二次多項式の目的関数を求解できるソルバーです。基本的には制約条件は扱えませんが、ソルバーによっては等式制約、不等式制約の入力に対応しています。 * MIP 混合整数計画問題を求解できるソルバーです。バイナリ変数、整数変数と実数変数を扱うことができます。 一般的には一次の問題 (線形計画問題) を対象としていますが、QUBO を含む二次の問題を扱うことができるソルバーもあります。 > [!NOTE] > > **注釈** > > Amplify SDK は、ソルバーが直接扱えない問題に対して、自動で変数変換や次数下げ、制約条件のペナルティ関数の生成といった変換を行います。そのため、ユーザが自身でソルバーが直接扱える形式の問題を作成する必要は必ずしもありません。ただし、ソルバーの種類や入力するモデルの種類によっては、未対応であったり、厳密な定式化にならないことがあります。詳細は [モデルの変換](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md) を参照してください。 **Graph** ソルバーに入力できる二次の項を表します。これらのタグがついていないソルバーには、二次の項に関する制限はありません。そうでないソルバーは、与えられる二次の項に制限があり、任意の二次多項式を解くためにはグラフ埋め込みと呼ばれる操作が必要です。扱える問題のサイズは、ソルバーに入力可能な変数の数 $N$ に対して最悪ケースで $O\left( \sqrt N \right)$ 程度になります。詳細は「[グラフ埋め込み](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md)」を参照してください。 **CPU GPU VE QPU Hybrid** マシンの動作する演算装置の種類を表します。VE は NEC SX-Aurora TSUBASA Vector Engine を表します。Hybrid は QPU とその他の技術のハイブリッドソルバーである事を表します。 **Annealing-XXX Gate-XXX** QPU または Hybrid ソルバーについてその方式を表します。 * Annealing-Superconducting 量子アニーリング方式・超伝導量子ビットのソルバーです。 * Gate-Superconducting ゲート型・超伝導量子ビットのソルバーです。 * Gate-Trapped-ion ゲート型・イオントラップ方式のソルバーです。 * Gate-Neutral-atom ゲート型・中性原子方式のソルバーです。 * Gate-Simulator ゲート型・量子コンピュータシミュレータのソルバーです。 **☁️ Cloud 💻 Local** クラウドサービスとして提供されるソルバーなのか、ユーザのマシンにインストールする必要があるソルバーなのかを表します。 --- # 7. 組合せ最適化問題の求解 このページでは、「[モデルの定式化](https://amplify.fixstars.com/ja/docs/amplify/v1/model.md)」と「[クライアントの作成](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md)」で作成したモデル [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) およびソルバークライアントを使用して、組合せ最適化問題の求解を行う方法を解説します。 ## 7.1. Solve 関数 組合せ最適化を実行するために、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が用意されています。この関数は第一引数に [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) を、第二引数にソルバークライアントオブジェクトを受け取り、 ソルバークライアントに対応するソルバーを用いてモデルの最適化を行います。 次の例を Amplify AE を用いて最適化します。 $$ \begin{align*} \text{minimize: } \quad & f = q_0 q_1 - q_2 \\ \text{subject to: } \quad & q_0 + q_1 + q_2 = 1, \\ & q_0, q_1, q_2 \in \{0, 1\} \end{align*} $$ 目的関数と制約条件を構築して、モデルを作成します。 ```python from amplify import VariableGenerator, one_hot, AmplifyAEClient, solve gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint = one_hot(q) model = objective + constraint ``` Amplify AE のソルバークライアントを作成して、タイムアウト時間を 1000 ミリ秒に設定します。 ```python from datetime import timedelta client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` 次のようにしてモデルとソルバークライアントを [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数に与え求解を実行します。 ```python result = solve(model, client) ``` 得られた結果は、以下のようにして確かめることができます。詳細は[結果の取得](#solver-result)を参照してください。 ```pycon >>> print(f"objective = {result.best.objective}") objective = -1.0 >>> print(f"q = {q.evaluate(result.best.values)}") q = [0. 0. 1.] ``` > [!NOTE] > > **参考** > > Amplify SDK は、入力されたモデルをクライアントが受け取れる形にするために、ペナルティ関数の計算、変数変換や次数下げ、グラフ埋め込みといったモデル変換を必要に応じて自動で行います。[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数には、このモデル変換で使用するいくつかのパラメータを指定することができます。各パラメータの詳細については「[モデル変換のパラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md#conversion-parameters)」下の各ページを参照してください。 ### 7.1.1. モデル構築の省略 モデルが目的関数のみ、または制約条件のみから構成される場合、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の第 1 引数に直接 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスのオブジェクトや [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) または [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) クラスのオブジェクトを渡すことが可能です。 ```python from amplify import VariableGenerator, one_hot, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint1 = one_hot(q[0] + q[1]) constraint2 = one_hot(q[1] + q[2]) client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` 制約条件のない組合せ最適化問題を解く: ```python result = solve(objective, client) ``` 単一の制約条件からなる組合せ最適化問題を解く: ```python result = solve(constraint1, client) ``` 制約条件のみからなる組合せ最適化問題を解く: ```python result = solve(constraint1 + constraint2, client) ``` ## 7.2. 結果の取得 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトには、ソルバーが返した解の情報や実行にかかった時間の情報が含まれています。 ```python from amplify import VariableGenerator, one_hot, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint = one_hot(q) model = objective + constraint client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) result = solve(model, client) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含まれる解の個数は [`len()`](https://docs.python.org/3/library/functions.html#len) 関数により取得できます。デフォルトでは、制約条件をすべてみたす解のみが[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含まれています。 ```pycon >>> len(result) 1 ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に 1 個以上の解が含まれている場合、[`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) プロパティにより最良解を取得できます。 ```pycon >>> type(result.best) ``` [`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) プロパティにより取得できる最良解は [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスのインスタンスです。このクラスは以下のアトリビュートを持ちます。 | | | | --- | --- | | [`objective`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) | 目的関数の値 | | [`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) | 解における各変数の値 | | [`feasible`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) | 制約条件がみたされているかどうか | | [`time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | 解が得られた時刻 | 以下のようにして、最良解における目的関数の値、変数の値、制約条件がすべてみたされているかどうか、解が得られた時刻をそれぞれ取得できます。 ```pycon >>> result.best.objective -1.0 >>> result.best.values Values({Poly(q_0): 0, Poly(q_1): 0, Poly(q_2): 1}) >>> result.best.feasible True >>> result.best.time datetime.timedelta(microseconds=27965) ``` 変数配列の [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドに [`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) を渡すことで、変数配列の各変数に対応する解の値を変数配列と同じ形の [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) として得ることができます。 ```pycon >>> print(q.evaluate(result.best.values)) [0. 0. 1.] ``` > [!WARNING] > > **注意** > > 使用したソルバーによっては、解が得られた時刻を取得できない場合があります。その場合、[`time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) アトリビュートにはソルバーの実行時間 [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) と同じ値が入ります。詳しくは [実行時間情報の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/timing.md) を参照してください。 [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) には最良解だけでなく複数の解が含まれている場合があります。それぞれの解は、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に対するインデックスアクセスにより [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスのインスタンスを取得できます。 ```pycon >>> result[0].objective -1.0 >>> result[0].feasible True ``` イテレートによるアクセスも可能です。 ```pycon >>> for r in result: ... print(r.objective) ... print(r.values) ... print(r.feasible) ... print(r.time) -1.0 amplify.Values({Poly(q_0): 0.0, Poly(q_1): 0.0, Poly(q_2): 1.0}) True 0:00:00.028060 ``` > [!NOTE] > > **参考** > > [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトには、ほかにモデル変換やグラフ埋め込み、実行時間の情報も含まれています。[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の各プロパティに関する詳細は [実行結果の評価](https://amplify.fixstars.com/ja/docs/amplify/v1/evaluation.md) を参照してください。 ## 7.3. 実行結果の出力オプション デフォルトでは、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトには、制約条件をみたす解のみが目的関数の値が小さい順に入っています。[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数に `filter_solution` キーワード引数および `sort_solution` キーワード引数を指定することで、この動作を変更することができます。 ### 7.3.1. 解のフィルター [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `filter_solution` キーワード引数に [`False`](https://docs.python.org/3/library/constants.html#False) を指定すると、制約条件をみたさない解も [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含めることができます。 ```python from amplify import VariableGenerator, equal_to, Model, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) constraint1 = equal_to(q, 1) constraint2 = equal_to(q, 2) model = Model(constraint1 + constraint2) client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` ```pycon >>> result1 = solve(model, client) >>> len(result1) 0 >>> result2 = solve(model, client, filter_solution=False) >>> len(result2) 1 >>> result2.best.feasible False ``` [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を呼んだあとでも、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`filter_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) プロパティを [`False`](https://docs.python.org/3/library/constants.html#False) に指定することで、制約条件をみたさない解が [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含まれるようにできます。 ```pycon >>> result = solve(model, client) >>> len(result) 0 >>> result.filter_solution = False >>> len(result) 1 ``` ### 7.3.2. 解のソート デフォルトでは、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含まれる解は良い順にソートされています。 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `sort_solution` キーワード引数に [`False`](https://docs.python.org/3/library/constants.html#False) を指定すると、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に入る解の順番はソルバーが返した解の順番のままになります。 ```python result = solve(model, client, sort_solution=False) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`sort()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.sort) メソッドにより、あとから解をソートすることも可能です。 ```python result.sort() ``` > [!NOTE] > > **注釈** > > Amplify SDK では、解の良さを以下の順に判定します。 > > 1. 制約条件をみたしているかどうか > 2. 目的関数の値が小さいかどうか > > したがって、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) プロパティにより取得できる解は、制約条件をみたしている解があればその中で最も目的関数の値が小さいものとなります。制約条件をみたしている解がない場合は、[`filter_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) が [`False`](https://docs.python.org/3/library/constants.html#False) ならば最も目的関数の値が小さいものが返ります。 ## 7.4. dry-run オプション [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `dry_run` キーワード引数に [`True`](https://docs.python.org/3/library/constants.html#True) を指定することで、ソルバーにモデルを送る直前までの処理が行われます。多くのソルバークライアントでは、API トークンを指定しなくても `dry_run` を指定した [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行が可能です。 このオプションにより、求解したいモデルがソルバーに入力可能なのか、また、その際にどのようなモデル変換やグラフ埋め込みが行われ、どのようなリクエストデータが送られるのかを、ソルバーに接続する前に確認することができます。 ```python from amplify import VariableGenerator, equal_to, Model, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) constraint1 = equal_to(q, 1) constraint2 = equal_to(q, 2) model = Model(constraint1 + constraint2) client = AmplifyAEClient() result = solve(model, client, dry_run = True) ``` `dry_run` オプションを指定して実行した場合、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトには解は入っていません。 ```pycon >>> len(result) 0 ``` > [!NOTE] > > **注釈** > > `dry_run` オプションを指定して実行した場合、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) プロパティおよび [`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) プロパティは `dry_run` オプションを指定せずに実行した場合と同じ結果になります。これは、モデル変換とグラフ埋め込みがどのように行われるかを知りたい場合に便利です。各プロパティの詳細については[モデルの変換](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md)をご覧ください。 > [!NOTE] > > **注釈** > > `dry_run` オプションを指定して実行した場合、実際のリクエストはソルバーには送られませんが、ソルバークライアントの [`write_request_data`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.write_request_data) が設定されていればリクエストデータのファイル書き込みが行われます。[`write_request_data`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.write_request_data) の詳細については [送受信データの保存 ☁️ Cloud 💻 Local](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-write-data)をご覧ください。 --- # モデルの変換 Amplify SDK では、実数変数や整数変数を含むモデルや、任意の次数の多項式を含むモデルを作成できます。一方で、組合せ最適化ソルバーは一般に扱える変数の種類や次数、制約条件の種類や入力の可否に制限があり、また、特定の構造を持った二次の多項式しか受け取れない場合もあります。 Amplify SDK は、 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数にソルバーが直接扱えないモデルを入力されたときに、ソルバーが扱える形への変換処理を可能な限り自動で行います。具体的には、変数変換や次数下げなどモデルを変換する処理と、グラフ埋め込みと呼ばれる 2 次の多項式をソルバーが受け取れる形に変換する処理が行われ、その後ソルバーの実行が行われます。 ## 変換処理の概要 まず、Amplify SDK はソルバーが対応できる変数の種類や目的関数・制約条件の次数に応じて変数変換や次数下げを行います。変数変換や次数下げを行ったあとのモデルを**中間モデル** (Intermediate Model) とよびます。中間モデルがソルバーに入力できる形になっているならば、ソルバーに中間モデルを求解させます。ソルバーから返ってきた解に対して、入力モデルに行った変数変換の逆変換を行い、入力モデルの解を計算します。 [![_images/conversion_intermediate_light.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_intermediate_light.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_intermediate_light.drawio.svg) [![_images/conversion_intermediate_dark.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_intermediate_dark.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_intermediate_dark.drawio.svg) ソルバーの種類によっては、中間モデルをそのままソルバーに入力できない場合があります。変数の種類と次数の制限以外に、与えられる 2 次の項の制限があるためです。この場合、Amplify SDK はさらに**グラフ埋め込み** とよばれる操作を行い、中間モデルをソルバーに入力できる形式に変換します。ソルバーから返ってきた解に対して、中間モデルに行ったグラフ埋め込みの逆変換をかけることで中間モデルの解が計算できます。さらに中間モデルの解に対して、入力モデルに行った変数変換の逆変換をかけることで、入力モデルの解となります。 [![_images/conversion_embedding_light.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_embedding_light.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_embedding_light.drawio.svg) [![_images/conversion_embedding_dark.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_embedding_dark.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/conversion_embedding_dark.drawio.svg) ### 中間モデルの構築 変換処理の準備として、ソルバークライアントから次の情報を取得してソルバーの扱える問題の種類を取得し、出力する中間モデルの持つ目的関数と制約条件の次数を決定します。 * 目的関数として扱える変数の種類とそれぞれの次数 * 等式制約として扱える変数の種類とそれぞれの次数 * 不等式制約として扱える変数の種類とそれぞれの次数 ソルバーの扱える最大の次数は変数の種類ごとに与えられます。以下は [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) の例です。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` ```pycon >>> client.acceptable_degrees.objective # 目的関数の次数 {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} >>> client.acceptable_degrees.equality_constraints # 等式制約の次数 {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} >>> client.acceptable_degrees.inequality_constraints # 不等式制約の次数 {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} ``` [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) では、目的関数はバイナリ変数の4次までで、等式制約と不等式制約もバイナリ変数の4次まで直接扱えることがわかります。 > [!NOTE] > > **注釈** > > 扱える次数はクライアントごとに異なりソルバークライアントの設定によっても変化します。詳しくは [クライアントの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md) を参照してください。 その後、Amplify SDK は次のようにして中間モデルへの変換を行います。 **中間モデル構築の処理手順** 1. 変数変換と次数下げを行うことで、目的関数をソルバーが扱える形に変換可能か確認する 2. 変数変換と次数下げを行うことで、等式・不等式制約をソルバーが扱える形に変換可能か確認する 3. ソルバーが扱えない制約条件が存在するならばそのペナルティ関数を計算し、ペナルティ関数が変数変換と次数下げで目的関数と同条件に変換可能か確認する 4. 目的関数と全ての制約条件が変換可能なら、変数変換と次数下げを実行する 5. 使用していない変数を削除して変数とモデルを再構築する 6. 入力モデルと中間モデルの間の変数変換マップを作成する ### グラフ埋め込み グラフ埋め込みが必要なソルバーの場合、中間モデルへの変換に加えてグラフ埋め込みを行います。 グラフ埋め込みが必要かどうかはソルバーごとに決まっており、グラフ埋め込みが必要なソルバーは[ソルバークライアントの一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md#solver-clients)にて Graph というラベルが付与されています。 まず、ソルバークライアントからソルバー固有のグラフ構造を取得します。以下は [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) の例です。 ```python from amplify import DWaveSamplerClient client = DWaveSamplerClient() client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` ```pycon >>> graph = client.graph # DWaveSampler のグラフ構造 >>> graph.type 'Pegasus' >>> len(graph.nodes) 5627 >>> len(graph.edges) 40279 ``` [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) に対応するソルバーが持つグラフ構造は、ノード 5627 個とエッジ 40279 個からなるペガサスグラフであることが分かります。 Amplify SDK は以下の手順によって 2 次の多項式に対してグラフ埋め込みを行い、ソルバーが扱えるようにします。 **グラフ埋め込みの処理手順** 1. 中間モデルのそれぞれの制約条件のペナルティ関数を目的関数に足すことにより、中間モデルを目的関数のみからなる最適化問題 (制約なし中間モデル) に変換する 2. 制約なし中間モデルの目的関数のグラフ表現からソルバー固有のグラフ (物理グラフ) へのグラフ埋め込みを試みる 3. 中間モデルと物理グラフの間の変数の対応マップ (チェイン) を作成する 4. チェインに基づいて 1. で得られた多項式の変換を行い、ソルバーが扱える形式の多項式を得る ### ソルバーの実行と結果の取得 以上のモデル変換とグラフ埋め込みによってソルバーの入力可能な形式に変換ができました。その後、Amplify SDK は [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数に与えられたソルバークライアントに対して `solve` メソッドを呼び出し、ソルバーによる最適化を実行します。ソルバークライアントは、ソルバーの要求するリクエストデータの作成から API や最適化関数の呼び出しを経て、ソルバーのレスポンスの解析までを行います。 Amplify SDK はソルバーから返却された解に対して、グラフ埋め込みによる変数変換処理と中間モデルの構築における変数変換それぞれの**逆変換**を段階的に行い、入力モデルの解を取得して [`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) アトリビュートに格納します。 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数は返値の [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスに一連の変換・逆変換処理やソルバーの実行結果に関する情報を保存します。以下は代表的な情報を取得するための[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのアトリビュートです。 | アトリビュート | データ型 | 概要 | 詳細 | | --- | --- | --- | --- | | [`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) | [`SolutionList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.SolutionList) | 入力モデルの解や目的関数の値などの情報を格納 | | | [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | [`ModelConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) | 中間モデルとその変数変換情報を格納 | | | [`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | [`GraphConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) | 中間モデルから物理グラフへのグラフ埋め込み情報を格納 (グラフ埋め込みが必要な場合のみ) | | | [`client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | `Client.Result` | ソルバークライアントの実行結果を格納 | | > [!NOTE] > > **参考** > > 中間モデルとグラフ埋め込みの実行結果に関する情報の詳細は、それぞれ [変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md) と [グラフ埋め込み](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md) を参照してください。 ## モデル変換のパラメータ モデル変換の際に使用されるパラメータを以下に示します。これらは、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数のキーワード引数として与えることができます。 | パラメータ名 | モデル変換の種類 | 概要 | 詳細 | | --- | --- | --- | --- | | `integer_encoding_method` | 変数変換 | 整数変数をバイナリ変数に変換変換するアルゴリズム | | | `real_encoding_method` | 変数変換 | 実数変数をバイナリ変数に変数変換するアルゴリズム | | | `quadratization_method` | 次数下げ | 次数下げに使用するアルゴリズム | | | `substitution_multiplier` | 次数下げ | 次数下げで生成される制約条件の重み | | | `embedding_method` | グラフ埋め込み | グラフ埋め込みに使用するアルゴリズム | | | `embedding_timeout` | グラフ埋め込み | グラフ埋め込みのタイムアウト値 (秒) | | | `chain_strength` | グラフ埋め込み | 多項式のグラフ埋め込みの際のパラメータ | | たとえば、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の中で、整数変数をバイナリ変数に変換変換する際に使用するアルゴリズムを [`Unary`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Unary) に設定したい場合は、以下のようにします。 ```python result = solve(model, client, integer_encoding_method="Unary") ``` また、以下のパラメータは、不等式制約のペナルティ生成方法を指定します。不等式制約を表す制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) を [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) などのヘルパー関数や [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) クラスのコンストラクタを使って構築する際に、キーワード引数 `method` により指定できます。 | パラメータ名 | モデル変換の種類 | 概要 | 詳細 | | --- | --- | --- | --- | | `penalty_formulation` | ペナルティ生成 | ペナルティ生成のアルゴリズム | | たとえば、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の中で、不等式制約のペナルティを生成する際に使用するアルゴリズムを [`IntegerVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) に設定したい場合は、以下のようにします。 ```python le_constraint = less_equal( q[0] + q[1] + q[2], 2, penalty_formulation="IntegerVariable" ) ``` ## 次のステップ 以下のページでは、Amplify の変換処理をより詳しく知りたい方のために、Amplify の行うモデル変換処理・ペナルティ関数の生成による制約条件の実現・グラフ埋め込み処理について説明しています。 **変数変換と次数下げ** 解きたいモデルをソルバーの扱える変数の種類や多項式の次数に合わせるために Amplify SDK の実装している変数変換と次数下げの方法を説明します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md) **制約条件とペナルティ関数** 制約条件を扱えないソルバーに対して Amplify SDK がどのようなペナルティ関数を生成し、制約条件を実現しているかを説明します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md) **グラフ埋め込み** ソルバーに入力可能な二次多項式にソルバー固有の構造を持つ場合に、任意の入力を可能にするために行われるグラフ埋め込みの処理について解説します。 特に、D-Wave の例を用いて Amplify SDK で実装されるグラフ埋め込みの詳細を説明します。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md) --- # 変数変換と次数下げ Amplify SDK では、実数変数や整数変数を含むモデルや、任意の次数の多項式を含むモデルを作成できます。一方で、組合わせ最適化ソルバーは一般に扱える変数の種類や次数に制限があります。解きたいモデルをソルバーの扱える変数の種類や多項式の次数に合わせるために Amplify SDK の実装している変数変換と次数下げの方法を説明します。 ## 中間モデルの取得 モデルに対して [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドを用いると、指定された変数の種類や多項式の次数に合わせて変換された中間モデルが返却されます。このメソッドは [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の内部で中間モデルの構築時に使用されるため、Amplify SDK がどのように変数変換と次数下げを行っているのかを確認するのに便利です。 > [!WARNING] > > **注意** > > 通常は [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドを呼び出す必要はありません。Amplify SDK が [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の内部でどのように変数変換と次数下げを行っているのかを確認するために使用してください。 中間モデルの持つ変数の種類や多項式の次数は [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドの第一引数に指定します。ソルバークライアントに合わせたい場合には、次のようにして [`acceptable_degrees`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.acceptable_degrees) プロパティを与えます。 ```python from amplify import VariableGenerator, Model, AmplifyAEClient, AcceptableDegrees gen = VariableGenerator() q = gen.array("Binary", 3) model = Model(q[0] * q[1] * q[2]) client = AmplifyAEClient() client.parameters.time_limit_ms = 1000 client.solver = "Qubo" im, mapping = model.to_intermediate_model(client.acceptable_degrees) ``` [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドは中間モデルと、入力モデルから中間モデルへの変数変換マップを返します。 例えば [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) は QUBO モードの場合、目的関数としてバイナリ変数の二次多項式を扱うことができます。(ソルバーが扱える最大次数の調べ方については [中間モデルの構築](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md#create-intermediate-model) をご参照ください) 上記では、入力モデルとしてバイナリ変数の三次多項式を与えていますが、[`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドによって、入力モデルはバイナリ変数の二次多項式を目的関数とし、[Substitute 制約](#substitution-multiplier) が課された中間モデルに変換されています。 ```pycon >>> print(im) minimize: q_2 q'_0 subject to: q_0 q_1 - q'_0 == 0 (weight: 1) ``` > [!NOTE] > > **注釈** > > 中間モデルに含まれる変数は、入力した変数とは使用している [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) が異なることに注意してください。つまり、入力モデルの変数と中間モデルに含まれる変数同士を演算することはできません。 [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドには [`AcceptableDegrees`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) クラスのインスタンスを与えることで、変換先の変数の種類と次数を自由に指定することもできます。 ```python bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) im, mapping = model.to_intermediate_model(bq) ``` また、[`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドには変数の種類と次数を指定する他に、変数変換や次数下げのアルゴリズムを指定が可能です。以下では [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドの結果を見ながら、Amplify に実装されている変数変換と次数下げの方法について説明します。 ## 変数変換 変数変換は入力モデルに含まれる変数を別の変数の種類に変換する処理です。これにより、ソルバーが扱える変数の種類を持った中間モデルに変換することができます。 現在、次の変数変換が実装されています。 * 整数変数からバイナリ変数への変換 * 実数変数からバイナリ変数への変換 * バイナリ変数からイジング変数への変換とその逆 ### 整数変数からバイナリ変数への変換 下限が $l$、上限が $u$ の整数変数 $n$ に対し、いくつかのバイナリ変数 $q_0, q_1, ..., q_{k-1}$ を新しく発行し、$n$ を多項式 $$ a_0 q_0 + a_1 q_1 + \cdots + a_{k-1} q_{k-1} + l $$ に変換します。このとき、この多項式の取りうる範囲が $l$ 以上 $u$ 以下のすべての整数の集合と一致するように整数列 $a_0, a_1, \ldots, a_{k-1}$ を決定します。 変数の数 $k$ および多項式の係数列 $a_0, a_1, \ldots, a_{k-1}$ を決めるために 4 種類のアルゴリズムが実装されています。 例として、次のように -10 以上 10 以下の整数を取る整数変数 `n` を目的関数として持つモデルに対して中間モデルをバイナリ変数で構成する場合に、それぞれのアルゴリズムにおいて整数変数 `n` がどのようなバイナリ変数の多項式に変換されるかを確認します。 ```python gen = VariableGenerator() n = gen.scalar("Integer", bounds=(-10, 10)) # 整数変数を発行 model = Model(n) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) ``` 整数変数からバイナリ変数への変換アルゴリズムは、[`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッド及び [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `integer_encoding_method` キーワード引数で指定します。デフォルトは [`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Default) です。 **[`Unary`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Unary)** 変数の数 $k$ を $u - l$ とし、$a_0 = a_1 = \cdots = a_{k-1} = 1$ とします。 ```python im, mapping = model.to_intermediate_model(bq, integer_encoding_method="Unary") ``` ```pycon >>> print(mapping[n]) q_0 + q_1 + q_2 + q_3 + q_4 + q_5 + q_6 + q_7 + q_8 + q_9 + q_{10} + q_{11} + q_{12} + q_{13} + q_{14} + q_{15} + q_{16} + q_{17} + q_{18} + q_{19} - 10 ``` **[`Linear`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Linear)** $(a_0, a_1, a_2, \ldots, a_{k-2}, a_{k-1}, a_k) = (1, 2, 3, \ldots, k-1, k, m)$ と割り当てます。 $k$ は $1 + 2 + 3 + \cdots + k \leq u - l$ となるような最大の整数で、$m$ は端数です。 ```python im, mapping = model.to_intermediate_model(bq, integer_encoding_method="Linear") ``` ```pycon >>> print(mapping[n]) q_0 + 2 q_1 + 3 q_2 + 4 q_3 + 5 q_4 + 5 q_5 - 10 ``` **[`Binary`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Binary)** $(a_0, a_1, a_2, a_3, \ldots, a_{k-1}, a_k) = (1, 2, 4, 8, \ldots, 2^{k-1}, m)$ と割り当てます。 $k$ は $1 + 2 + 4 + \cdots + 2^{k-1} \leq u - l$ となるような最大の整数で、$m$ は端数です。 ```python im, mapping = model.to_intermediate_model(bq, integer_encoding_method="Binary") ``` ```pycon >>> print(mapping[n]) q_0 + 2 q_1 + 4 q_2 + 8 q_3 + 5 q_4 - 10 ``` **[`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Default) (Default)** 上記の 3 つのアルゴリズムのうち、使用する変数の数 $k$ が最も少なくなる方法を採用します。 > [!NOTE] > > **注釈** > > [`Linear`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Linear) と [`Binary`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Binary) において、 > 端数 $m$, $m_1$, $m_2$ が $0$ になる場合は対応する補助変数の発行は省略されます。 ### 実数変数からバイナリ変数への変換 下限が $l$、上限が $u$ の実数変数 $x$ に対し、いくつかのバイナリ変数 $q_0, q_1, ..., q_{k-1}$ を新しく発行し、$x$ を多項式 $$ a_0 q_0 + a_1 q_1 + \cdots + a_{k-1} q_{k-1} + l $$ に変換して表現します。このとき、係数列 $a_0, a_1, \ldots, a_{k-1}$ は $a_0 + a_1 + \cdots a_{k-1} = u - l$ を満たす正の実数列で構成されます。 多項式の係数列 $a_0, a_1, \ldots, a_{k-1}$ を決めるために、乱数に基づくアルゴリズム [[5]](#id21)が実装されています。 例として、次のように -10 以上 10 以下の実数を取る実数変数 `x` を目的関数として持つモデルをバイナリ変数で構成する場合に、実数変数 `x` がどのようなバイナリ変数の多項式に変換されるかを確認します。 ```python gen = VariableGenerator() x = gen.scalar("Real", bounds=(-10, 10)) model = Model(x) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) ``` 実数変数からバイナリ変数への変換アルゴリズムは、[`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッド及び [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `real_encoding_method` キーワード引数に指定します。デフォルトは [`Random16`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md#amplify.RealEncodingMethod.Random16) です。 **`Random`** $(a_0, a_1, a_2, a_3, \ldots, a_{k-1})$ を一様乱数で与えます。 バイナリ変数の数 $k$ は変換アルゴリズムの末尾の数字によって (4, 8, 16, 32) のうちいずれかを設定します。以下は $k = 16$ の場合の例です。 ```python amplify.set_seed(0) im, mapping = model.to_intermediate_model(bq, real_encoding_method="Random16") ``` ```pycon >>> print(mapping[x]) 1.99333941505556 q_0 + 1.05184485013684 q_1 + 1.18505654902564 q_2 + 1.49764241671521 q_3 + 1.76252706549575 q_4 + 0.841695701394766 q_5 + 0.21960146400976 q_6 + 0.635503335788004 q_7 + 1.80253453941945 q_8 + 0.173438994097798 q_9 + 2.04763527252344 q_{10} + 0.611762636976138 q_{11} + 1.95487069012893 q_{12} + 1.62228108547751 q_{13} + 1.9691590736731 q_{14} + 0.631106910082103 q_{15} - 10 ``` > [!NOTE] > > **注釈** > > [`set_seed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.set_seed.md#amplify.set_seed) 関数で変数変換に利用する乱数のシードを固定できます。 > [!NOTE] > > **注釈** > > [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) では数式処理の数値誤差への対処として、係数が `1e-10` を下回る項は無視されます。 > そのため、上限と下限の差 $u - l$ が非常に小さい場合において、変換されたバイナリ変数の項のうちいくつかが消失する可能性があります。 ### イジング変数からバイナリ変数への変換 イジング変数 $s$ に対し、新しくバイナリ変数 $q$ を発行し、$s$ を $2 q - 1$ に変換します。 ```python gen = VariableGenerator() s = gen.scalar("Ising") model = Model(s) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) im, mapping = model.to_intermediate_model(bq) ``` ```pycon >>> print(mapping[s]) 2 q_0 - 1 ``` ### バイナリ変数からイジング変数への変換 バイナリ変数 $q$ に対し、新しくイジング変数 $s$ を発行し、$q$ を $(s + 1) / 2$ に変換します。 ```python gen = VariableGenerator() q = gen.scalar("Binary") model = Model(q) iq = AcceptableDegrees(objective={"Ising": "Quadratic"}) im, mapping = model.to_intermediate_model(iq) ``` ```pycon >>> print(mapping[q]) 0.5 s_0 + 0.5 ``` ## バイナリ変数多項式の次数下げ Amplify SDK は、バイナリまたはイジング変数の多項式を、ソルバーの要求に合わせてより低い次数の多項式に変換する機能を実装しています。 変数変換と次数下げを両方適用することで、整数変数を含む多項式もバイナリ変数の低次多項式に変換可能です。 ### 次数下げのアルゴリズム [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) [[1]](#id17) と [`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) [[2]](#id18) [[3]](#id19) [[4]](#id20) の 2 通りのアルゴリズムが実装されています。 次数下げのアルゴリズムは、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数 及び [`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドの `quadratization_method` キーワード引数で指定できます。デフォルトは [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) です。 それぞれのアルゴリズムにおいて、次数下げが行われた場合にどのような中間モデルが構築されるかを確認するために、次のような 3 次のバイナリ変数多項式を目的関数として持つモデルを作成しておきます。また、中間モデルは目的関数がバイナリ 2 次で制約条件なしとなるように指定します。 ```python gen = VariableGenerator() q = gen.array("Binary", 4) model = Model(q[0] * q[2] * q[3] - q[1] * q[2] * q[3]) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) ``` **[`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) (Default)** 3次以上のバイナリ変数の積に現れる 2 つのバイナリ変数の積 $q_a q_b$ に対して、補助変数 $x$ を発行し、多項式の各項に含まれる $q_a q_b$ をすべて $x$ に置換します。このとき中間モデルには以下の制約条件が追加されます。 $$ \begin{align*} \text{subject to:} \quad & q_a q_b = x \\ \text{penalty function:} \quad & q_a q_b - 2 q_a x - 2 q_b x + 3 x \end{align*} $$ 以上の操作を多項式が所望の次数になるまで繰り返します。 ```python im, mapping = model.to_intermediate_model( bq, quadratization_method="Substitute" ) ``` ```pycon >>> print(im) minimize: q_0 q'_0 - q_1 q'_0 subject to: q_2 q_3 - q'_0 == 0 (weight: 2) ``` 上記では、`q_0 q_1` が補助変数 `q'_0` で置き換えられたことがわかります。 次数下げで追加される制約条件のペナルティ関数の重みは、置換が発生した項の係数の絶対値の和を初期値として設定されます。これは目的関数に対して十分に大きな値を重みに与える必要があるためです。 この重みの初期値は時に大きすぎる場合があるため、`substitution_multiplier` キーワード引数で重みの初期値に対する係数を指定することができます。 ```python im, mapping = model.to_intermediate_model(bq, quadratization_method="Substitute", substitution_multiplier=0.5 ) ``` ```pycon >>> print(im) minimize: q_0 q'_0 - q_1 q'_0 subject to: q_2 q_3 - q'_0 == 0 (weight: 1) ``` > [!NOTE] > > **注釈** > > 制約条件の重みの調整に関しては「[ペナルティ関数の重み](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-weight)」を参照してください。 **[`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD)** 多項式の高次の項ごとに補助変数を発行して、補助変数が最適な値を取る場合に値が変化しないように、高次の項を 2 次式にします。 3 次以上のバイナリ変数の項 $k q_1 q_2 \cdots q_n$ に対して以下の変換を行います。 * 項の係数 $k$ が負の場合、補助変数 $x$ を 1 つ発行して、項 $k q_1 q_2 \cdots q_n$ を $$ kx (q_1 + q_2 + \cdots + q_n + 1 - n) $$ に変換します。 * 項の係数 $k$ が正で次数 $n$ が偶数の場合、$(n-2)/2$ 個の補助変数 $x_1, x_2, \ldots, x_{\left(n-2 \right)/2}$ を発行して、 項 $k q_1 q_2 \cdots q_n$ を $$ \begin{align*} & k \left(\frac{1}{2} S\left(S-1\right) - \sum_{i = 1}^{\frac{n-2}{2}} x_i \left(2 \left(S - 2i\right) + 1\right) \right) \\ & \text{where} \quad S = q_1 + q_2 + \cdots + q_n \end{align*} $$ に変換します。 * 項の係数 $k$ が正で次数 $n$ が奇数の場合、$(n-1)/2$ 個の補助変数 $x_1, x_2, \ldots, x_{\left(n-1\right)/2}$ を発行して、 項 $k q_1 q_2 \cdots q_n$ を $$ \begin{align*} & k \left(\frac{1}{2} S\left(S-1\right) - \sum_{i = 1}^{\frac{n-1}{2} - 1} x_i \left(2 \left(S - 2i\right) + 1\right) - x_{\frac{n-1}{2}} \left(S - n + 2\right) \right) \\ & \text{where} \quad S = q_1 + q_2 + \cdots + q_n \end{align*} $$ に変換します。 ```python im, mapping = model.to_intermediate_model( bq, quadratization_method="IshikawaKZFD" ) ``` ```pycon >>> print(im) minimize: q_0 q_2 + q_0 q_3 - q_0 q'_0 - q_1 q'_1 + q_2 q_3 - q_2 q'_0 - q_2 q'_1 - q_3 q'_0 - q_3 q'_1 + q'_0 + 2 q'_1 ``` ここで、`q'_0` と `q'_1` は各項それぞれで発行された補助変数です。 > [!WARNING] > > **注意** > > [`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) アルゴリズムでは、制約条件式を次数下げすることはできません。 > 3 次の制約条件式を持つ制約条件を 2 次の制約条件式を受け取れるソルバーに渡したい場合は [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) アルゴリズムを使用してください。 イジング変数の場合 3 次以上のイジング変数の項 $k s_1 s_2 \cdots s_n$ に対して以下の変換を行います。 * 項の係数 $k$ が正で次数 $n$ が奇数の場合、または項の係数 $k$ が負で次数 $n$ が偶数の場合: $\mathrm{floor} \left( n / 2 \right)$ 個の補助変数 $x_1, x_2, \ldots, x_{\mathrm{floor} \left( n / 2 \right)}$ を発行して、 項 $k s_1 s_2 \cdots s_n$ を $$ \begin{align*} & \left| k \right| \left( 2 S^2 - 8 \sum_{i = 1}^{\mathrm{floor} \left( n / 2 \right)}{ \left( \frac{x_i + 1}{2} \right) \left( S - 2 i + 1 \right) } - 1 \right) \\ & \text{where} \quad S = \sum_{i =1}^{n}{\frac{s_i + 1}{2}} \end{align*} $$ に変換します。 * 項の係数 $k$ が正で次数 $n$ が偶数の場合、または項の係数 $k$ が負で次数 $n$ が奇数の場合: $\mathrm{floor} \left( \left(n-1\right) / 2 \right)$ 個の補助変数 $x_1, x_2, \ldots, x_{\mathrm{floor} \left( \left(n-1\right) / 2 \right)}$ を発行して、 項 $k s_1 s_2 \cdots s_n$ を $$ \begin{align*} & \left| k \right| \left( 2 \left(S-1\right)^2 - 8 \sum_{i = 1}^{\mathrm{floor} \left( \left(n-1\right) / 2 \right)}{ \left( \frac{x_i + 1}{2} \right) \left( S - 2 i \right) } - 1 \right) \\ & \text{where} \quad S = \sum_{i =1}^{n}{\frac{s_i + 1}{2}} \end{align*} $$ に変換します。 ### 各アルゴリズムの特徴 次数下げの各アルゴリズムには次のような特徴があります。どのアルゴリズムを使用するかでモデルによっては中間モデルの変数の数が大きく変わることがあり、ソルバーの実行可否や結果に影響が現れることがあります。 | アルゴリズム | [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) | [`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) | | --- | --- | --- | | 次数下げ可能な多項式の変数 | バイナリ変数 | バイナリ変数またはイジング変数 | | 次数下げ後の次数 | 任意の次数。ただし 2 次の等式制約または 2 次のペナルティが付加される | 必ず 2 次以下になる | | 制約条件の次数下げ | 可能 | 不可能。ペナルティを次数下げする必要がある | | 補助変数の数 | 項をまたいだ置換が有効に働く場合、補助変数の数を [`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) よりも少なくできることがある | 次数の半分 $\times$ 項数に概ね比例 (係数が負の場合、項数に比例) | ## ソルバーの実行結果と中間モデル [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行結果から、中間モデルと中間モデルに対する求解結果の情報を取得することもできます。この情報は、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) アトリビュート ([`ModelConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) クラス) から取得できます。 [`ModelConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) クラスは以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.model) | [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) | 中間モデル | | [`mapping`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) | [`IntermediateMapping`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.IntermediateMapping) | 入力モデルの変数から中間モデルの変数への変数変換マップ | | [`num_variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.num_variables) | [`int`](https://docs.python.org/3/library/functions.html#int) | 中間モデルの目的関数と制約条件 (ペナルティ関数が生成された場合はそれを含む) で使用されている変数の数 | | [`values_list`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list) | [`ValuesList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ValuesList) | 中間モデルの求解結果 | 例として、目的関数に整数変数を持つ次のモデルに対して [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を用いて [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) を実行します。 ```python from amplify import VariableGenerator, Model, AmplifyAEClient, solve gen = VariableGenerator() n = gen.scalar("Integer", bounds=(1, 3)) # 整数変数を発行 model = Model(n) client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = 1000 result = solve(model, client) ``` 実行結果の [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) アトリビュートから中間モデルに関する情報が取得できます。 ```pycon >>> print(result.intermediate.model) minimize: q_0 + q_1 + 1 ``` 整数変数 `n` がどのように変数変換されたかは、次のように [`mapping`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) で確認できます。 ```pycon >>> print(result.intermediate.mapping[n]) q_0 + q_1 + 1 ``` 中間モデルの解は [`values_list`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list) で確認できます。[`values_list`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list) には複数の解が含まれていることがあるので、ここでは最初の解を取得します。 ```pycon >>> result.intermediate.values_list[0] Values({Poly(q_0): 0, Poly(q_1): 0}) ``` 入力モデルの解は、中間モデルの解に対して [`mapping`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) を用いた変換を行って得られるものとなります。 少し複雑ですが、次のようにして全ての中間モデルの解を入力モデルの解に変換できます。 ```pycon >>> im = result.intermediate >>> { ... var: im_mapped.evaluate(im_values) ... for im_values in im.values_list ... for var, im_mapped in im.mapping.items() ... } {Poly(n_0): 1.0} ``` これは [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) の出力結果である [`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) と一致することが確認できます。 --- [[1](#id11)] I. G. Rosenberg, “Reduction of Bivalent Maximization to the Quadratic Case,” Cahiers du Centre d’Etudes de Recherche Operationnelle 17, 71–74 (1975). [[2](#id12)] [V. Kolmogorov and R. Zabih, “What energy functions can be minimized via graph cuts?” IEEE Transactions on Pattern Analysis and Machine Intelligence 26, 147–159 (2004).](https://doi.org/10.1109/TPAMI.2004.1262177) [[3](#id13)] [D. Freedman and P. Drineas, “Energy Minimization via Graph Cuts: Settling What is Possible,” in 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR’05), Vol. 2 (IEEE, 2005) pp. 939–946.](https://doi.org/10.1109/CVPR.2005.143) [[4](#id14)] [H Ishikawa, “Transformation of General Binary MRF Minimization to the First-Order Case,” IEEE Transactions on Pattern Analysis and Machine Intelligence 33, 1234–1249 (2011).](https://doi.org/10.1109/TPAMI.2010.91) [[5](#id6)] [K. Endo, Y. Matsuda, S. Tanaka, and M. Muramatsu, “Novel real number representations in Ising machines and performance evaluation: Combinatorial random number sum and constant division,” PLOS ONE 19, e0304594 (2024).](https://doi.org/10.1371/journal.pone.0304594) --- # 制約条件とペナルティ関数 Amplify SDK では、任意の変数と多項式の次数を持つ制約条件を含むモデルを作成できます。しかし、組合せ最適化ソルバーごとに、制約条件として扱える変数の種類や次数は異なり、特に [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーでは制約条件そのものを受け取れないものもあります。 Amplify SDK は、目的関数と同様に、制約条件の変数と多項式の次数を変換することで、組合せ最適化ソルバーに対応した中間モデルを構築します。もし、このような変換で対応ができない場合には、制約条件に対応する **ペナルティ関数** を生成し、自動で目的関数にペナルティ関数を足し込むことでソルバーを呼び出します。これらの処理により、制約条件をそのままでは受け取れない組合せ最適化ソルバーに対しても、制約条件を含むモデルの求解を可能にします。 ## 中間モデルにおける制約条件 それぞれのソルバークライアントには、目的関数に加えて **等式制約** と **不等式制約** それぞれについて、扱える変数の種類と次数が定義されています。Amplify SDK は、これらの情報をもとに、中間モデルにおける制約条件の変数と多項式の次数を決定して変換を試みます。 整数変数に対する等式制約を含む入力モデルを中間モデルに変換する例をいくつか紹介します。 ```python from amplify import ( VariableGenerator, Model, AmplifyAEClient, AcceptableDegrees, equal_to, ) gen = VariableGenerator() n = gen.scalar("Integer", bounds=(-10, 10)) # 整数変数を発行 c = equal_to(n, 1) # n = 1 の等式制約を作成 model = Model(c) ``` 例えば一次のバイナリ変数からなる等式制約をそのまま扱えるソルバークライアント向けには、次のように入力モデルから中間モデルへの変換が行われます。 ```python bqbl = AcceptableDegrees( objective={"Binary": "Quadratic"}, equality_constraints={"Binary": "Linear"} ) im, mapping = model.to_intermediate_model(bqbl) ``` ```pycon >>> print(im) minimize: 0 subject to: q_0 + 2 q_1 + 4 q_2 + 8 q_3 + 5 q_4 - 10 == 1 (weight: 1) >>> print(mapping[n]) q_0 + 2 q_1 + 4 q_2 + 8 q_3 + 5 q_4 - 10 ``` [目的関数における変数変換](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md#encode-integer)と同様に、中間モデルに含まれる制約条件がバイナリ変数のみで構成され、中間モデルにおいて整数変数とバイナリ変数の変数変換が行われていることがわかります。 一方で、制約を全く扱えないソルバーに対しても、Amplify SDK は制約条件を含むモデルの求解が可能です。次の例は、[QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーに対して、整数変数を含む入力モデルを中間モデルに変換する例です。 ```python bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) im, mapping = model.to_intermediate_model(bq) ``` ```pycon >>> print(im) minimize: 0 subject to: q_0 + 2 q_1 + 4 q_2 + 8 q_3 + 5 q_4 - 10 == 1 (weight: 1) >>> print(mapping[n]) q_0 + 2 q_1 + 4 q_2 + 8 q_3 + 5 q_4 - 10 ``` 一見すると前の例と全く違いが無いように見えますが、実は次節で説明するペナルティ関数と呼ばれる多項式が生成され、さらに変数変換されています。ペナルティ関数は目的関数の一部として利用されるため、目的関数と同様の変数変換と次数下げが行われます。これは次のようにして確認できます。 ```pycon >>> # 入力モデルの制約条件のペナルティ関数 >>> print(model.constraints[0].penalty) n_0^2 - 2 n_0 + 1 ``` ```pycon >>> # 中間モデルの制約条件のペナルティ関数 >>> print(im.constraints[0].penalty) 4 q_0 q_1 + 8 q_0 q_2 + 16 q_0 q_3 + 10 q_0 q_4 + 16 q_1 q_2 + 32 q_1 q_3 + 20 q_1 q_4 + 64 q_2 q_3 + 40 q_2 q_4 + 80 q_3 q_4 - 21 q_0 - 40 q_1 - 72 q_2 - 112 q_3 - 85 q_4 + 121 ``` ## ペナルティ法 Amplify SDK は、ソルバーが扱える制約条件の種類や次数に応じて、変数変換や次数下げによって制約条件の条件式の変換を試みます。しかし変換ができない場合には、制約条件の条件式の代わりにペナルティ関数と呼ばれる多項式を目的関数に付与します。ペナルティ関数は制約条件と等価と見なせるように生成されるため、制約条件が間接的に実現されることになります。中間モデルを構築する際には、必要に応じて目的関数に加えてペナルティ関数の変数変換と次数下げも行われます。 **ペナルティ法** 変数 $x_1, x_1, \ldots, x_n$ についてのある制約条件 $c$ に対し、実数値をとる関数 $p$ が $$ p(x_1, x_2, \ldots, x_n) \begin{cases} = 0 \quad & \text{if } c \text{ is satisfied} \\ > 0 \quad & \text{otherwise} \end{cases} $$ をみたすとき、$p$ を **ペナルティ関数** といいます。 組合せ最適化最適化問題 $$ \begin{align*} \text{minimize} & \quad f(x) \\ \text{subject to} & \quad g_1(x) \leq c_1, \, g_2(x) \leq c_2, \, \ldots, \, g_m(x) \leq c_m \end{align*} $$ に対し、$m$ 個の制約条件のペナルティ関数 $p_1, p_2, \ldots, p_m$ をそれぞれ計算し、制約条件を持たない組合せ最適化問題 $$ \text{minimize} \quad f(x) + k_1 p_1(x) + k_2 p_2(x) + \cdots + k_m p_m(x) $$ に変換する方法を **[ペナルティ法](https://en.wikipedia.org/wiki/Penalty_method)** といいます。ここで、$k_1, k_2, \ldots, k_m$ は十分に大きなハイパーパラメータです。 [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) クラスのインスタンスに対して、そのペナルティ関数は、[`penalty`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.penalty) プロパティを用いて取得できます。 例として、[`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) ヘルパー関数を用いて作成された制約条件オブジェクトのペナルティ関数は、次のようにして確認できます。 ```python from amplify import VariableGenerator, equal_to gen = VariableGenerator() q = gen.array("Binary", 6) c = equal_to(q[0] + q[1] + q[2], 1) ``` ```pycon >>> print(c.penalty) 2 q_0 q_1 + 2 q_0 q_2 + 2 q_1 q_2 - q_0 - q_1 - q_2 + 1 ``` `c.penalty` の値は、`c` がみたされるとき、つまり `q[0] + q[1] + q[2] == 1` となるときに 0 をとり、 それ以外の場合は 0 よりも大きな値をとるようになっています。つまり、[前節](#penalty-definition) で定義されたペナルティ関数の要件をみたしています。 ## ペナルティ関数の重み ペナルティ関数は目的関数に追加されることで、制約を満たしていないときにのみ目的関数の値が大きくなる、まさにペナルティとして扱われます。ソルバーは目的関数とペナルティの値の合計を最小化するように解を探索するため、目的関数もペナルティも小さな解が得られることが期待されます。 ペナルティ法が上手く働くための重要な点として、制約条件の重み (上記の $k_1$, $k_2$, $\ldots$, $k_m$) を適切に設定する必要があることが挙げられます。ソルバーは目的関数とペナルティの値の合計を最小化するため、制約条件を破ったときにかかるペナルティの値が小さい場合、制約条件を満たす中で目的関数が最小の解よりも、制約条件を満たさないが目的関数がとても小さい解の方が良い解だと判定される可能性があるためです。 言い換えると、ソルバーに目的関数の最小化よりもペナルティ値の最小化を優先させる必要があるということになります。 ペナルティ関数の重みは、制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) が持つ [`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) プロパティを用いて取得・設定できます。[`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) の初期値は 1 に設定されており、目的関数に足されるペナルティ関数は Amplify SDK が自動で計算する値に [`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) を乗じたものとなります。 ```python gen = VariableGenerator() q = gen.array("Binary", shape=(2, 3)) c_list = equal_to(q, 1, axis=1) ``` ```pycon >>> print(c_list) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 1), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 1)] >>> c_list[0].weight 1.0 ``` 次節で述べるように、通常は Amplify SDK が自動でペナルティ関数をペナルティとして最低 1 の値がかかるように規格化して設定します。つまり初期状態では 1 の値がペナルティとして課せられることになります。[`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) をどのくらいの値にするのが適切かは問題によって異なりますが、一つの目安としては、制約条件に関係する目的関数の値よりも大きく設定しておくと実行可能解が出やすくなります。そのため、その値が 1 からかけ離れている場合、ペナルティ関数の重みを適切に設定する必要があります。 ペナルティ関数の重みは直接 [`weight`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) プロパティに代入して設定できますが、制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) や制約条件リスト [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) に対して数値をかけることでも設定できます。後者は複数の制約条件オブジェクトに一括で同じ値の重みを設定したいときや、モデルを構築した後で重みを設定したいときに便利です。 ```pycon >>> c_list *= 2.0 >>> print(c_list) [q_{0,0} + q_{0,1} + q_{0,2} == 1 (weight: 2), q_{1,0} + q_{1,1} + q_{1,2} == 1 (weight: 2)] ``` 具体的な問題におけるペナルティ関数の重みの設定については下記を参照してください。 * [巡回セールスマン問題](https://amplify.fixstars.com/ja/docs/amplify/v1/tsp.md#tsp-model) * [二次割り当て問題](https://amplify.fixstars.com/ja/docs/amplify/v1/qap.md#qap-model) > [!TIP] > > **ヒント** > > たとえば次のような手順でペナルティ関数の重みを調整すると良いでしょう。 > > 1. ある制約に着目したときにその制約が満たされていないときの **目的関数の最大の利得** を見積もります > > * 例えば巡回セールスマン問題であれば、都市を **訪問しない** ことによる最大の利得は、都市間の辺の長さの最大値と見積もれます > 2. 見積もった値よりも大きな値を対象の制約のペナルティ関数の重みとして設定します > 3. 実行可能解が得られなかった場合は重みを大きくしてソルバーを再度実行します > > * 例えば 2 倍ずつ大きくしていくと良いでしょう > > 解の精度を上げたい場合には上記の後に以下の手順を行います。 > > 4. 重みを少しずつ小さくしてソルバーを複数回実行します > > * 例えば 0.9 倍ずつ小さくしていくと良いでしょう > 5. 得られた全ての解のうち目的関数の値が最小のものを最終的な解とします ## ペナルティ関数の自動生成 [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) や [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) などのヘルパー関数を用いて制約条件オブジェクト [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)を作成すると、Amplify は必要に応じて自動で最適なペナルティ関数を生成します。 Amplify SDK が制約条件のペナルティ関数を生成するとき、まず、制約条件式の左辺が取りうる値の上限と下限を大まかに見積もります。 この見積もりは、たとえばバイナリ変数多項式の場合は、その多項式に含まれる負の係数の総和と正の係数の総和を計算することで得ることができます。 その後、等式・不等式制約の種類や指定されたアルゴリズムに応じて、以下のようにペナルティ関数を生成します。 ### 等式制約 等式制約 $f(x) = c$ に対して、以下のようにペナルティ関数 $p$ が生成されます。 **(i) 制約条件式の左辺 $f$ の取りうる値の範囲の下限が $c$ と一致する場合** ペナルティ関数 $p$ を $f - c$ とします。 例えばバイナリ変数の積 `q[0] * q[1] = 0` に対しては、$f$ の下限と右辺 $c$ が一致しているので、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = equal_to(q[0] * q[1], 0) >>> print(c.penalty) q_0 q_1 ``` **(ii) 制約条件式の左辺 $f$ の取りうる値の範囲の上限が $c$ と一致する場合** ペナルティ関数 $p$ を $c - f$ とします。 例えばバイナリ変数の積 `q[0] * q[1] = 1` に対しては、$f$ の上限と右辺 $c$ が一致しているので、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = equal_to(q[0] * q[1], 1) >>> print(c.penalty) - q_0 q_1 + 1 ``` **(iii) 上記以外の場合** ペナルティ関数 $p$ を $(f - c)^2$ とします。 例えばバイナリ変数の和 `q[0] + q[1] + q[2] = 2` に対しては、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = equal_to(q[0] + q[1] + q[2], 2) >>> print(c.penalty) 2 q_0 q_1 + 2 q_0 q_2 + 2 q_1 q_2 - 3 q_0 - 3 q_1 - 3 q_2 + 4 ``` > [!NOTE] > > **注釈** > > 上記は、上限値と下限値が一致している不等式制約など等式制約とみなせる場合にも適用されます。 ### 不等式制約 不等式制約のペナルティ関数を生成する場合、まず、制約条件式の左辺が取りうる値の上界と下界の値を用いて制約条件を $a \leq f \leq b$ という形に書き直します。 この形の不等式制約に対してペナルティ関数を生成するアルゴリズムとして、以下のアルゴリズムが提供されています。アルゴリズムの指定は、不等式制約を生成するヘルパー関数 [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal)、[`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal)、[`clamp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) の `penalty_formulation` キーワード引数を用いて行います。デフォルトは [`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default) です。 **[`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default) (Default)** 制約条件式の変数と係数がすべて整数値の場合は [`IntegerVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) アルゴリズムを使用し、そうでない場合は [`RealVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.RealVariable) アルゴリズムを使用します。 **[`IntegerVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable)** 整数値をとる補助変数を用いてペナルティを生成します。不等式制約 $a \leq f \leq b$ に対して $a$ 以上 $b$ 以下の値を取る整数変数 $n$ を発行し、等式制約 $f - n = 0$ のペナルティ関数を不等式制約 $a \leq f \leq b$ のペナルティ関数とします。 ただし、例外的に、$b - a = 1$ となっている場合は、整数変数を発行せずに $(f - a)(f - b) / 2$ がペナルティ関数となります。 > [!WARNING] > > **注意** > > 整数値でない制約条件に [`IntegerVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) を指定した場合、正確な定式化にはならないので注意してください。 例えばバイナリ変数の和 `q[0] + q[1] + q[2] <= 2` に対しては、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = less_equal(q[0] + q[1] + q[2], 2, penalty_formulation="IntegerVariable") >>> print(c.penalty) 2 q_0 q_1 + 2 q_0 q_2 - 2 q_0 n_0 + 2 q_1 q_2 - 2 q_1 n_0 - 2 q_2 n_0 + n_0^2 + q_0 + q_1 + q_2 >>> print(gen.variables[3]) {name: n_0, id: 3, type: Integer, lower_bound: -0, upper_bound: 2} ``` ここで、`n_0` はペナルティ関数の生成と共に発行された整数の補助変数です。 > [!NOTE] > > **注釈** > > [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーなど整数変数を扱えないソルバーでは、中間モデルの構築時に変数変換が行われます。詳細は 「[変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md)」を参照してください。 > > この変数変換では、整数変数の取り得る値の範囲が大きいほど必要な補助変数の数は多くなります。そのため、制約条件の構築時点で両辺を約分するなどして、不等式制約の取り得る範囲を小さくしておくと変数変換が効率化されることがあります。 バイナリ変数の和 `q[0] + q[1] + q[2] <= 1` に対しては、制約条件の左辺 $f$ の下限 $0$ と右辺 $c=1$ の差が 1 なので、整数変数は発行されず以下のようなペナルティ関数が生成されます。 ```pycon >>> c = less_equal(q[0] + q[1] + q[2], 1, penalty_formulation="IntegerVariable") >>> print(c.penalty) q_0 q_1 + q_0 q_2 + q_1 q_2 ``` **[`RealVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.RealVariable)** 実数値をとる補助変数を用いてペナルティを生成します。 不等式制約 $a \leq f \leq b$ に対して $a$ 以上 $b$ 以下の値を取る実数変数 $x$ を発行し、等式制約 $f - x = 0$ のペナルティ関数を不等式制約 $a \leq f \leq b$ のペナルティ関数とします。 例えばバイナリ変数の和 `0.1 * q[0] + 0.2 * q[1] + 0.4 * q[2] <= 0.5` に対しては、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = less_equal(0.1 * q[0] + 0.2 * q[1] + 0.4 * q[2], 0.5, penalty_formulation="RealVariable") >>> print(c.penalty) 0.04 q_0 q_1 + 0.08 q_0 q_2 - 0.2 q_0 x_0 + 0.16 q_1 q_2 - 0.4 q_1 x_0 - 0.8 q_2 x_0 + x_0^2 + 0.01 q_0 + 0.04 q_1 + 0.16 q_2 >>> print(gen.variables[3]) {name: x_0, id: 3, type: Real, lower_bound: 0, upper_bound: 0.5} ``` ここで、`x_0` はペナルティ関数の生成と共に発行された実数の補助変数です。 > [!NOTE] > > **注釈** > > [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) ソルバーなど実数変数を扱えないソルバーでは、実数からバイナリ変数への [変数変換](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md#encode-real) が行われます。この時、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `real_encoding_method` キーワード引数で変換方法を指定しますが、変換に使用するバイナリ変数の数が少ないと、制約条件が正確に表現できないことがあります。 > > このような場合に、実数変数の使用を回避する以下の方法も考えられます。 > > * 制約条件の両辺を定数倍し両辺を整数値にして [`IntegerVariable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) を使用する > * 次で述べる緩和法 ([`Relaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation)) による近似を試みる **[`Relaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation)** 制約条件の左辺 $f$ が二次以上で、制約の範囲と $f$ の下限あるいは上限が一致している場合は [`LinearRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation) を使用し、そうでない場合は [`QuadraticRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation) を使用します。 > [!WARNING] > > **注意** > > 緩和法 ([`Relaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation), [`LinearRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation), [`QuadraticRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation)) によって作られるペナルティ関数は正確な定式化ではないことに注意してください。「[ペナルティ法](#penalty-definition)」で定義されたペナルティ関数の要件をみたさないためです。 > > [`LinearRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation) が適用される場合は $f$ を $a$ あるいは $b$ に近づける方向に、[`QuadraticRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation) が適用される場合は $f$ を $(a + b) / 2$ に近づける方向にペナルティがかかります。しかし、制約を満たす場合にかかるペナルティ値が一定でないため、ペナルティの重みを十分に大きくしても最適解が見つかるとは限りません。そのため、より良い解を見つけるためには、[ペナルティ関数の重み](#penalty-weight) を変更しながら何度もソルバーを実行し、実行可能解の中から最良解を選択するという方針が考えられます。 **[`LinearRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation)** ペナルティ法ではなくラグランジュ緩和を用います。 不等式制約 $a \leq f \leq b$ に対して、$f$ の取りうる値の範囲の下限が $a$ と一致する場合、$f - a$ を規格化したものを生成し、$f$ の取りうる値の範囲の上限が $b$ と一致する場合は、$b - f$ を規格化したものを生成します。どちらでもない場合は [`QuadraticRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation) が使用されます。 例として、バイナリ変数の和 `q[0] + q[1] + q[2] <= 2` に対しては、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = less_equal(q[0] + q[1] + q[2], 2, penalty_formulation="LinearRelaxation") >>> print(c.penalty) 0.5 q_0 + 0.5 q_1 + 0.5 q_2 ``` **[`QuadraticRelaxation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation)** ペナルティ法ではなくラグランジュ緩和を用います。不等式制約 $a \leq f \leq b$ に対して、$(f - \left(a + b\right)/2)^2$ を規格化したものを生成します。 例として、バイナリ変数の和 `q[0] + q[1] + q[2] <= 2` に対しては、以下のようなペナルティ関数が生成されます。 ```pycon >>> c = less_equal(q[0] + q[1] + q[2], 2, penalty_formulation="QuadraticRelaxation") >>> print(c.penalty) 2 q_0 q_1 + 2 q_0 q_2 + 2 q_1 q_2 - q_0 - q_1 - q_2 + 1 ``` ## ペナルティ関数の指定 ヘルパー関数を用いて作成された制約条件に対しては、Amplify が自動でペナルティ関数を指定します。一方で、ユーザが自身で定義したペナルティ関数を設定したい場合には [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) のコンストラクタを呼び出します。 次のように、制約条件の式とペナルティ関数を指定して制約条件オブジェクトを作成することができます。 * 制約条件式が $q_0 + q_1 = 2$ でペナルティが $- q_0 - q_1$ の等式制約を作成する: ```pycon >>> c = Constraint(q[0] + q[1], eq=2, penalty=-q[0] - q[1]) ``` * 制約条件式が $q_0 + q_1 \leq 1$ でペナルティが $q_0 q_1$ の不等式制約を作成する: ```pycon >>> c = Constraint(q[0] + q[1], le=1, penalty=q[0] * q[1]) ``` * 制約条件式が $q_0 + q_1 \geq 1$ でペナルティが $q_0 q_1 - q_0 - q_1$ の不等式制約を作成する: ```pycon >>> c = Constraint(q[0] + q[1], ge=1, penalty=q[0] * q[1] - q[0] - q[1]) ``` * 制約条件式が $1 \leq q_0 + q_1 + q_2 \leq 2$ でペナルティが $(q_0 + q_1 + q_2 - 1)(q_0 + q_1 + q_2 - 2)$ の不等式制約を作成する: ```pycon >>> f = q[0] + q[1] + q[2] >>> c = Constraint(f, bounds=(1, 2), penalty=(f - 1) * (f - 2)) ``` --- # グラフ埋め込み QUBO ソルバーやイジングソルバーの中には、任意の 2 次多項式を受け取れず、入力できる 2 次の項が制限されているものもあります。Amplify SDK は、そのようなソルバーに対して、グラフ埋め込みとよばれる操作を行い、多項式をそのソルバーが受け取れる形に変換します。 グラフ埋め込みが必要なソルバーの代表例は D-Wave のマシンです。D-Wave マシンの QPU には、マシンごとに異なる量子ビット間の物理的なトポロジーが存在するため、この量子ビット間の結合をグラフ構造と見立てた場合に、入力できる二次多項式の項はこのグラフ構造に制限されます。このグラフ構造を物理グラフと呼び、Amplify SDK が構築する中間モデルの多項式のグラフ構造を中間グラフと呼びます。グラフ埋め込みとは、中間グラフを物理グラフに埋め込む操作のことを指します。 > [!NOTE] > > **参考** > > グラフ埋め込みが必要なソルバーは、[こちら](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md#solver-clients)のページで Graph タグがついているソルバーです。 > > D-Wave マシンの QPU のトポロジーについては [D-Wave QPU Architecture: Topologies](https://docs.dwavequantum.com/en/latest/quantum_research/topologies.html) を参照してください。 ## グラフ埋め込みとは 埋め込みが必要なソルバーは、入力できる 2 次項の種類が限られています。つまり、あるインデックスのペアの集合 $E$ があって、入力する多項式に含まれる 2 次項はすべて $$ c_{ab} q_a q_b \quad (c_{ab} \in \mathbb{R}, (a, b) \in E) $$ と表せる必要があります。$E$ は通常、変数をノードとみなし、入力できる 2 次の項に含まれる 2 つの変数をエッジでつないだグラフとして表されます。 また、入力したい多項式に対しても、その多項式に含まれる 2 次の項それぞれに注目し、その 2 つの変数をエッジでつないだグラフを考えることができます。 たとえば、目的関数が $q_0 q_1 + 2 q_1 q_2 - 3 q_0 q_2 + 4 q_2 q_3 - 5 q_3 q_4 - 6 q_2 q_4$ で、ソルバーに入力できる 2 次項を表すグラフ $E$ が $3 \times 4$ の格子グラフである場合、目的関数を変換したグラフ $P$ および $E$ はそれぞれ以下の図のようになります。 [![_images/graph1.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph1.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph1.png) グラフ $P$ [![_images/graph2.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph2.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph2.png) グラフ $E$ ここで、$P$ の各変数を $E$ のノードのうちいくつかに割り当てて、以下の条件をみたすように $P$ と $E$ 上のノードの対応関係を求める操作を **グラフ埋め込み** と呼びます。 * どの $P$ の変数 $q_i$ に対しても、対応する $E$ のノードが一つ以上存在する (1対多の割り当てが許される) * どの $E$ のノード $a$ に対しても、対応する $P$ の変数はたかだか一つである (割り当てに重複が無い) * $P$ 上で $q_i$ と $q_j$ が隣り合っているとき、$q_i$ と $q_j$ それぞれに対応し $E$ 上のどこかで隣り合う $E$ のノード $a$ と $b$ が存在する * すべての $P$ の変数 $q_i$ について $q_i$ に対応する $E$ のノード $a$ からなる $E$ の部分グラフは連結である (チェインと呼ぶ) たとえば、以下の左の図のように $E$ に適当に変数を割り当ててしまうと、$q_0$ が割り当てられているノードと $q_2$ が割り当てられているノードが隣り合っていないので条件をみたしません。一方で、以下の 2 番目の図のように変数を割り当てると条件が満たされます。 [![_images/graph3.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph3.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph3.png) グラフ埋め込みの失敗例 [![_images/graph4.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph4.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/graph4.png) グラフ埋め込みの成功例 グラフ埋め込みに成功した場合、目的関数を以下のようにしてソルバーが受け取れる形に変換できます。 **グラフ埋め込みによる多項式の変換** **目的関数の 2 次の項** 目的関数の 2 次の項 $Q_{ij} q_i q_j$ を $\sum_{a,b} c_{ab} q_a q_b \left( Q_{ij} = \sum_{a,b} c_{ab} \right)$ となるように変換して新たな目的関数に加算する。ここで $q_a$ は $q_i$ が割り当てられた $E$ のノード $a$ の変数、$q_b$ は $q_j$ が割り当てられた $E$ のノード $b$ の変数で、 $a$ と $b$ は隣接している。 **目的関数の 1 次の項** 目的関数の 1 次の項 $Q_{ii} q_i$ を $\sum_{a} c_{aa} q_a \left( Q_{ii} = \sum_{a} c_{aa} \right)$ となるように変換して新たな目的関数に加算する。ここで $q_a$ は $q_i$ が割り当てられた $E$ のノード $a$ の変数とする。 **目的関数の定数項** 新たな目的関数にそのまま加算する。 **チェイン制約** $P$ の変数 $q_i$ に対応する 全ての $E$ のノード $a$ からなる部分グラフについて、隣り合うノード上の変数 $q_{a}$ と $q_{a'}$ が $q_{a} = q_{a'}$ となる制約を満たすようにペナルティ関数を加算する。 1つのチェインに対するペナルティ関数は次のように与えられます。 バイナリ変数 $q$ の場合: $$ \sum_{a, a'} \left( q_a - q_{a'} \right)^2 $$ イジング変数 $s$ の場合: $$ - \frac{1}{2} \sum_{a, a'} s_a s_{a'} $$ 必要なペナルティ関数の重みは $q_i$ の係数に依存します。これをチェイン強度と呼びます。 ソルバーの実行結果はグラフ $E$ 上の変数に対するものになります。そのため、グラフ埋め込みの逆変換を行い元のグラフ $P$ 上の変数の値を決定しなくてはなりません。グラフ $P$ の変数 $q_i$ に対応するグラフ $E$ の変数 $q_a$ は複数存在します。理想的には全ての変数の値 $q_a$ が同じになることですが、実際には異なる値がソルバーから返されることもあります。そのような状況をチェインが壊れていると表現し、ある物理グラフ上の多項式に対してチェインが壊れている割合を **chain break fraction** と呼びます。壊れているチェインについて $q_i$ が二値変数の場合「多数決」によって決定されることが多いです。 ## グラフ埋め込み処理 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の内部では中間モデルの構築後に、必要に応じて自動的にグラフ埋め込みが行われ、その後ソルバーの実行を行います。ここからは Amplify SDK が [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の内部で行っているグラフ埋め込み処理について、ステップごとに詳しく説明します。 以下では、$4 \times 4$ 変数のバイナリ変数からなる目的関数と制約条件を持つモデルに対して [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) を対象にグラフ埋め込みを行う例を示します。 ```python from amplify import DWaveSamplerClient, VariableGenerator, Model, equal_to, to_edges import numpy as np # 変数の生成 gen = VariableGenerator() q = gen.array("Binary", shape=(4, 4)) # 目的関数と制約条件の定義 rng = np.random.default_rng() p = (q[:-1] * q[1:] * rng.uniform(-1, 1, (3, 4))).sum() c = equal_to(q, 1, axis=1) # 入力モデルの作成 m = p + c # ソルバークライアントの作成 client = DWaveSamplerClient() ``` ### 多項式からグラフへの変換 まず、[`to_intermediate_model()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) メソッドを用いて中間モデルを取得します。今回のモデルは二次バイナリ変数で構成されているためこの操作は必須ではないですが、変数変換や次数下げを行う場合は必要になります。 ```python im, im_mapping = m.to_intermediate_model(client.acceptable_degrees) ``` 次に、[`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) は制約条件を扱うことができないため、目的関数に全ての制約条件のペナルティを足し合わせた多項式を計算します。 ```python im_unconstrained = im.to_unconstrained_poly() ``` これでバイナリ変数の二次多項式として中間モデルを取得できました。二次多項式のグラフ表現は [`to_edges`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.to_edges.md#amplify.to_edges) 関数を用いて取得できます。グラフのノードを変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) で表したとき、この関数はエッジを [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) のタプルのリストで返却します。1 次の項は自己ループとして表されます。 ```python edges = to_edges(im_unconstrained) ``` ```python >>> im_unconstrained.variables [Variable({name: q_{0,0}, id: 0, type: Binary}), Variable({name: q_{0,1}, id: 1, type: Binary}), Variable({name: q_{0,2}, id: 2, type: Binary}), ... ] >>> edges [(0, 4), (1, 5), (2, 6), (3, 7), (4, 8), (5, 9), (6, 10), ...] ``` 次のようにして [networkx](https://networkx.org/documentation/stable/index.html) モジュールを用いてグラフを可視化することができます。 ```python import networkx as nx g = nx.Graph() g.add_edges_from(edges) g.remove_edges_from(nx.selfloop_edges(g)) nx.draw(g, with_labels=True) ``` [![_images/64ed5f8ccfd9959ca2ae55e9a485de333f30531a74e35024c8363caac93c0f24.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/64ed5f8ccfd9959ca2ae55e9a485de333f30531a74e35024c8363caac93c0f24.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/64ed5f8ccfd9959ca2ae55e9a485de333f30531a74e35024c8363caac93c0f24.png) ### 物理グラフの取得 グラフ埋め込みが必要なソルバークライアントクラスには、[`graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) アトリビュートがあります。これは [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) クラスのインスタンスであり、ソルバーの物理グラフを表します。[`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) クラスは次のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.type) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | グラフの種類 | | [`shape`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.shape) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`int`](https://docs.python.org/3/library/functions.html#int)] | グラフのサイズパラメータ | | [`nodes`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.nodes) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`int`](https://docs.python.org/3/library/functions.html#int)] | グラフに含まれるノードのリスト | | [`edges`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.edges) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/library/functions.html#int), [`int`](https://docs.python.org/3/library/functions.html#int)]] | グラフのエッジのリスト | | [`adjacency`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.adjacency) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`int`](https://docs.python.org/3/library/functions.html#int)]] | ノードごとの隣接ノードのリスト | [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) を例として、[`graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) アトリビュートを取得します。 ```python from amplify import DWaveSamplerClient client = DWaveSamplerClient() client.solver = "Advantage_system4.1;graph_id=01d07086e1" graph = client.graph ``` ```pycon >>> graph.type 'Pegasus' >>> graph.shape [16] >>> len(graph.nodes) 5627 >>> len(graph.edges) 40279 ``` 物理グラフは、 [networkx](https://networkx.org/documentation/stable/index.html) モジュールを用いて [`edges`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.edges) を描画することで可視化できます。一方で、[dwave-networkx](https://dnx.readthedocs.io/en/latest/index.html) モジュールを用いると [`shape`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.shape) に応じた整ったレイアウトでグラフを描画できます。次の図は、ペガサスグラフ (`shape=4`) をプロットする例です。 ```python import dwave_networkx as dnx p = dnx.pegasus_graph(4) dnx.draw_pegasus(p, with_labels=True) ``` [![_images/6f82485a03e6381526d46b0cbf963bd4b0ed20660a47f1991ff4c667349bee85.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/6f82485a03e6381526d46b0cbf963bd4b0ed20660a47f1991ff4c667349bee85.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/6f82485a03e6381526d46b0cbf963bd4b0ed20660a47f1991ff4c667349bee85.png) ペガサスグラフ (`shape=4`) ### グラフ埋め込みの実行 グラフ埋め込みを実行して埋め込みの情報を取得するには、[`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) 関数を呼び出します。この関数は多項式 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) と [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) クラスのインスタンスを引数に取り、グラフ埋め込み後の多項式とグラフ埋め込みのマッピング、引数の多項式をグラフに変換したものからなるタプルを返します。 ```python from amplify import embed # D-Wave のグラフに対してグラフ埋め込みを行う emb_poly, embedding, src_graph = embed(im_unconstrained, graph) ``` `emb_poly` には [グラフ埋め込みによる多項式の変換](#embed-polynomial) が行われた多項式が返却されます。`embedding` は `im_unconstrained` に使われている変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) から、`emb_poly` に現れる変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) へのマッピング (チェイン) を表すリストです。リストのインデックスは `im_unconstrained` に使われている変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) に対応します。 ```python >>> embedding [array([ 180, 181, 2940], dtype=uint32), array([ 195, 196, 2955], dtype=uint32), array([ 150, 151, 2970], dtype=uint32), array([ 165, 166, 2985], dtype=uint32), ...] ``` `src_graph` は `im_unconstrained` のグラフ表現です。`im_unconstrained` に [`to_edges`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.to_edges.md#amplify.to_edges) 関数を適用した場合と同じ結果が返ります。 次のように [dwave-networkx](https://dnx.readthedocs.io/en/latest/index.html) モジュールを用いてグラフ埋め込みを可視化できます。 ```python p = dnx.pegasus_graph(*graph.shape) dnx.draw_pegasus_embedding( p, emb={i: v.tolist() for i, v in enumerate(embedding)}, embedded_graph=g, show_labels=True ) ``` [![_images/f189634ca396139fe6744f9b337f9ae730655d61246fd529bef2ef7530245618.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/f189634ca396139fe6744f9b337f9ae730655d61246fd529bef2ef7530245618.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/f189634ca396139fe6744f9b337f9ae730655d61246fd529bef2ef7530245618.png) ペガサスグラフ (`shape=16`) へのグラフ埋め込み例 上の図で、ノードに書かれた番号は埋め込み前の多項式 `im_unconstrained` の変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) を表します。同じ色で繋がった複数のノードはチェインを表し、埋め込み前の 1 つの変数に対応します。また、異なる色のノード同士を結ぶ黒い線は、埋め込み前の多項式 `im_unconstrained` に含まれる 2 次の項に対応する物理グラフ上のエッジを表します。 ## グラフ埋め込みの実行パラメータ グラフ埋め込みの実行に関する以下のパラメータが提供されています。埋め込みの実行パラメータは、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数および [`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) 関数のキーワード引数として指定することができます。 | パラメータ | 説明 | | --- | --- | | `embedding_timeout` | グラフ埋め込み探索のタイムアウト | | `embedding_method` | グラフ埋め込みに使用するアルゴリズム | | `chain_strength` | 目的関数に足されるチェインペナルティの重み | ### 埋め込みのタイムアウト [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数または [`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) 関数の `embedding_timeout` キーワード引数に数値または [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) オブジェクトを与えることで、グラフ埋め込みに使用する時間のタイムアウトを指定することができます。デフォルトは 10 秒です。 ### 埋め込みのアルゴリズム 以下のアルゴリズムが提供されています。埋め込みアルゴリズムを指定したい場合は、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数または [`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) 関数の `embedding_method` キーワード引数に指定します。 **[`Clique`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique)** 埋め込み対象のグラフのノード数と同一の全結合グラフの埋め込みを探索します。 一度探索されたクリーク埋め込みはキャッシュ化されます。対象のグラフのノード数のみに依存するためキャッシュを利用した高速な探索が可能なことがあります。 しかし、クリーク埋め込みが可能な最大ノード数は物理グラフのみで決まるため、本質的に埋め込みが可能なノード数を超えるグラフでは必ず失敗します。 **[`Minor`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor)** [minorminer](https://github.com/dwavesystems/minorminer) を用いたマイナー埋め込みを行います。 対象のグラフが疎であれば、[`Clique`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) 埋め込みより効率の良い (チェインの短い) 埋め込みが期待出来ることや、[`Clique`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) 埋め込みが失敗するようなサイズの入力に対してもマイナー埋め込みなら成功する可能性があります。 探索のタイムアウト時間は `embedding_timeout` キーワード引数で指定します。 **[`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Default) (Default)** 最初に [`Clique`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) 埋め込みを試みて、失敗した場合は [`Minor`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) 埋め込みに切り替えます。 **[`Parallel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Parallel)** [`Clique`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) 埋め込みと [`Minor`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) 埋め込みを並列に実行し、チェインの変数の数が少ない方の結果を選択します。 ### チェイン強度 目的関数をグラフ埋め込みに応じて変換するとき、同じ入力変数に割り当てられたノードがすべて同じ値をとるように[チェイン制約](#chain-constraint)がかけられます。Amplify SDK は自動でチェイン制約のペナルティを埋め込み後の多項式に追加しますが、この時のペナルティの重みの初期値は、埋め込み前の多項式の 2 次の係数の二乗平均平方根を変数の数で割ったものになります。[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数または [`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) 関数の `chain_strength` キーワード引数を与えることで、このペナルティの相対的な重みを設定することができます。デフォルトは 1.0 です。 > [!IMPORTANT] > > **重要** > > 上記の二乗平均平方根による初期値の設定は [D-Wave の実装](https://docs.ocean.dwavesys.com/projects/system/en/latest/reference/generated/dwave.embedding.chain_strength.uniform_torque_compensation.html) に基づくものです。Amplify SDK での計算方法は将来的に変更される可能性があります。 ## ソルバーの実行結果とグラフ変換 Amplify SDK はグラフ埋め込みが必要なソルバーが指定された場合、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数内でグラフ埋め込みを行います。どのような埋め込みが行われたかの情報は、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) アトリビュートに [`GraphConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) クラスのインスタンスとして格納されます。 > [!NOTE] > > **注釈** > > グラフ埋め込みが不要なソルバーに対しては、[`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) アトリビュートは [`None`](https://docs.python.org/3/library/constants.html#None) を返すことに注意してください。 [`GraphConversion`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) クラスは以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`src_graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.src_graph) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/library/functions.html#int), [`int`](https://docs.python.org/3/library/functions.html#int)]] | 中間モデルの目的関数と制約条件のペナルティを足した多項式のグラフの表現 | | [`dst_graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.dst_graph) | [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) | ソルバー固有の物理グラフ | | [`chains`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chains) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)] | 中間モデルの変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) と物理グラフ上の変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) の対応を表すリスト | | [`poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) | [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | 中間モデルの多項式に対してグラフ埋め込みを行った結果の多項式 | | [`num_variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.num_variables) | [`int`](https://docs.python.org/3/library/functions.html#int) | [`poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) の変数の数 | | [`values_list`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.values_list) | [`ValuesList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ValuesList) | ソルバーが返した解 | | [`chain_break_fractions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chain_break_fractions) | [`ChainBreakFractions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.ChainBreakFractions) | ソルバーが返した各々の解においてチェインが壊れている割合 | 例として、次のモデルに対して [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) を用いて [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を実行した結果から、グラフ埋め込みの情報を取得します。 ```python from amplify import VariableGenerator, Model, DWaveSamplerClient, solve gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] + 2 * q[1] * q[2] - 3 * q[0] * q[2] model = Model(objective) client = DWaveSamplerClient() client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" result = solve(model, client) ``` [`src_graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.src_graph) アトリビュートにより、中間モデルのペナルティ関数込みの多項式をエッジのリストに変換したものが取得できます。 ```python >>> result.embedding.src_graph [(0, 1), (1, 2), (0, 2)] ``` 中間モデルの多項式に含まれる変数の [`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) は以下のようにして調べることができます。 ```python >>> im_unconstrained = result.intermediate.model.to_unconstrained_poly() >>> print(im_unconstrained) q_0 q_1 - 3 q_0 q_2 + 2 q_1 q_2 >>> im_unconstrained.variables [Variable({name: q_0, id: 0, type: Binary}), Variable({name: q_1, id: 1, type: Binary}), Variable({name: q_2, id: 2, type: Binary})] ``` [`dst_graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.dst_graph) アトリビュートは、物理グラフとしてソルバークライアントの [`graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) アトリビュートと同一の [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) クラスのインスタンスを返します。 ```python >>> result.embedding.dst_graph.type 'Pegasus' >>> result.embedding.dst_graph.shape [16] ``` [`chains`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chains) アトリビュートは、中間レイヤの変数とソルバーの変数の間のマッピングを表します。[`chains`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chains) はチェインのリストとして表され、各チェインは 1 次元の [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) オブジェクトとして表されます。たとえば以下の例では、中間レイヤの 0 番目の変数は 2940 番の変数のみに対応することが分かります。 ```python >>> result.embedding.chains [array([2940], dtype=uint32), array([2955], dtype=uint32), array([45], dtype=uint32)] >>> print(result.embedding.chains[0]) [2940] ``` [`poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) アトリビュートからグラフ埋め込み後の多項式が取得できます。これは実際にソルバーに入力された多項式と同一のものです。 ```python >>> print(result.embedding.poly) - 3 q_{45} q_{2940} + 2 q_{45} q_{2955} + q_{2940} q_{2955} ``` [`num_variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.num_variables) アトリビュートは、[`poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) アトリビュートに含まれる変数の数を表します。問題の簡単さを表す 1 つの指標として使うことができ、一般的には、この値が小さいほど解きやすい問題であるといえます。 ```python >>> result.embedding.num_variables 3 ``` [`values_list`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.values_list) アトリビュートによりソルバーが返した解の値のリストを取得できます。これはソルバーが返した解の個数と同じ長さを持つ list ライクなオブジェクトで、それぞれの要素はソルバーが返した解に対応します。解は辞書として表現され、キーはソルバーの変数です。 ```python >>> print(result.embedding.values_list) [{q_{45}: 1, q_{2940}: 1, q_{2955}: 0}] ``` [`chain_break_fractions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chain_break_fractions) アトリビュートは、ソルバーが返したそれぞれの解について、[チェイン制約](#chain-constraint) が壊れている割合を表します。 適切な値は一般に問題によって異なり、必ずしも 0 である必要は無いと考えられています。もし、この値が大き過ぎることで良い解が得られない場合には、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `chain_strength` キーワード引数に 1.0 より大きな値を与え、逆に小さすぎる場合には 1.0 より小さな値を与えることで、性能が改善することがあります。 ```python >>> print(result.embedding.chain_break_fractions) [0] ``` > [!TIP] > > **Tip** > > [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトに解が含まれていない場合、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトの [`filter_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) プロパティを False に指定することでソルバーが返した解をすべて取得することができます。詳しくは[解のフィルター](https://amplify.fixstars.com/ja/docs/amplify/v1/solve.md#filter-solution)を参照してください。 --- # 実行結果の評価 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行結果には、解に関する情報やモデル変換の情報・実行時間情報などさまざまな情報が含まれています。このページでは、これらの情報を取得し、活用する方法について説明します。 以下は、[`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を用いて、目的関数と制約条件で構成されたモデルに対して、求解の実行結果を取得する例です。 ```python from datetime import timedelta from amplify import VariableGenerator, equal_to, AmplifyAEClient, solve # 決定変数の配列を生成 gen = VariableGenerator() q = gen.array("Binary", 5) # 目的関数と制約条件を作成 objective = q[0] * q[1] - q[2] constraint = equal_to(q[0] + q[1] + q[2], 1) # モデルの定義 model = objective + constraint # ソルバークライアントの作成 client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) # 実行結果の取得 result = solve(model, client) ``` ## 実行結果クラス [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスから、解に関する情報やモデル変換の情報・実行時間情報などを取得する方法を以下に示します。 ### 解に関する情報 入力モデルに対する解は、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) アトリビュートに格納されています。[`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) アトリビュートは [`SolutionList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.SolutionList) クラスのインスタンスであり、[`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスを要素に持つリストのように振る舞います。 ```pycon >>> type(result.solutions[0]) ``` [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスは解を表すクラスであり、以下のアトリビュートを持ちます。 | アトリビュート名 | 型 | 概要 | | --- | --- | --- | | [`objective`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) | [`float`](https://docs.python.org/3/library/functions.html#float) | 目的関数の値 | | [`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) | [`amplify.Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) | 解における各変数の値 | | [`feasible`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | 制約条件がみたされているかどうか | | [`time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | 解が得られた時刻 | このうち、[`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) アトリビュートの型である [`Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) クラスは解の値を表すクラスであり、変数をキーとし解の値を値とする辞書のように振る舞います。 ```pycon >>> solution = result.solutions[0] >>> solution.values Values({Poly(q_0): 0, Poly(q_1): 0, Poly(q_2): 1}) >>> solution.values[q[0]] 0.0 >>> solution.values[q[2]] 1.0 ``` また、変数配列クラスや多項式クラスの [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate) メソッドや制約条件クラスの [`is_satisfied()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.is_satisfied) メソッドを使用することにより、[`Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) クラスにより表される解の値を変数配列や多項式・制約条件に代入した結果を得ることができます。詳しくは以下の [決定変数の評価](#variable-evaluation)、[多項式の評価](#polynomial-evaluation)、[制約条件の評価](#constraint-evaluation) セクションを参照してください。 [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスは、[`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) アトリビュート以外にも解にアクセスするためのショートカットをいくつか提供しています。 まず、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) アトリビュートにより、最良解が取得できます。また、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスから直接インデックスによるアクセスを行うことも可能です。 ```pycon >>> result.best.values Values({Poly(q_0): 0, Poly(q_1): 0, Poly(q_2): 1}) >>> len(result) 1 >>> result[0].values Values({Poly(q_0): 0, Poly(q_1): 0, Poly(q_2): 1}) ``` ### モデル変換に関する情報 以下のアトリビュートにより、モデル変換に関する情報を取得できます。詳細は [モデルの変換](https://amplify.fixstars.com/ja/docs/amplify/v1/conversion.md) を参照してください。 | | | | --- | --- | | [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | 中間モデルに関する情報 | | [`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | グラフ埋め込みに関する情報 | ### ソルバーのレスポンスに関する情報 [`solve`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数はモデルの変換やグラフ埋め込み処理を行った後、ソルバークライアントの `solve(...)` メソッドを呼び出してソルバーを実行します。このときソルバークライアントが返却したオブジェクトは、[`client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) アトリビュートにより取得できます。 ```pycon >>> type(result.client_result) ``` [`client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) の型はソルバークライアントの型に依存します。それぞれのソルバークライアントの結果型の詳細については、[クライアントの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md) およびそのサブページを参照してください。 ### 実行時間に関する情報 以下のアトリビュートにより、実行時間に関する情報を取得できます。詳細は [実行時間情報の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/timing.md) を参照してください。 | | | | --- | --- | | [`total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) にかかった時間 | | [`response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | ソルバーにリクエストを送ってからレスポンスが返ってくるまでの時間 | | [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | ソルバーが求解に費やした時間 | ## 決定変数の評価 定式化に使用した決定変数配列に対して、ソルバーの実行結果を決定変数の配列に代入した結果を取得できます。このとき、代入結果は決定変数配列と同じ [`shape`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape) を持つ NumPy 配列として得られます。 次のようにして、[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) の [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドに [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) オブジェクトの [`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) アトリビュートを渡すことで、実行結果に含まれる最良解の値を決定変数の配列で評価できます。 > [!TIP] > > **Tip** > > 実行結果に含まれる解は、実行結果の最良解を [`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) アトリビュートで取得するか、あるいはリストと同じように要素アクセスを行うことで取得できます。 ```pycon >>> print(result.best.values) {q_0: 0, q_1: 0, q_2: 1} >>> q_values = q.evaluate(result.best.values) >>> print(q_values) [0. 0. 1. 0. 0.] ``` もし、上記の `q[3]` や `q[4]` のように、定式化に使われなかった変数が含まれている場合、デフォルトではその変数がとりうる値から適当に一つ選んで代入されます。上記ではバイナリ変数のデフォルト値として `0` が代入されています。 [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドに `default` キーワード引数を与えることで、評価が行われない場合に用いられる値を変更できます。`default` キーワード引数に数値を与えた場合、ソルバーに渡されなかった変数にはその値が代入されます。 ```pycon >>> q_values = q.evaluate(result.best.values, default=3) Warning: Substituting variable q_3 with 3 is out of bounds. Warning: Substituting variable q_4 with 3 is out of bounds. >>> print(q_values) [0. 0. 1. 3. 3.] ``` > [!NOTE] > > **注釈** > > 上記で与えた初期値 `default=3` のように、変数の範囲外の値を指定すると警告が表示されます。 `default` キーワード引数に [`None`](https://docs.python.org/3/library/constants.html#None) を与えた場合、ソルバーに渡されなかった変数はそのまま残ります。この場合のみ、[`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドは [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) を返します。 ```pycon >>> q_values = q.evaluate(result.best.values, default=None) >>> print(q_values) [ 0, 0, 1, q_3, q_4] ``` > [!WARNING] > > **注意** > > モデルに含まれる変数であってもソルバーに渡されない場合があります。ペナルティ関数の生成やグラフ埋め込みなどといったモデル変換により、項同士が相殺される可能性があるためです。 ## 多項式の評価 入力モデルの目的関数を [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返した解で評価した結果は、[`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) オブジェクトの [`objective`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) アトリビュートで取得できます。 ```pycon >>> solution = result.best >>> solution.objective -1.0 ``` 一方で、例えば目的関数がいくつかの多項式の和として表されるときなど、目的関数以外の多項式をソルバーが返した解で評価したい場合があります。この場合、変数の配列の評価と同様に、[`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) の [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate) メソッドに [`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) オブジェクトの [`values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) アトリビュートを渡します。 ```pycon >>> objective_1 = q[0] * q[1] # 目的関数の第 1 項 >>> objective_1.evaluate(solution.values) 0.0 ``` > [!TIP] > > **ヒント** > > 多項式にソルバーに渡されなかった変数が含まれている場合の動作は、[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスの [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) メソッドと同様です。`default` キーワード引数によってこの動作を変更できます。 ## 制約条件の評価 実行結果の解が制約条件が満たされているかどうかを知りたい場合は、[`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) クラスの [`feasible`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) アトリビュートで確認できます。 ```pycon >>> solution.feasible True ``` デフォルトでは、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数はモデルに含まれる全ての制約条件を満たす解だけが取得できるようにフィルタされているため、上記は必ず [`True`](https://docs.python.org/3/library/constants.html#True) になります。この動作を変更して、ソルバーの出力する解で制約条件を満たさないものも取得できるようにするには、前もって [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の `filter_solution` キーワード引数に [`bool`](https://docs.python.org/3/library/functions.html#bool) を渡すか、あるいは後から [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`filter_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) に [`False`](https://docs.python.org/3/library/constants.html#False) を設定します。 あえてモデルに矛盾して満たせない制約条件を追加して、このことを確認してみます。 ```python # 目的関数と制約条件を作成 objective = q[0] * q[1] - q[2] constraint1 = equal_to(q[0] + q[1] + q[2], 1, label="sum equals one") constraint2 = equal_to(q[0] + q[1] + q[2], 2, label="sum equals two") # モデルの定義 (矛盾する制約条件が含まれる) model = objective + constraint1 + constraint2 # 実行結果の取得 result = solve(model, client) ``` 解のフィルタが有効な場合は [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) から解が取得できません。 ```python >>> result.best.feasible Traceback (most recent call last): File "", line 1, in RuntimeError: result has no feasible solution ``` 解のフィルタを無効にすると、制約条件を満たさない解も取得できるようになります。 ```pycon >>> result.filter_solution = False >>> result.best.feasible False ``` モデルの構成、ペナルティ関数の重みやソルバーの設定など、何らかの理由で制約条件を満たさない解が取得された場合、どの制約条件が満たされなかったのかを特定したいことがあります。 [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) クラスの [`is_satisfied()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.is_satisfied) メソッドに [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返した解を渡すと制約条件を満たしているかどうかが確認できます。 ```python >>> constraint1.is_satisfied(result.best.values) True >>> constraint2.is_satisfied(result.best.values) False ``` 上記の例では `constraint2` が満たせなかったことがわかります。 次のようにして、モデルに含まれる制約条件のリストから機械的に制約条件を満たさないものを特定することもできます。これはペナルティ関数の重みを調整して再実行するときに利用すると便利です。 ```python >>> list(c for c in model.constraints if not c.is_satisfied(result.best.values)) [Constraint({conditional: q_0 + q_1 + q_2 == 2, weight: 1, label: "sum equals two"})] ``` --- # 実行時間情報の取得 Amplify SDK は、組合せ最適化問題を解く一連のシーケンスにおいて、実行時間に関する情報を取得するインターフェースを提供しています。 [![_images/timing_light.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_light.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_light.drawio.svg) [![_images/timing_dark.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_dark.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_dark.drawio.svg) ## 実行時間情報の種類 取得できる実行時間情報の種類は以下の表の通りです。[`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) オブジェクトとして取得することができます。 | | | | --- | --- | | [`amplify.Result.total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | [`amplify.solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) にかかった時間を表します。 | | [`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | ソルバーにリクエストを送ってからレスポンスが返ってくるまでの時間を表します。 | | [`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | ソルバーが求解に費やした時間を表します。 | | [`amplify.Result.Solution.time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | ソルバーが返したそれぞれの解について、ソルバーが求解を始めてからその解が得られるまでの時間を表します。 | ## 実行時間の取得例 実行時間を取得する例を以下に示します。まず、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を実行して [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトを得ます。 ```python from amplify import VariableGenerator, one_hot, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint = one_hot(q) model = objective + constraint client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) result = solve(model, client) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) アトリビュートは [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の開始から終了までにかかった時間を表します。これは、ソルバーのレスポンス時間に加えて、モデルの変換やソルバーに渡すリクエストデータの作成にかかった Amplify SDK の処理時間を含みます。 ```pycon >>> result.total_time datetime.timedelta(seconds=1, microseconds=870877) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) アトリビュートは [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数内でソルバーにリクエストを送ってからレスポンスが返ってくるまでの時間を表します。 ```pycon >>> result.response_time datetime.timedelta(seconds=1, microseconds=865211) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) の [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) アトリビュートは、ソルバーが求解に使用した時間を表します。これは通常、ソルバーのレスポンスに含まれる値が用いられます。 ```pycon >>> result.execution_time datetime.timedelta(microseconds=980543) ``` [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) に含まれるそれぞれの解 ([`Solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution)) について、ソルバーが求解を始めてからその解を見つけるまでの時間を [`time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) アトリビュートにより取得することができます。これは通常、ソルバーのレスポンスに含まれる値が用いられますが、ソルバーがそのような情報を返却しない場合は [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) と同じ値が入ります。 ```pycon >>> result.best.time datetime.timedelta(microseconds=27925) ``` [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数に `dry_run` オプションをつけて実行した場合、[`total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) は Amplify SDK がモデル変換やリクエストデータの作成を行うのにかかった時間とおおよそ等しくなります。また、[`response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) および [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) は 0 になります。 ```pycon >>> dry_run_result = solve(model, client, dry_run=True) >>> dry_run_result.total_time datetime.timedelta(microseconds=59) ``` ## 解の取得時刻のプロット 複数の解を返すように設定されたソルバーに対して、ソルバーがそれぞれの解を得た時刻をプロットする方法を紹介します。これを用いると、与えられたソルバーの実行時間の範囲においてソルバーがある時刻でどのような解を見つけたのかを確認することができます。解の収束の様子などから実行時間の過不足の判断に用いると良いでしょう。 例として、50 都市のランダムな巡回セールスマン問題に対して、Amplify AE がどのように解に対応する目的関数値を更新していくのかを図示します。 まず、モデルの作成を行います。定式化の詳細については[巡回セールスマン問題](https://amplify.fixstars.com/ja/docs/amplify/v1/tsp.md)を参照してください。 ```python import numpy as np from amplify import VariableGenerator, einsum, one_hot N = 50 x = np.random.rand(N) y = np.random.rand(N) d = ( (x[:, np.newaxis] - x[np.newaxis, :]) ** 2 + (y[:, np.newaxis] - y[np.newaxis, :]) ** 2 ) ** 0.5 gen = VariableGenerator() q = gen.array("Binary", N + 1, N) q[-1, :] = q[0, :] objective = einsum("ij,ki,kj->", d, q[:-1], q[1:]) constraints = one_hot(q[:-1], axis=1) + one_hot(q[:-1], axis=0) model = objective + d.max() * constraints ``` ソルバークライアントを設定します。デフォルトでは Amplify AE v1 は探索中に見つけた解をすべて返します。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() client.parameters.time_limit_ms = 1000 # 実行時間 1000 ms ``` ソルバーの実行を行い、得られた全ての解の時刻と目的関数の値を図示します。 ```python from amplify import solve import matplotlib.pyplot as plt # ソルバーの実行 result = solve(model, client) # それぞれの解の時刻と目的関数の値を取得 times = [solution.time.total_seconds() for solution in result] objective_values = [solution.objective for solution in result] # プロット plt.scatter(times, objective_values) plt.plot(times, objective_values) plt.xlabel("elapsed time in seconds") plt.ylabel("objective value") plt.grid(True) ``` [![_images/b69eaf384e182b1974fdd25d0c36c3622ab57fd44ad03bb713b713518ed4e5e1.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/b69eaf384e182b1974fdd25d0c36c3622ab57fd44ad03bb713b713518ed4e5e1.png)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/b69eaf384e182b1974fdd25d0c36c3622ab57fd44ad03bb713b713518ed4e5e1.png) 50都市の巡回セールスマン問題における Amplify AE の取得した解の更新履歴 次のようにして、探索の初期解と最良解を取得し、各々をプロットして比較することもできます。 ```python def tsp_plot(q_values, x, y): route_x = q_values @ x route_y = q_values @ y plt.scatter(x, y) plt.plot(route_x, route_y) plt.show() # 初期解のプロット tsp_plot(q.evaluate(result[-1].values), x, y) # 最良解のプロット tsp_plot(q.evaluate(result[0].values), x, y) ``` ![_images/8cd71b9474a088ff2d0159cc57d7c1153fa4024b9f509027208816c5756685a4.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/8cd71b9474a088ff2d0159cc57d7c1153fa4024b9f509027208816c5756685a4.png) 初期解 (0.02 秒) の経路 ![_images/11c4b8d4c48b2bbabd3d1e5974c4425bd7c1ba33cdbdb588a7d2bdb27c14a7d2.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/11c4b8d4c48b2bbabd3d1e5974c4425bd7c1ba33cdbdb588a7d2bdb27c14a7d2.png) 最良解 (0.74 秒) の経路 --- # クライアントの詳細 Amplify SDK には Amplify SDK から実行できるソルバーに対応したクライアントクラスが用意されています。クライアントクラスは各ソルバーの API をラップしたものであり、ソルバーの設定や実行パラメータの設定を行うインターフェースや、API のリクエストを行うメソッドを提供します。 ソルバーの提供形態は、WEB API、実行ファイル、ライブラリ API など様々ですが、ソルバーのクライアントクラスを通じて統一的に扱うことができます。また、Amplify SDK はクライアントクラスの共通インターフェースを用いる事で、モデル変換やグラフ埋め込み処理に加えて、ソルバーの実行や結果の解析の抽象化を可能にしています。 このページではソルバークライアントの提供する共通のインターフェースについて説明し、各ソルバークライアント固有の機能や特徴についてはそれぞれのサブページで解説します。 ## クライアントクラス クライアントクラスは、大別すると以下の 3 種類のインターフェースを提供します。 * ソルバーの実行パラメータの設定 * クライアントの設定やソルバー情報の取得 * ソルバーの提供する API の呼び出し ソルバークライアントの共通インターフェースは次の通りです。一部のソルバーでのみ有効なインターフェースについては、[ソルバークライアントの一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md#solver-clients)にて各ソルバーに付与されている tag で分類しています。また、ソルバー固有のインターフェースについては、各ソルバーのサブページを参照してください。 **実行パラメータの取得と設定**: **`parameters`: [`object`](https://docs.python.org/3/library/functions.html#object)** ソルバーの実行パラメータを取得・指定するパラメータクラスを返します。 パラメータクラスの型はソルバーによって異なりますが、可能な限り全ての実行パラメータを取得・設定できるように設計されています。 パラメータの詳細は各ソルバーのサブページとソルバーのAPIリファレンスを参照してください。 > [!NOTE] > > **注釈** > > 全てのソルバーのアトリビュートにおいて、 [`None`](https://docs.python.org/3/library/constants.html#None) の設定が可能な場合は未設定状態を表します。 > [`None`](https://docs.python.org/3/library/constants.html#None) が設定されたアトリビュートは設定そのものが行われず、リクエストデータへの追加も行われません。 > これはソルバーにデフォルト値を使用させるための仕様です。 **ソルバー情報の取得**: **`acceptable_degrees`: [`amplify.AcceptableDegrees`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees)** ソルバーの扱える問題の次数を取得します。詳細は [変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md) を参照してください。 **`version`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** ソルバーのバージョン情報を取得します。 リモートソルバーの場合は `token` の設定が必要になることがあります。これは API への問い合わせが行われることがあるためです。 ローカルソルバーの場合は実行ファイルやライブラリのバージョン情報を取得します。 **二次多項式のグラフ構造** Graph: **`graph`: [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph)** ソルバー固有のグラフ構造を取得します。詳細は [グラフ埋め込み](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md) を参照してください。 **WEB API の接続設定** ☁️ Cloud: **`url`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** ソルバーのエンドポイント URL を取得・指定します。 **`token`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** API トークン等の認証情報を取得・指定します。 **`proxy`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** 接続に用いるプロキシサーバを取得・指定します。詳細は [プロキシサーバの設定](https://amplify.fixstars.com/ja/docs/amplify/v1/proxy.md) を参照してください。 **実行ファイル・ライブラリパスの設定** 💻 Local: **`library_path`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** ソルバーのライブラリのファイルパスを指定します。 **送受信データの保存** ☁️ Cloud 💻 Local: **`write_request_data`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** ソルバーに送信されたリクエストデータを指定されたファイルパスに保存します。データ形式はソルバーごとに異なります。 **`write_response_data`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** ソルバーから受信したレスポンスデータを指定されたファイルパスに保存します。データ形式はソルバーごとに異なります。 **ソルバーの実行**: **`solve(...)`:** ソルバーを実行する関数として 各ソルバークライアントには、`solve(...)` メソッドが実装されています。これはソルバーの API のラッパー関数です。 > [!NOTE] > > **注釈** > > 通常はユーザが直接このメソッドを呼び出す必要はありません。代わりに [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を使用してください。 引数には、ソルバーの API へ入力可能な形式に応じて、多項式 ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly))、行列形式 ([`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) または制約条件 ([`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) あるいは [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList))、そしてその両方のいずれかを与えて API を呼び出すことができます。しかし、グローバルの [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数とは異なり、モデル変換やグラフ埋め込み等が行われることはありません。そのため、ソルバーの扱えない変数の種類や次数、制約条件を与えた場合には例外を送出します。 `solve(...)` メソッドの返り値型はソルバーごとに異なり、たとえば Amplify AE ([`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)) の場合は [`amplify.AmplifyAEClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result) クラスのインスタンスとなります。このクラスは、ソルバーが返すレスポンスデータのデータ構造を極力変えないようにしてクラス化したものです。 ### [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数との連携 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数はモデルの変換やグラフ埋め込み処理を行った後、ソルバークライアントの `solve(...)` メソッドを呼び出してソルバーを実行し、返却されたデータを解析することで解や実行時間の情報を得ます。 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の返却する [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのインスタンスには、ソルバーの返却したデータや応答時間、実行時間が次のアトリビュートに格納されます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`amplify.Result.client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | `Client.Result` | ソルバークライアントの実行結果 (レスポンスデータ) | | [`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | ソルバー内部の実行時間 | | [`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | ソルバーの応答時間 | --- # Fixstars Amplify ## Fixstars Amplify Annealing Engine v1 Fixstars Amplify Annealing Engine (以下 Amplify AE) は Fixstars Amplify 社の提供するソルバーです。シミュレーテッドアニーリングをベースとしたヒューリスティックアルゴリズムが GPU 上に実装されており、GPU の持つ並列計算技術を活用して解を高速・高精度に探索します。 > [!TIP] > > **Tip** > > [ユーザ登録](https://amplify.fixstars.com/register)を行うと無償の API トークンを入手できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.parameters) | [`amplify.AmplifyAEClient.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.AmplifyAEClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.AmplifyAEClient.Result.execution_time_ms`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result.execution_time_ms) | | API 方式 | REST API (JSON) | | リファレンス | [📖 Documents](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae.md) | * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) プロパティに [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Constraint) が設定されている場合 (デフォルト): | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 4次 | - | - | - | | 等式制約 | 4次 | - | - | - | | 不等式制約 | 4次 | - | - | - | * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) プロパティに [`Pubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Pubo) が設定されている場合: | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 4次 | - | - | - | | 等式制約 | 4次\* | - | - | - | | 不等式制約 | 4次\* | - | - | - | \*: ペナルティ関数を与える必要があります。 * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) プロパティに [`Qubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Qubo) が設定されている場合: | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | 2次\* | - | - | - | | 不等式制約 | 2次\* | - | - | - | \*: ペナルティ関数を与える必要があります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) | [`Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver) | Amplify AE の求解モードを設定します。デフォルトは [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Constraint) です。[`Pubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Pubo) または [`Qubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Qubo) に設定することで、それぞれ PUBO / QUBO ソルバーを模した求解が可能です。詳細は Amplify AE の[ドキュメント](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae.md)を参照してください。 | | [`compression`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | リクエストデータを圧縮して送信します。デフォルトは [`True`](https://docs.python.org/3/library/constants.html#True) です。[`False`](https://docs.python.org/3/library/constants.html#False) に設定することでリクエストデータの圧縮時間を削減できますが、通信時間が増加する可能性があります。 | **設定例**: 以下に設定例を示します。パラメータの詳細は [Amplify AE のドキュメント](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/api_reference.md) を参照してください。 ```python from amplify import AmplifyAEClient from datetime import timedelta client = AmplifyAEClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 求解モードの指定 client.solver = "Constraint" # 一般向け (デフォルト) # client.solver = "Pubo" # PUBO シミュレーション用途 # client.solver = "Qubo" # QUBO シミュレーション用途 # 実行時間を 1 秒に設定 client.parameters.time_limit_ms = timedelta(milliseconds=1000) # 使用する GPU 数を 1 に設定 client.parameters.num_gpus = 1 # 探索中に得られた全ての重複解を取得 client.parameters.duplicate_solutions = True ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ソルバーのバージョンと GPU 名を取得: ```python >>> client.version '1.0.0+V100' ``` [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solvetiming)を取得: ```python # GPU のアニーリング時間を取得 >>> print(result.client_result.execution_time_ms) 0:00:01.008328 # キュー待ち時間を取得 >>> print(result.client_result.queue_time_ms) 0:00:00.000108 # リクエストを受信した時刻を取得 >>> print(result.client_result.submitted_at) 2025-08-25 17:37:38.553593+09:00 # リクエストの処理を開始した時刻を取得 >>> print(result.client_result.started_at) 2025-08-25 17:37:38.553701+09:00 ``` [求解情報](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solveinfo)を取得: ```python # 求解に使用した GPU 数 >>> result.client_result.num_gpus 1 # 実行結果を返却するまでに試行した全 GPU の合計フリップ数 >>> result.client_result.num_flips 1567467520 # 実行結果を返却するまでに得られた解の数 (サンプリング数) >>> result.client_result.num_samplings 58 ``` ## [Deprecated] Fixstars Amplify Annealing Engine v0 > [!IMPORTANT] > > **Deprecated** > > Amplify AE v0 は非推奨となりました。これに伴い、[`amplify.FixstarsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) も同様に非推奨となりました。 > 新規の利用では Amplify AE v1 及び [`amplify.AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を使用してください。 [Fixstars Amplify](https://amplify.fixstars.com/) の提供する QUBO ソルバーです。GPU で実装された Simulated Annealing をベースとしたアルゴリズムが用いられています。 > [!TIP] > > **Tip** > > [ユーザ登録](https://amplify.fixstars.com/register)を行うと無償の API トークンを入手できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.FixstarsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.parameters) | [`amplify.FixstarsClient.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FixstarsClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FixstarsClient.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Result.execution_time) | | API 方式 | REST API (JSON) | | API リファレンス | [📖 API Reference](https://amplify.fixstars.com/ja/docs/amplify/v0/amplify-ae/reference.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | 2次\* | - | - | - | | 不等式制約 | 2次\* | - | - | - | \*: ペナルティ関数を与える必要があります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`compression`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | リクエストデータを圧縮して送信します。デフォルトは [`True`](https://docs.python.org/3/library/constants.html#True) です。[`False`](https://docs.python.org/3/library/constants.html#False) に設定することでリクエストデータの圧縮時間を削減できますが、通信時間が増加する可能性があります。 | **設定例**: ```python from amplify import FixstarsClient from datetime import timedelta client = FixstarsClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 実行時間を 1 秒に設定 client.parameters.timeout = timedelta(milliseconds=1000) # 使用する GPU 数を 1 に設定 client.parameters.num_gpus = 1 # 探索中に得られた全ての解を取得 client.parameters.outputs.num_outputs = 0 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ソルバーのバージョンを取得: ```python >>> client.version 'v0.8.5-V100' ``` 詳細な実行時間を取得: ```python >>> result.client_result.execution_time FixstarsClient.Result.ExecutionTime({ "annealing_time": 9988.965504, "queue_time": 0.047615, "cpu_time": 0.19356399999999996, "time_stamps": [ 8.764683 ] }) ``` 実行時のパラメータ情報を取得: ```python >>> result.client_result.execution_parameters FixstarsClient.Result.ExecutionParameters({ "num_gpus": 1, "timeout": 10000, "num_iterations": 585, "penalty_calibration": false, "penalty_multipliers": [], "version": "v0.8.7-V100" }) ``` --- # D-Wave Systems ## D-Wave Sampler [D-Wave Systems](https://www.dwavesys.com/) の提供する量子アニーリングマシン (QPU) です。QUBO あるいは イジング変数の二次多項式で表された組合せ最適化問題を入力できます。 > [!TIP] > > **Tip** > > Fixstars Amplify の[ユーザ登録](https://amplify.fixstars.com/register)を行い無償のお試し API トークンを入手するか、自身の D-Wave Systems のアカウントで API トークンを入手してください。 > [!TIP] > > **ヒント** > > D-Wave のマシンを使う場合は、次のコマンドで追加のパッケージを含めてインストールしてください。 > > ```bash > $ python3 -m pip install -U 'amplify[dwave]' > ``` > > > [!WARNING] > > > > **注意** > > > > Python のバージョンによっては追加パッケージが対応していないことがあります。[動作確認済み環境](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/quickstart.md#quantum-support-env)を参照してください。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`dimod.sampleset.SampleSet`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["timing"]["qpu_access_time"]` | | API 方式 | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | 実行パラメータリファレンス | [📖 Parameters Reference](https://docs.dwavequantum.com/en/latest/quantum_research/solver_parameters.html#qpu-solver-parameters) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次\* | 2次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: バイナリ変数とイジング変数の両方が同時に含まれる問題には対応していません。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する D-Wave Sampler の名前を取得・設定します | | [`solver_names`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.solver_names) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`str`](https://docs.python.org/3/library/stdtypes.html#str)] | 設定されたトークンで仕様可能な D-Wave Sampler の名前の一覧を取得します | | [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | 使用するソルバーのプロパティを取得します ([`dwave.system.samplers.DWaveSampler.properties`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_system/generated/dwave.system.samplers.DWaveSampler.properties.html#dwave.system.samplers.DWaveSampler.properties) と同じ結果が返ります) | **設定例**: ```python from amplify import DWaveSamplerClient client = DWaveSamplerClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 使用するソルバーを指定 # (client.solver_names に含まれる名前のいずれかを指定) client.solver = "Advantage2_system1" # 実行回数を 1000 に設定 client.parameters.num_reads = 1000 ``` > [!NOTE] > > **参考** > > [`amplify.DWaveSamplerClient.parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.parameters) は各ソルバーパラメータを型付きのアトリビュートとして公開します。存在しないアトリビュートを設定すると [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) が送出されます。[`None`](https://docs.python.org/3/library/constants.html#None) を設定するとソルバーの既定値に戻ります。各パラメータの意味は [📖 Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html) を参照してください。 > > [`annealing_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.annealing_time)、[`programming_thermalization`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.programming_thermalization)、[`readout_thermalization`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.readout_thermalization) の単位は**マイクロ秒**です。マイクロ秒を表す数値と [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) のどちらでも設定できますが、取得時はマイクロ秒を表す [`float`](https://docs.python.org/3/library/functions.html#float) を返します。これは [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) が 1 マイクロ秒未満を表現できないためです。 > > ```python > client.parameters.annealing_time = 0.5 # 0.5 マイクロ秒 > client.parameters.annealing_time = timedelta(microseconds=20) # 20.0 マイクロ秒 > ``` > > 次のようにして [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.properties) から取得することも可能です (出力は [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.solver) によって変わります)。 > > ```python > >>> client.properties["parameters"] > {'anneal_offsets': 'Anneal offsets for each working qubit, formatted as a list, with NaN specified for unused qubits.', > 'anneal_schedule': "Annealing schedule formatted as a piecewise linear list of floating-point pairs of 't' and 's'.", > 'annealing_time': 'Quantum annealing duration, in microseconds, as a positive floating point number.', > ...} > ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` 使用するソルバーを取得 (未指定の場合は自動的に決定): ```python >>> client.solver 'Advantage_system4;graph_id=01d07086e1' ``` 現在使用可能なソルバーの一覧を取得: ```python >>> client.solver_names ['Advantage_system6;graph_id=01dae5a273', 'Advantage_system4;graph_id=01d07086e1', 'Advantage2_system1;graph_id=01138bbada'] ``` 詳細な実行時間を取得: ```python >>> result.client_result.info {'timing': {'qpu_sampling_time': 66040.0, 'qpu_anneal_time_per_sample': 20.0, 'qpu_readout_time_per_sample': 25.46, 'qpu_access_time': 81799.16, 'qpu_access_overhead_time': 621.84, 'qpu_programming_time': 15759.16, 'qpu_delay_time_per_sample': 20.58, 'total_post_processing_time': 1.0, 'post_processing_overhead_time': 1.0}, 'problem_id': '14eaa606-9eed-4c72-83f1-d563bb0e1956'} ``` ## Leap's Hybrid BQM Sampler [D-Wave Systems](https://www.dwavesys.com/) の提供する量子アニーリングマシン (QPU) と古典アルゴリズムで動作するハイブリッドソルバーです。QUBO あるいは イジング変数の二次多項式で表された組合せ最適化問題を入力でき、[D-Wave Sampler](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) よりも大規模な問題の入力に対応しています。 > [!TIP] > > **Tip** > > Fixstars Amplify の[ユーザ登録](https://amplify.fixstars.com/register)を行い無償のお試し API トークンを入手するか、自身の D-Wave Systems のアカウントで API トークンを入手してください。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.LeapHybridSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`dimod.sampleset.SampleSet`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["run_time"]` | | API 方式 | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | 実行パラメータリファレンス | [📖 Parameters Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_bqm_parameters.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | 2次 | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する Leap's Hybrid BQM Sampler の名前を取得・設定します | | [`solver_names`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.solver_names) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`str`](https://docs.python.org/3/library/stdtypes.html#str)] | 設定されたトークンで仕様可能な Leap's Hybrid BQM Sampler の名前の一覧を取得します | | [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | 使用するソルバーのプロパティを取得します ([`dwave.system.samplers.LeapHybridSampler.properties`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_system/generated/dwave.system.samplers.LeapHybridSampler.properties.html#dwave.system.samplers.LeapHybridSampler.properties) と同じ結果が返ります) | **設定例**: ```python from amplify import LeapHybridSamplerClient client = LeapHybridSamplerClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 使用するソルバーを取得 # (未指定であれば自動的に決定される) # print(client.solver) # 使用可能なソルバーの一覧を取得 # print(client.solver_names) # 使用するソルバーを指定 # (client.solver_names に含まれる名前のいずれかを指定) client.solver = "hybrid_binary_quadratic_model_version2p" # 実行時間を 5 秒に設定 client.parameters.time_limit = 5 ``` > [!NOTE] > > **参考** > > [`amplify.LeapHybridSamplerClient.parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.parameters) は各ソルバーパラメータを型付きのアトリビュートとして公開します。存在しないアトリビュートを設定すると [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) が送出されます。[`None`](https://docs.python.org/3/library/constants.html#None) を設定するとソルバーの既定値に戻ります。[`time_limit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.Parameters.time_limit) の単位は秒で、数値と [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) のどちらでも設定できます。各パラメータの意味は [📖 Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html) を参照してください。 > > 次のようにして [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.properties) から取得することも可能です (出力は [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.solver) によって変わります)。 > > ```python > >>> client.properties["parameters"] > {'time_limit': 'Maximum requested runtime in seconds.'} > ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` 使用するソルバーを取得 (未指定の場合は自動的に決定): ```python >>> client.solver 'hybrid_binary_quadratic_model_version2p' ``` 現在使用可能なソルバーの一覧を取得: ```python >>> client.solver_names ['hybrid_binary_quadratic_model_version2p'] ``` 詳細な実行時間を取得: ```python >>> result.client_result.info {'qpu_access_time': 47632, 'charge_time': 2989001, 'run_time': 2989001, 'problem_id': '745910bb-2e3b-4f3e-90fc-eb5734c637f3'} ``` ## Leap's Hybrid CQM Sampler [D-Wave Systems](https://www.dwavesys.com/) の提供する量子アニーリングマシン (QPU) と古典アルゴリズムで動作するハイブリッドソルバーです。QUBO あるいは イジング変数、整数変数、実数変数の目的関数と1つ以上の制約条件で表された組合せ最適化問題を入力できます。 > [!TIP] > > **Tip** > > Fixstars Amplify の[ユーザ登録](https://amplify.fixstars.com/register)を行い無償のお試し API トークンを入手するか、自身の D-Wave Systems のアカウントで API トークンを入手してください。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`dimod.sampleset.SampleSet`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["run_time"]` | | API 方式 | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | 実行パラメータリファレンス | [📖 Parameters Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_cqm_parameters.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | 2次 | 2次 | 1次 | | 等式制約 | 2次 | 2次 | 2次 | 1次 | | 不等式制約 | 2次 | 2次 | 2次 | 1次 | **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する Leap's Hybrid CQM Sampler の名前を取得・設定します | | [`solver_names`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.solver_names) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`str`](https://docs.python.org/3/library/stdtypes.html#str)] | 設定されたトークンで仕様可能な Leap's Hybrid CQM Sampler の名前の一覧を取得します | | [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | 使用するソルバーのプロパティを取得します ([`dwave.system.samplers.LeapHybridCQMSampler.properties`](https://docs.dwavequantum.com/en/latest/ocean/api_ref_system/generated/dwave.system.samplers.LeapHybridCQMSampler.properties.html#dwave.system.samplers.LeapHybridCQMSampler.properties) と同じ結果が返ります) | **設定例**: ```python from amplify import LeapHybridCQMSamplerClient client = LeapHybridCQMSamplerClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 使用するソルバーを指定 # (client.solver_names に含まれる名前のいずれかを指定) client.solver = "hybrid_constrained_quadratic_model_version1p" # 実行時間を 3 秒に設定 client.parameters.time_limit = 3 ``` > [!NOTE] > > **参考** > > [`amplify.LeapHybridCQMSamplerClient.parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.parameters) は各ソルバーパラメータを型付きのアトリビュートとして公開します。存在しないアトリビュートを設定すると [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) が送出されます。[`None`](https://docs.python.org/3/library/constants.html#None) を設定するとソルバーの既定値に戻ります。[`time_limit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.Parameters.time_limit) の単位は秒で、数値と [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) のどちらでも設定できます。各パラメータの意味は [📖 Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html) を参照してください。 > > 次のようにして [`properties`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.properties) から取得することも可能です (出力は [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.solver) によって変わります)。 > > ```python > >>> client.properties["parameters"] > {'time_limit': 'Maximum requested runtime in seconds.'} > ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` 使用するソルバーを取得 (未指定の場合は自動的に決定): ```python >>> client.solver 'hybrid_constrained_quadratic_model_version1p' ``` 現在使用可能なソルバーの一覧を取得: ```python >>> client.solver_names ['hybrid_constrained_quadratic_model_version1p'] ``` ソルバーのバージョンを取得: ```python >>> client.version '1.12' ``` 詳細な実行時間を取得: ```python >>> result.client_result.info {'constraint_labels': [], 'qpu_access_time': 15846, 'charge_time': 4305380, 'run_time': 4305380, 'problem_id': '47db4ee7-2e60-4c99-99ae-b596914d4907'} ``` --- # 東芝 ## SQBM+ v2.0.3 [東芝](https://www.global.toshiba/jp/products-solutions/ai-iot/sbm.html) の開発したシミュレーテッド分岐マシンを核とする量子インスパイアード最適化ソリューションです。 > [!TIP] > > **Tip** > > AWS Marketplace あるいは Fixstars Amplify の有償オプションとして提供されています。 > [!TIP] > > **Tip** > > SQBM+のバージョンにより、使用可能なソルバーや受付可能な変数タイプが異なります。 > バージョンは [`version`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.version) プロパティから取得できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.ToshibaSQBM2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.parameters) | [`amplify.ToshibaSQBM2Client.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.ToshibaSQBM2Client.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.ToshibaSQBM2Client.Result.time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result.time) | | API 方式 | REST API (HDF5/JSON) | | API リファレンス | [📖 User Guide (v2.0.3)](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/7e21cdf718c667d7e3b709b4d6413bbd/User_Manual-SQBM%2B_for_On-premises.pdf) | * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) プロパティに [`Qubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qubo) が設定されている場合 (デフォルト): | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) プロパティに [`Qplib`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qplib) が設定されている場合: | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | 2次 | | 等式制約 | 1次 | - | - | 1次 | | 不等式制約 | 1次 | - | - | 1次 | * [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) プロパティに [`Pubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Pubo) が設定されている場合: | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 4次 | - | - | 4次 | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートとメソッドを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) | [`Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用するソルバーを指定します。[`Qubo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qubo) (デフォルト) または [`Qplib`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qplib) を指定可能です。 | | [`compression`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | リクエストデータを圧縮して送信します。デフォルトは [`True`](https://docs.python.org/3/library/constants.html#True) です。[`False`](https://docs.python.org/3/library/constants.html#False) に設定することでリクエストデータの圧縮時間を削減できますが、通信時間が増加する可能性があります。 | | メソッド | 返却型 | 詳細 | | --- | --- | --- | | [`health_check()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.health_check) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | ヘルスチェック API への問合せを行い、ソルバーが正常動作しているかを確認します。 | **設定例**: ```python from amplify import ToshibaSQBM2Client from datetime import timedelta client = ToshibaSQBM2Client() # API トークンを設定 # (AWS 版を使用する場合は不要) client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # URL を設定 # (AWS 版を使用する場合は必要) # client.url = "http://xxx.xxx.xxx.xxx:8000/" # ソルバーを指定 # (Qubo, Qplib, Pubo のいずれか) client.solver = "Qplib" # 実行時間を 1 秒に設定 client.parameters.timeout = timedelta(milliseconds=1000) ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ヘルスチェックAPIの実行: ```python >>> client.health_check() True ``` ソルバーのバージョンを取得: ```python >>> client.version '2.0.3' ``` 実行時のパラメータ情報を取得: ```python >>> result.client_result.param ToshibaSQBM2Client.Parameters({ "steps": 1, "dt": 1.0, "C": 0.1502210944890976, "algo": 204 }) ``` --- # 富士通 ## Fujitsu DA4 Solver [富士通](https://www.fujitsu.com/jp/digitalannealer/) の提供する第四世代アニーリングコア (GPU) による QUBO ソルバーです。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.parameters) | [`amplify.FujitsuDA4Client.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FujitsuDA4Client.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FujitsuDA4Client.SolverTiming.solve_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.SolverTiming.solve_time) | | API 方式 | REST API (JSON) | | API リファレンス | [📖 API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v4-ja.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | \*/\*\* | - | - | - | | 不等式制約 | 1次 | - | - | - | \*: one-way-one-hot 制約および two-way-one-hot 制約に対応しています。 \*\*: ペナルティ関数として与えることが可能です。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートとメソッドを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`type_id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.type_id) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [Premium API](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v3c-v4-premium-ja.html) を使用する場合のタイプIDを指定します | | [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると制約条件のペナルティ関数の重みの設定を `penalty_binary_polynomial` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) [`False`](https://docs.python.org/3/library/constants.html#False) に設定するとペナルティ関数は目的関数に足されます。 | | [`set_inequalities`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_inequalities) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると一次の不等式制約を `inequalities` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) [`False`](https://docs.python.org/3/library/constants.html#False) に設定すると不等式制約のペナルティ関数を生成して [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) に従って処理します。 | | [`set_one_way_one_hot_groups`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_one_way_one_hot_groups) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、決定変数の先頭から並んでいる one-hot 制約を可能な限り検出して `one_way_one_hot_groups` パラメータに与えます (デフォルト: [`False`](https://docs.python.org/3/library/constants.html#False)) [`False`](https://docs.python.org/3/library/constants.html#False) に設定した場合や、パラメータに与えることのできなかった one-hot 制約はペナルティ関数を生成して [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) に従って処理します。 | | [`set_two_way_one_hot_groups`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_two_way_one_hot_groups) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、等間隔に並ぶ `one_way_one_hot_groups` の検出を行い、さらに `two_way_one_hot_groups` の条件を満たす one-hot 制約を追加できる場合にはそれらを検出して `two_way_one_hot_groups` パラメータに与えます (デフォルト: [`False`](https://docs.python.org/3/library/constants.html#False)) [`False`](https://docs.python.org/3/library/constants.html#False) に設定した場合や、パラメータに与えることのできなかった one-hot 制約はペナルティ関数を生成して [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) に従って処理します。 [`set_one_way_one_hot_groups`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_one_way_one_hot_groups) と同時に [`True`](https://docs.python.org/3/library/constants.html#True) に設定した場合は `two_way_one_hot_groups` の検出を優先します。 | | メソッド | 返却型 | 詳細 | | --- | --- | --- | | [`health_check()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.health_check) | [`CommonError`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.CommonError) | [`None`](https://docs.python.org/3/library/constants.html#None) | ヘルスチェック API への問合せを行い、ソルバーが正常動作しているかを確認します。正常時は [`None`](https://docs.python.org/3/library/constants.html#None) を返します。 | | [`async_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.async_solve) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | `/async/qubo/solve` API を非同期で実行してジョブ ID を返します。 | | [`get_jobs()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.get_jobs) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`JobStatusInfo`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatusInfo)] | ジョブのステータスの一覧を取得します。 | | [`cancel_job()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.cancel_job) | [`JobStatus`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatus) | ジョブのIDを指定してジョブのキャンセルを試みます。 | | [`get_job_result()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.get_job_result) | [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | ジョブのIDを指定して完了済みの結果を取得します。 | | [`delete_job_result()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.delete_job_result) | [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | ジョブのIDを指定して完了済みの結果を取得し結果を削除します。 | > [!NOTE] > > **注釈** > > クライアントクラスの共通インターフェースの [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.solve) は [`async_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.async_solve) の同期版です。ジョブの実行が完了するまで待機して実行結果の返却を行います。 **設定例**: ```python from amplify import FujitsuDA4Client from datetime import timedelta client = FujitsuDA4Client() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # one-way one-hot groups の検出を有効化 client.set_one_way_one_hot_groups = True # 実行時間を 100 秒に設定 client.parameters.time_limit_sec = timedelta(seconds=100) ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ヘルスチェックAPIの実行: ```python >>> client.health_check() ``` ジョブ一覧の取得: ```python >>> client.get_jobs() [FujitsuDA4ClientJobStatusInfo({"job_id":"...","job_status":"Done","start_time":"..."}), FujitsuDA4ClientJobStatusInfo({"job_id":"...","job_status":"Done","start_time":"..."}) ...] ``` ジョブの結果の取得と削除: ```python >>> client.delete_job_result("...") {"qubo_solution":{"progress":[{"energy":417.0,"penalty_energy":366429644.0,"time":1.179},... ``` ソルバーのバージョンを取得: ```python >>> client.version 'v4' ``` 詳細な実行時間を取得: ```python >>> result.client_result.qubo_solution.timing FujitsuDA4Client.SolverTiming({ "solve_time": 101963.0, "total_elapsed_time": 101963.0 }) ``` ## Fujitsu DA3c Solver [富士通](https://www.fujitsu.com/jp/digitalannealer/) の提供する第三世代アニーリングコア (DAU: Digital Annealing Unit) による QUBO ソルバーです。 > [!NOTE] > > **注釈** > > クライアントクラスの仕様は [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) と同様です。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.FujitsuDA3cClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.parameters) | [`amplify.FujitsuDA3cClient.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FujitsuDA3cClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FujitsuDA3cClient.SolverTiming.solve_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.SolverTiming.solve_time) | | API 方式 | REST API (JSON) | | API リファレンス | [📖 API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v3c-ja.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | \*/\*\* | - | - | - | | 不等式制約 | 1次 | - | - | - | \*: one-way-one-hot 制約および two-way-one-hot 制約に対応しています。 \*\*: ペナルティ関数として与えることが可能です。 --- # NEC ## NEC Vector Annealing (VA) サービス 2.0 > [!WARNING] > > **警告** > > NEC VA サービス 2.0 は 2025 年 4 月 1 日にサービス終了しました。 [NEC](https://jpn.nec.com/nec-vector-annealing-service/) の提供する QUBO ソルバーです。ベクトル型スーパーコンピュータ SX-Aurora TSUBASA 上で動作します。 Amplify SDK の提供する [`NECVA2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) を使用することで、リクエストパラメータの自動検出・自動設定を行いながら NEC Vector Annealing サービス 2.0 API を呼び出すことができます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.NECVA2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.parameters)1 | [`amplify.NECVA2Client.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result)2 | [`amplify.NECVA2Client.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) ([詳細](#clients-necva2client-exectime)) | [`amplify.NECVA2Client.Result.Timing.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time) | | API 方式3 | SAC サービスクライアント (Python) | | API リファレンス | [📖 User Guide](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/f90ee151bb5d360d5b6dadd8db400663/nec_vector_annealing_service_2.0_user_guide_v4.pdf) | 1: [API リファレンス「3-3-2 solve_paramsのパラメータ」](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/f90ee151bb5d360d5b6dadd8db400663/nec_vector_annealing_service_2.0_user_guide_v4.pdf)に相当します 2: [API リファレンス「3-4.レスポンス」](https://amplify.fixstars.com/ja/docs/amplify/v1/_downloads/f90ee151bb5d360d5b6dadd8db400663/nec_vector_annealing_service_2.0_user_guide_v4.pdf)に相当します 3: 追加インストールの必要はありません | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | - | - | | 等式制約 | \* | - | - | - | | 不等式制約 | \* | - | - | - | \*: 後述する1次または2次の特別な制約条件に対応しています。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`set_fixed`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_fixed) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から fixed 制約を可能な限り検出してフリップオプションの `fixed` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_onehot`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_onehot) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から onehot 制約を可能な限り検出してフリップオプションの `onehot` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_andzero`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_andzero) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から andzero 制約を可能な限り検出してフリップオプションの `andzero` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_orone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_orone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から orone 制約を可能な限り検出してフリップオプションの `orone` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_supplement`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_supplement) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から supplement 制約を可能な限り検出してフリップオプションの `supplement` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_maxone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_maxone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から maxone 制約を可能な限り検出してフリップオプションの `maxone` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_minmaxone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_minmaxone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`True`](https://docs.python.org/3/library/constants.html#True) に設定すると、モデルの持つ制約条件の中から minmaxone 制約を可能な限り検出してフリップオプションの `minmaxone` パラメータに与えます (デフォルト: [`True`](https://docs.python.org/3/library/constants.html#True)) | フリップオプションの各制約は、係数を含めて以下の形と一致する制約条件式が設定されたときのみ検出されます。 $q_1, q_2, \dots , q_N$ ($N$ は自然数) を互いに独立なバイナリ変数、$m, n, k$ を整数定数とします。 | フリップオプション | 検出する制約条件の形式 | | --- | --- | | [`set_fixed`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_fixed) | $q_1 + k = k$ $q_1 + k = k + 1$ | | [`set_onehot`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_onehot) | $q_1 + q_2 + \cdots + q_N + k = k + 1$ | | [`set_andzero`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_andzero) | $q_1 + q_2 + \cdots + q_N + k \leq k + N - 1$ $n q_1 q_2 + k = k$ | | [`set_orone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_orone) | $q_1 + q_2 + \cdots + q_N + k \geq k + 1$ $n (q_1 - 1)(q_2 - 1) + k = k$ | | [`set_supplement`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_supplement) | $n (q_1 - q_2 q_3) + k = k$ | | [`set_minmaxone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_minmaxone) | $m \leq q_1 + q_2 + \cdots + q_N + k \leq n \quad (0 \leq m - k, n - k \leq N)$ $q_1 + q_2 + \cdots + q_N + k = n \quad (0 \leq n - k \leq N)$ $q_1 + q_2 + \cdots + q_N + k \leq n \quad (0 \leq n - k \leq N)$ $q_1 + q_2 + \cdots + q_N + k \geq n \quad (0 \leq n - k \leq N)$ | | [`set_maxone`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_maxone) | $q_1 + q_2 + \cdots + q_N + k \leq n \quad (0 \leq n - k \leq N)$ | 各制約条件式に対するフリップオプションの検出は、上表の順番と同じ優先順位で行われます。 ある制約条件が複数のフリップオプションに該当する場合、[`True`](https://docs.python.org/3/library/constants.html#True) に設定されているフリップオプションの中で、より優先度の高いものが設定されます。 > [!NOTE] > > **注釈** > > フリップオプションが有効であるかにかかわらず、制約条件は必要に応じてペナルティ関数として目的関数に追加されます。 **実行時間**: NEC VA 2.0 は VA の各サンプリングの実行時間を返却しますが、一方で求解全体に要した実行時間は返却されません。[`NECVA2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) では、サンプリング時間に加えて、独自に SAC サービスクライアントの `solve_qubo()` API のレスポンス時間 ([`solve_qubo_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.solve_qubo_time)) 、このうち VA の実行に係る時間 ([`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time)) およびキュー待ち時間 ([`queue_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.queue_time))を計測し返却します。これらは実行結果クラスの [`timing`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.timing) アトリビュートに格納されます。 | アトリビュート | 詳細 | | --- | --- | | [`amplify.NECVA2Client.Result.Result.time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Result.time) | VA の各サンプリングの実行時間 | | [`amplify.NECVA2Client.Result.Timing.solve_qubo_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.solve_qubo_time) | `solve_qubo()` Python API のレスポンス時間 | | [`amplify.NECVA2Client.Result.Timing.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time) | VA の実行時間 (ネットワークオーバーヘッド・キュー待ち時間等を含む) | | [`amplify.NECVA2Client.Result.Timing.queue_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.queue_time) | キュー待ち時間 | **設定例**: ```python from amplify import NECVA2Client client = NECVA2Client() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 速度優先モードで実行 client.parameters.vector_mode = "speed" ``` **実行例**: ```python from amplify import VariableGenerator, Model, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) # API の実行時間を表示 print(result.execution_time) ``` ソルバーのバージョンを取得: ```python >>> client.version '2.0.2' ``` 詳細な実行時間を取得: ```python >>> result.client_result.result[0].time datetime.timedelta(microseconds=4257) >>> result.client_result.timing NECVA2Client.Result.Timing({ "execution_time": 3.8289530351758003, "solve_qubo_time": 24.603095658123493, "queue_time": 0.0007024258375167847 }) ``` --- # 日立 ## Hitachi Annealing Cloud Web [日立](https://annealing-cloud.com/ja/index.html) の提供する CMOS アニーリングマシンです。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.parameters) | [`amplify.HitachiClient.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.HitachiClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.HitachiClient.Result.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result.Result.execution_time) | | API 方式 | REST API (JSON) | | API リファレンス | [📖 API Reference](https://annealing-cloud.com/ja/web-api/reference/v2.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | 2次 | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | > [!NOTE] > > **注釈** > > 処理を実行できるマシンは以下の 3 種類があり、[`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) で指定できます。 (デフォルト:[`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 4) > > * [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 3: GPU 32bit (int) > > * 256k スピン (512×512 の King's graph に相当) を処理可能 > * [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 4: GPU 32bit (float) > > * 256k スピン (512×512 の King's graph に相当) を処理可能 > * [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 5: ASIC 4bit > > * 147,456 スピン (384×384 の King's graph に相当) を処理可能 > > [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 3, 5 のマシンは整数係数のモデルしか扱えません。それぞれのタイプで扱える整数値の範囲については [API リファレンス](https://annealing-cloud.com/ja/web-api/reference/v2.html) を参照してください。ただし、もし目的関数が整数係数であっても、Amplify SDK は [`amplify.solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数において、モデル変換とグラフ埋め込み処理が行われるため、マシンに渡されるモデルには結果として小数が含まれることがあります。そのような場合 Amplify SDK 内部では符号に応じた無限大方向への切り上げによって整数化するため、必ずしも意図通りの定式化とはならないことに注意してください。 > これらのマシンを使用する場合には、直接 [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) を用いて実行することを推奨します ([こちら](#hitachiclient-solve)を参照してください)。 **設定例**: ```python from amplify import HitachiClient client = HitachiClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # アニーリング実行回数を 3 に設定 client.parameters.num_executions = 3 # スピンのサイトあたりの平均値を出力する client.parameters.outputs.averaged_spins = True # エネルギーの平均値を出力する client.parameters.outputs.averaged_energy = True ``` **実行例**: ```python from amplify import VariableGenerator, Model, solve # 決定変数と目的関数を定義 g = VariableGenerator() s = g.array("Ising", 2) f = s[0] * s[1] + s[0] - s[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ソルバーのバージョンを取得: ```python >>> client.version 'v2' ``` 詳細な実行結果を取得: ```python >>> result.client_result.result HitachiClient.Result.Result({ "execution_time": 185832138, "energies": [ -3.0, -3.0, -3.0 ], "spins": [ [[0, 0, -1], [1, 0, 1]], [[0, 0, -1], [1, 0, 1]], ... ], "averaged_energy": -3.0, "averaged_spins": [ [1, 0, 1], [0, 0, -1] ] }) ``` ### クライアントインターフェースを使用して実行する [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) メソッドを使用して、ソルバーの API を直接利用して問題を送信し、結果を取得することができます。この方法は、日立 CMOS アニーリングマシンのチップのトポロジーに最適化された問題や、グラフ埋め込みを自身で行って問題を解く際に有用です。 CMOS アニーリングマシンの API では、King's graph 上の座標 $(x, y)$ でイジング変数を定義します。一方で、Amplify SDK では変数を ID ([`id`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id)) で管理するため、[`amplify.HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) クラスでは、King's graph 上の座標との対応関係を `id = x + y * graph_size` として与えることにしています。 使用する CMOS アニーリングマシンの [`type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) に対応した `graph_size` を用いると、この対応関係を満たした変数を以下のように発行することができます。 ```python from amplify import VariableGenerator, HitachiClient client = HitachiClient() client.parameters.type = 3 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" graph_size = client.graph.shape[0] # グラフの一辺のサイズ g = VariableGenerator() s = g.array("Ising", (graph_size, graph_size)) # graph_size x graph_size の King's graph 上のイジング変数を生成 ``` 生成したイジング変数配列 `s` は King's graph 上の座標と配列インデックスが対応します。例えば `s[x, y]` は King's graph 上の座標 $(x, y)$ に対応するイジング変数を表します。 次に、以下を満たす目的関数 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) を作成します。 * 二次以下のイジング変数のみで構成された多項式である * 制約条件はあらかじめペナルティ関数として目的関数に含める * 係数に指定出来る値の種類と範囲に注意する ([API リファレンス](https://annealing-cloud.com/ja/web-api/reference/v2.html) を参照) * 二次項に含まれる 2 つのイジング変数のインデックスは二次元配列上で上下左右斜めのいずれかで隣接している (King's graph 上で隣接している) 例えば以下のような目的関数は上記の条件を満たします。 ```python f = s[0, 0] * s[0, 1] + 2 * s[0, 0] * s[1, 0] - s[0, 1] * s[1, 0] - s[1, 0] * s[1, 1] + 1 ``` 作成した目的関数を [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) メソッドに与えることで、ソルバーが実行され、レスポンスが返却されます。 ```python >>> res = client.solve(f) >>> res.result.energies array([-5.]) >>> res.result.spins [[(0, 0, 1), (1, 0, -1), (0, 1, -1), (1, 1, -1)]] ``` ソルバーから返却された各イジング変数の解 $s'$ は [`spins`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result.Result.spins) に `[[(x, y, s'), ...], ...]` という形式で格納されています。ここで `s'` は King's graph 上の座標 $(x, y)$ におけるイジング変数の値を表します。目的関数に使用されなかった変数については値が返却されないことに注意してください。複数の解が返却されることがあるため、タプルのリストのリストとして格納されています。 変数配列 `s` と同様の形状で、King's graph 上の座標 $(x, y)$ におけるイジング変数の解を取得するには以下のようにします。 ```python import numpy as np # graph_size x graph_size のゼロ配列を生成 spin_values = np.zeros((graph_size, graph_size)) # インデックス 0 の結果から解を代入 # (複数の解が返却される場合は適宜インデックスを指定する) for x, y, s in res.result.spins[0]: spin_values[x, y] = s ``` --- # Gurobi ## Gurobi Optimizer Gurobi が提供する MIP (混合整数計画問題) ソルバーです。Gurobi Optimizer は QUBO を含む整数変数、実数変数の二次の問題を扱うことができます。 > [!NOTE] > > **注釈** > > Gurobi の実行には Amplify SDK の実行マシンに [Gurobi Optimizer](https://www.gurobi.com/solutions/gurobi-optimizer/) およびライセンスが適切にインストールされている必要があります。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.GurobiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.parameters) | [`amplify.GurobiClient.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.GurobiClient.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result) | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.GurobiClient.Result.runtime`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result.runtime) | | 対応バージョン | 9.0.0 以上 | | API リファレンス | [📖 Reference Manual](https://www.gurobi.com/documentation/current/refman/index.html) | | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | 2次 | - | 2次 | 2次 | | 等式制約 | 2次 | - | 2次 | 2次 | | 不等式制約 | 2次 | - | 2次 | 2次 | **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のメソッドを持ちます。 | メソッド | 返却型 | 詳細 | | --- | --- | --- | | [`tune()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.tune) | [`None`](https://docs.python.org/3/library/constants.html#None) | 実行パラメータのサーチを行います。 | > [!NOTE] > > **注釈** > > [`GurobiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) のファイル出力は次のように振る舞います。 > > * **[`write_request_data`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.write_request_data):** > > 指定されたファイルパスの拡張子に従ってモデルをファイルに出力します。 > 指定可能な拡張子は `.mps`, `.rew`, `.lp`, `.rlp`, `.dua/.dlp` (LP の双対問題のモデルとして) です。 > * **[`write_response_data`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.write_response_data):** > > 指定されたファイルパスの拡張子に従って解をファイルに出力します。 > 指定可能な拡張子は `.sol` または `.json` です。 > [!NOTE] > > **参考** > > [`parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.parameters) に指定可能な [`Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) クラスのアトリビュートの詳細は [Gurobi Parameters](https://www.gurobi.com/documentation/current/refman/parameters.html#sec:Parameters) を参照してください。 > ただし [`Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) クラスのアトリビュート名は *snake_case* に統一されていることに注意してください。 > [!NOTE] > > **注釈** > > [`Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) クラスのアトリビュートはデフォルト値として全て [`None`](https://docs.python.org/3/library/constants.html#None) (未設定) に初期化されていますが、一部のアトリビュートは利便性のため [`None`](https://docs.python.org/3/library/constants.html#None) の場合に明示的に Gurobi に次のように渡されます。 > > * **[`log_to_console`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters.log_to_console):** > > Gurobi のデフォルト (`1`) とは異なり `0` (出力しない) をデフォルトとして扱います。 > * **[`seed`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters.seed):** > > Gurobi のデフォルト (`0`) とは異なりハードウェア乱数を生成して初期化します。 **設定例**: ```python from amplify import GurobiClient from datetime import timedelta client = GurobiClient() # インストールパスを設定 # (インストールパスが自動的に検出されない場合に必要) # client.library_path = "/opt/gurobi1203/linux64/lib/libgurobi.so.12.0.3" # 実行時間を 100 秒に設定 client.parameters.time_limit = timedelta(seconds=100) ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` ソルバーのバージョンを取得: ```python >>> client.version '9.5.0' ``` --- # 量子コンピュータ 量子コンピュータのクライアントでは、[QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md) に代表される量子アルゴリズムで最適化計算を実行します。 クラウドサービスとして提供されている各種量子コンピュータ及びローカルシミュレータを利用して、量子回路を実行します。 > [!TIP] > > **Tip** > > ローカルシミュレータを使うクライアントは登録不要で利用できます。 > > その他のクライアントでは、量子コンピューティングサービスを提供する各ベンダーとの契約が必要です。 > [!TIP] > > **ヒント** > > 量子コンピュータを利用する場合は、以下のコマンドで追加パッケージを含む Amplify をインストールしてください。 > > ```bash > $ python3 -m pip install -U 'amplify[quantum]' > ``` > > > [!WARNING] > > > > **注意** > > > > Python のバージョンによっては追加パッケージが対応していないことがあります。[動作確認済み環境](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/quickstart.md#quantum-support-env)を参照してください。 利用に必要な手順はクライアントごとに異なります。 クラウド API を利用するクライアントでは、保有しているライセンスを使って認証を行う必要があります。 | クライアントクラス | 種別 | 必要な手順 | | --- | --- | --- | | [QUDORAClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qudora.md) | ☁️ Cloud | [Fixstars Amplify アカウント](https://amplify.fixstars.com/user/token)または自身の QUDORA Cloud アカウントで API トークンを取得する | | [IonQClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ionq.md) | ☁️ Cloud | (API トークンを使う場合) [Fixstars Amplify アカウント](https://amplify.fixstars.com/user/token)または自身の IonQ アカウントで API トークンを取得する (Amazon Braket を使う場合) 自身の AWS アカウントの認証情報を設定する | | [AerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aer.md) | 💻 Local | なし | | [QulacsClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qulacs.md) | 💻 Local | なし | | [BraketSimulatorClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aws.md) | 💻 Local ☁️ Cloud | なし (クラウドシミュレータを利用する場合) 自身の AWS アカウントの認証情報を設定する | | [IBMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ibm.md) | ☁️ Cloud | 自身の IBM Cloud アカウントで IBM Quantum API キーを取得する | | [AQTClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aqt.md) [IQMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/iqm.md) [RigettiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/rigetti.md) | ☁️ Cloud | 自身の AWS アカウントの認証情報を設定する | | [OqtopusClient](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/oqtopus.md) | ☁️ Cloud | 自身のアクセス可能な OQTOPUS Cloud の接続先 URL と API トークンを設定する | また、量子コンピュータ向けのクライアントでは、初期化時にアルゴリズムを指定する必要があります。 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 量子コンピュータクライアントは[クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface)に加えて、それぞれの量子コンピュータ/シミュレータ固有のパラメータを設定することができます。 同じアルゴリズムを選択したソルバークライアントでは、`client.parameters`から同じパラメータを取得および設定できます。パラメータや解情報の詳細は[アルゴリズムの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/index.md) を参照してください。 **設定例**: QAOAを Qulacs Simulator を使って動かすクライアントを例として以下のように作成します。 ```python from amplify import QAOA, QulacsClient # アルゴリズムを表すクラス QAOA と バックエンドを表すクラス QulacsClient を組み合わせてソルバークライアントを作成 client = QulacsClient(QAOA) # QAOAのreps, shotsを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() '0.6.13' ``` [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-result-duration)を取得: ```python >>> d = result.client_result.durations >>> result.total_time # amplify.solveにかかった時間 datetime.timedelta(microseconds=26152) >>> d.total_time # QAOA 全体の経過時間 datetime.timedelta(microseconds=25779) >>> d.total_response_time # QPU との通信時間の合計 datetime.timedelta(microseconds=283) >>> d.total_execution_time # QPU での実行時間の合計 datetime.timedelta(microseconds=283) >>> d.classical_processing_time # 古典最適化にかかった時間 (= total_time - total_response_time) datetime.timedelta(microseconds=25496) ``` 量子回路の取得: ```python >>> print(result.client_result.history[0].sampling_meta.circuit) ``` バックエンドによって回路オブジェクトの型は異なります。 [サンプリング結果](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-best-count)の解釈: ```python >>> sorted_counts = sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True) >>> for sol, freq in sorted_counts[:5]: ... values = q.substitute( ... { ... k: p.substitute( ... {v: sol[v.id] for v in result.intermediate.model.get_variables()} ... ) ... for k, p in result.intermediate.mapping.items() ... } ... ) ... print(f"解: {values}, 出現回数: {freq}") 解: [0, 1], 出現回数: 76 解: [0, 0], 出現回数: 17 解: [1, 0], 出現回数: 4 解: [1, 1], 出現回数: 3 ``` --- # ソルバーの直列実行 性能の評価を行いたい場合、ソルバーを何回か繰り返し実行したい場合があります。また、ソルバーによっては、長時間のタイムアウトを指定して 1 回実行するよりも短時間のタイムアウトで何回か繰り返し実行したほうが良い解を見つける可能性が高くなることもあります。Amplify SDK は、そのようなニーズのために、同じ組合せ最適化問題を同じソルバーで複数回連続して実行する機能を提供しています。 > [!NOTE] > > **参考** > > 定式化やソルバーの性能調査などのために複数回を実行した統計を取る場合には [ソルバーの並列実行](https://amplify.fixstars.com/ja/docs/amplify/v1/parallel.md) の方が適していることもります。そちらも参照してください。 ## 複数実行の例 まず、通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行と同様に、モデルとソルバークライアントを作成します。 ```python from amplify import VariableGenerator, one_hot, AmplifyAEClient, solve from datetime import timedelta gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint = one_hot(q) model = objective + constraint client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) の `num_solves` キーワード引数に整数を与えることで、ソルバーがその回数だけ繰り返し実行されます。 ```python result = solve(model, client, num_solves=3) ``` 通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) の実行と同様に、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのインスタンスが返ります。返り値には、`num_solves` 回の実行結果がフラットに入っています。 ```pycon >>> len(result) 3 ``` アトリビュートを用いることにより、`num_solves` 回の実行で返ってきた中で最も良い解を取得することができます。 ```pycon >>> print(f"objective = {result.best.objective}, q = {q.evaluate(result.best.values)}") objective = -1.0, q = [0. 0. 1.] ``` ## 結果の取得 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) を `num_solves` キーワードを指定して実行した場合、返り値は通常と同様に [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのインスタンスとなっています。 ソルバーが実行された回数は、[`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスの [`num_solves`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) アトリビュートにより知ることができます。これは通常 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) に `num_solves` キーワード引数として指定した値と同一ですが、ソルバー実行のうち何回かが何らかの理由により失敗した場合、`num_solves` キーワード引数として指定した値よりも小さくなることがあります。 ```pycon >>> result.num_solves 3 ``` インデックスアクセスやイテレートアクセスにより、ソルバーが `num_solves` 回の実行で返した全ての解を集約して得ることができます。デフォルトでは、良い解の順にソートされて入っており、何回目の実行で返されたかの区別はありません。 ```pycon >>> print(f"objective = {result[0].objective}, q = {q.evaluate(result[0].values)}") objective = -1.0, q = [0. 0. 1.] ``` 特定の実行により返された解のみを取得するには、[`split`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) プロパティを使用します。 ```pycon >>> first_result = result.split[0] # `result` から初回の実行にかかった部分のみを抽出 >>> type(first_result) >>> len(first_result) 1 >>> print(f"objective = {first_result.best.objective}, q = {q.evaluate(first_result.best.values)}") objective = -1.0, q = [0. 0. 1.] ``` `num_solves` が指定された場合に [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) から返される [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクト、およびそれに [`split`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) プロパティを使用して得られる `i` 回目の実行結果を表す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) オブジェクトの各プロパティについては、以下の通りのものが入ります。 | プロパティ名 | [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数が返す [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | [`split`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) 適用後の [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | | --- | --- | --- | | [`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) | [`num_solves`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) 回の実行のうち最も良い解 | `i` 回目の実行のうち最も良い解 | | [`solutions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) | [`num_solves`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) 回の実行で得たすべての解 | `i` 回目の実行で得たすべての解 | | [`intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | 通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 実行と同様 | 通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 実行と同様 | | [`embedding`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | 通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 実行と同様 | 通常の [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 実行と同様 | | [`client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | 最初の実行で得られたもの | `i` 回目の実行で得られたもの | | [`execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`num_solves`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) 回の実行の合計値 | `i` 回目の実行で得られたもの | | [`response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | [`num_solves`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) 回の実行の合計値 | `i` 回目の実行で得られたもの | | [`total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) を始めてから終わるまでの時間 | `i` 回目の実行のために費やされた時間 | --- # ソルバーの並列実行 [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) を使用すると、複数のクライアントやモデルに対して同時にリクエストを送ることができます。これにより、複数回の実行が必要な場合に、モデル変換やリクエストデータの処理時間、ソルバーへのネットワークアクセスによる転送時間などの隠蔽が期待出来ます。また、複数の問題を同時に実行できるソルバーに対しても、並列実行による実行効率の向上が期待出来ます。 ## 並列実行の例 まず、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を使用するときと同様に、モデルを構築します。 あとで複数のモデルを用いる例も示すため、ここでは 2 つのモデルを構築します。 ```python from amplify import VariableGenerator, one_hot, solve gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] constraint = one_hot(q) model1 = objective + constraint model2 = objective + 2 * constraint ``` 次に、複数のソルバークライアントを構築します。 ```python from amplify import AmplifyAEClient, DWaveSamplerClient from datetime import timedelta amplify_client = AmplifyAEClient() # amplify_client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" amplify_client.parameters.time_limit_ms = timedelta(milliseconds=1000) dwave_client = DWaveSamplerClient() # dwave_client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" dwave_client.parameters.num_reads = 100 ``` [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) 関数を用いて、複数のクライアントにリクエストを送ります。[`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) は [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) と同様のインターフェースを持ちますが、引数にリストを与えることができます。 ```python from amplify import parallel_solve amplify_result, dwave_result = parallel_solve(model1, [amplify_client, dwave_client]) ``` 上記のコードは、以下の `for` ループを並列で実行したのと同じ効果を持ちます。 ```python from amplify import solve for client in [amplify_client, dwave_client]: result = solve(model1, client) ``` [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) はモデル引数とクライアント引数の両方にリストを与えることもできます。 例えば、次のように複数のモデルと複数のクライアントに対して、[`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) を用いて同時実行できます。 ```python result1, result2 = parallel_solve([model1, model2], [amplify_client, dwave_client]) ``` この時、上記は以下の `for` ループを並列で実行した場合と同じ効果を持ちます。 ```python for model, client in zip([model1, model2], [amplify_client, dwave_client], strict=True): result = solve(model, client) ``` > [!NOTE] > > **注釈** > > モデル引数とクライアント引数の両方にリストを与えた場合、それぞれのリストの要素数は同じでなければなりません。 もし片方の引数がスカラー値であれば、もう一方の引数のリストの各要素に対して同じ値が繰り返されたリストとして扱われます。最初の例では、単一のモデルに対して複数のクライアントが使用されましたが、次のように複数のモデルに対して単一のクライアントを使用することもできます。 ```python # 以下は parallel_solve([model1, model2], [amplify_client] * 2) と同じ意味です。 result1, result2 = parallel_solve([model1, model2], amplify_client) # 以下は parallel_solve([model1] * 2, [amplify_client, dwave_client]) と同じ意味です。 result1, result2 = parallel_solve(model1, [amplify_client, dwave_client]) ``` ## 並列実行のパラメータ [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) は [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) と同様のキーワード引数を受け取ることができます。通常はキーワード引数は全ての並列実行で共通で使用されますが、キーワード引数にもリストを与えることで、複数のモデル、複数のクライアントと同様に、複数のキーワード引数を同時に指定することができます。 この場合についても、リスト型のキーワード引数の要素数はモデル引数やクライアント引数の要素数と同じでなければなりません。 例として、以下のリストを用いた次のパラメータの指定を考えます。 ```python amplify_result, dwave_result = parallel_solve( model1, [amplify_client, dwave_client], dry_run=[False, True], num_solves=2, ) ``` 上記は、以下を並列で実行したのと同じ効果を持ちます。 ```python for client, dry_run in zip([amplify_client, dwave_client], [False, True], strict=True): result = solve(model1, client, dry_run=dry_run, num_solves=2) ``` ソルバーの種類や契約内容によっては、同一のクライアントに複数のリクエストを同時に送ることができない場合があります。[`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) の `concurrency` パラメータを指定することで、並列実行数の最大値を設定することができます。デフォルトは 0 で、この場合は動作させているマシンの CPU 数に応じて並列実行数が自動で決定されます。 ```python amplify_result, dwave_result = parallel_solve( model1, [amplify_client, dwave_client], concurrency=2, ) ``` --- # 係数行列による目的関数の作成 目的関数を表現する方法の 1 つとして、多項式の係数からなる多次元配列を用いる方法が用意されています。 この方法は、目的関数が $x^\top Q x + p^\top x + c$ と表されるような実数値の 2 次元配列 $Q$ と実数ベクトル $p$ がすでに計算されている場合に便利な定式化方法です。 また、目的関数の項の数が変数の数の 2 乗程度の場合に、定式化速度において [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) クラスを用いて目的関数を構築する場合と比較して有利となる場合があります。 ## 係数行列クラス 2 次の変数多項式は次のように行列で表現することができます。 $$ x^\top Qx + p^\top x + c $$ ここで、$x$ は変数のベクトル、$Q$ は係数行列、$p$ は係数のベクトル、$c$ は定数です。 例えば、次の二次形式のバイナリ変数多項式は $$ 2 q_0 q_1 + q_0 - q_1 + 1 $$ 次のように行列とベクトルで表現できます: $$ Q = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} , \quad p^\top = \begin{pmatrix} 1 & -1 \end{pmatrix} , \quad c = 1 $$ $$ x^\top = \begin{pmatrix} q_0 & q_1 \end{pmatrix} $$ [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) の [`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) メソッドは、変数ベクトルの長さを指定して [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスのインスタンスで表現された二次の変数多項式を作成します。 次のようにして長さ 2 のバイナリ変数ベクトルを持つ [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスのインスタンスを作成できます。 ```python from amplify import VariableGenerator gen = VariableGenerator() m = gen.matrix("Binary", 2) ``` ```pycon >>> print(m) (x^T) Q x + (p^T) x + c where: x = [q_0, q_1], Q = [[ 0., 0.], [ 0., 0.]], p = [ 0., 0.], c = 0 ``` 例として、多項式 $2 q_0 q_1 + q_0 - q_1 + 1$ に対応する係数を与えます。 二次の係数行列は [`quadratic`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) アトリビュートで NumPy 配列 ([`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)) として与えられます。次のように要素アクセスによって係数行列の値を設定できます。 ```python q = m.quadratic q[0, 1] = 1 q[1, 0] = 1 ``` または、配列の形が同じであれば、NumPy 配列を代入することもできます。 ```python import numpy m.quadratic = numpy.array([[0, 1], [1, 0]]) ``` > [!NOTE] > > **注釈** > > $Q$ は必ずしも対称行列である必要はありません。上記の例では $Q_{0, 1} + Q_{1, 0} = 2$ を満たしていれば十分です。 同様に、一次の係数ベクトルは [`linear`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear)、定数は [`constant`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) アトリビュートで取得できます。 ```python p = m.linear p[0] = 1 p[1] = -1 m.constant = 1 ``` 正しく係数が設定できたか確認します。 ```pycon >>> print(m) (x^T) Q x + (p^T) x + c where: x = [q_0, q_1], Q = [[ 0., 1.], [ 1., 0.]], p = [ 1., -1.], c = 1 ``` > [!NOTE] > > **注釈** > > $Q$ の対角項は二乗の項の係数を表しますが、バイナリ変数およびイジング変数において、変数を二乗したものはその変数および 1 とそれぞれ一致するため、注意が必要です。 > > * バイナリ変数多項式 > > * 一次の係数は $Q$ の対角項と $p$ から決定されます > * イジング変数多項式 > > * 定数は $Q$ の対角項と $c$ から決定されます [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) の持つ変数配列を取得するには、[`variable_array`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.variable_array) アトリビュートを参照します。 制約条件は多項式クラス ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) で与えるため、行列形式の目的関数に制約条件を与えたい場合には変数配列を取得する必要があります。 ```pycon >>> x = m.variable_array >>> print(x) [q_0, q_1] ``` 行列形式から多項式クラス ([`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) への変換は [`to_poly()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.to_poly) メソッドで行えます。 ```pycon >>> print(m.to_poly()) 2 q_0 q_1 + q_0 - q_1 + 1 ``` > [!TIP] > > **Tip** > > 上記の例では変数配列が一次元ベクトルでしたが、多次元の変数配列に対しても同様に行列形式を作成できます。 > > ```pycon > >>> gen = VariableGenerator() > >>> m = gen.matrix("Binary", shape=(2, 2)) > >>> print(m) > (x^T) Q x + (p^T) x + c > where: > x = [[q_{0,0}, q_{0,1}], > [q_{1,0}, q_{1,1}]], > Q = [[[[ 0., 0.], > [ 0., 0.]], > [[ 0., 0.], > [ 0., 0.]]], > [[[ 0., 0.], > [ 0., 0.]], > [[ 0., 0.], > [ 0., 0.]]]], > p = [[ 0., 0.], > [ 0., 0.]], > c = 0 > ``` > > 変数配列の次元を $n$ として一般に、$Q$ は次元数 $2n$ の係数配列 ($n = 1$ の場合は行列)、$p$ は係数の $n$ 次元配列 ($n = 1$の場合はベクトル)、$c$ は定数を表します。 > 多次元配列の行列形式は[二次割当問題](https://amplify.fixstars.com/ja/docs/amplify/v1/qap.md)の定式化など、多次元の変数を用いた高速な定式化において有用なことがあります。 --- # 定式化の高速化 大規模な組合せ最適化問題を定式化したい場合、Python の for 文などを用いて定式化すると大きく時間がかかることがあります。 Amplify SDK は大規模な最適化問題を実用的な時間で定式化するための高速な定式化手段を提供しています。 例えば、[`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) クラスの Numpy-like なメソッドを用いることで、大幅な高速化が可能です。 このページでは、巡回セールスマン問題のバイナリ変数による定式化を例に、高速な定式化を行ういくつかの方法について説明します。 ## 巡回セールスマン問題の定式化 都市数が $n$ である巡回セールスマン問題は、以下のように $(n+1)n$ 個のバイナリ変数を用いて定式化されます。ただし $d$ は $d_{i,j}$ が都市 $i$ と都市 $j$ の距離を表す距離行列であるとします。 > [!NOTE] > > **参考** > > ここでは、定式化の意味は重要ではないため、変数や目的関数、制約条件が何を指すのかについては解説しません。巡回セールスマン問題の定式化の詳細については [巡回セールスマン問題](https://amplify.fixstars.com/ja/docs/amplify/v1/tsp.md) を参照してください。 $$ \begin{align} \text{minimize} \quad & \sum_{0 \leq i, j, k < n} d_{i, j} q_{k, i} q_{k+1, j} & \\ \text{subject to} \quad & \sum_{0 \leq i < n} q_{k, i} = 1 \quad & \text{for} \quad k \in \{0, 1, \ldots, n - 1\}, \\ & \sum_{0 \leq k < n} q_{k, i} = 1 \quad & \text{for} \quad i \in \{0, 1, \ldots, n - 1\}, \\ & q_{0, i} = q_{n, i} \quad & \text{for} \quad i \in \{0, 1, \ldots, n - 1\}, \\ & q_{k, i} \in \{0, 1\} & \end{align} $$ 定式化に入る前に、距離行列 `distance` (= $d$) を作成しておきます。今回は、`distance` はランダムな対称行列として生成します。 ```python import numpy as np NUM_CITIES = 100 # ランダムな対称行列を生成 distance = np.zeros((NUM_CITIES, NUM_CITIES)) for i in range(NUM_CITIES): for j in range(i+1, NUM_CITIES): distance[i, j] = distance[j, i] = np.random.rand() ``` > [!NOTE] > > **注釈** > > 実用的には各都市の座標を生成して距離行列を求めると良いでしょう。例えば [scipy](https://scipy.org/) を用いて次のような方法で高速に計算できます。 > > ```python > from scipy.spatial import distance > > locations = np.random.random((NUM_CITIES, 2)) # 座標をランダムに生成 > distance = distance.cdist(locations, locations, metric='euclidean') > ``` ## ナイーブな定式化 for 文やリスト内包表記を用いると、以下のように定式化することが可能です。 ```python from amplify import Poly, VariableGenerator, one_hot # 決定変数を作成 gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # q[NUM_CITIES, i] = q[0, i] となるように設定 for i in range(NUM_CITIES): q[NUM_CITIES, i] = q[0, i] # 目的関数を計算 objective = 0 for i in range(NUM_CITIES): for j in range(NUM_CITIES): for k in range(NUM_CITIES): objective += distance[i, j] * q[k, i] * q[k + 1, j] # 制約条件の構築 row_one_hot_constraints = sum( one_hot(sum(q[i, k] for k in range(NUM_CITIES))) for i in range(NUM_CITIES) ) col_one_hot_constraints = sum( one_hot(sum(q[i, k] for i in range(NUM_CITIES))) for k in range(NUM_CITIES) ) # モデルの作成 model = objective + (row_one_hot_constraints + col_one_hot_constraints) ``` 定式化の時間は以下のようになります (実行環境により異なります)。 | 目的関数 | 制約条件 | 全体 | | --- | --- | --- | | 1.55 s | 13.3 ms | 1.56 s | ## 改善その 1: ビルトインの sum 関数を使わない 上記のコードの最初の行に ```python from amplify import sum ``` を追加し、ビルトインの [`sum()`](https://docs.python.org/3/library/functions.html#sum) 関数の代わりに [`amplify.sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) 関数を使用します。[`amplify.sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) 関数は Amplify SDK の提供するクラスの和に特化した関数です。すると、定式化の時間は以下のようになります (実行環境により異なります)。 | 目的関数 | 制約条件 | 全体 | | --- | --- | --- | | 1.55 s | **3.95 ms** | 1.55 s | amplify の [`amplify.sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) 関数を import するだけで、制約条件の定式化が約 3 倍高速化されました。全体の時間からの差分は小さいですが、巡回セールスマン問題の場合、制約条件の個数 ($2n$) が目的関数の項数 ($O\left(n^3\right)$) と比べて小さいためです。定式化に時間がかかる部分に [`sum()`](https://docs.python.org/3/library/functions.html#sum) 関数が使われている場合、この最適化が非常に効果的になることがあります。 > [!NOTE] > > **注釈** > > 上記では `from amplify import sum` とすることにより [`sum()`](https://docs.python.org/3/library/functions.html#sum) 関数をオーバーライドしています。Amplify SDK の [`amplify.sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) 関数は Amplify SDK の提供するクラス以外に対しては自動的にビルトインの [`sum()`](https://docs.python.org/3/library/functions.html#sum) 関数にフォールバックするため、置き換えが可能になっています。 ## 改善その 2: for 文やリスト内包表記を使わない 目的関数は for 文を使って定式化していましたが、Python の for 文は見た目が悪い上に低速です。できるだけ numpy や Amplify SDK の numpy-like な多項式配列である [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) のメソッドを使用して定式化することを試みます。 まず、$q$ の上 $n$ 行からなる $n \times n$ 行列を $A$, 下 n 行からなる $n\times n$ 行列を $B$ とおきます。すると目的関数は $$ \sum_{0 \leq i, j, k < n} d_{i, j} q_{k, i} q_{k+1, j} = \sum_{0 \leq i, j, k < n} d_{i, j} A_{k, i} B_{k, j} $$ と書けます。$A$ と $d$ に着目すると、 $$ (Ad)_{k, j} = \sum_{0 \leq k, j < n} A_{k, i} d_{i, j} $$ なので、目的関数 $\displaystyle \sum_{0 \leq i, j, k < n} d_{i, j} A_{k, i} B_{k, j}$ は 「($A$ と $d$ の行列積) と $B$ の要素積」の総和であることができます。したがって、目的関数は Amplify を用いて以下のように書けます。 ```python q1 = q[:-1] q2 = q[1:] objective = ((q1 @ distance) * q2).sum() ``` また、制約条件は、[`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数に `axis` キーワード引数を渡すことで ``` row_one_hot_constraints = one_hot(q1, axis=1) col_one_hot_constraints = one_hot(q1, axis=0) ``` と書けます。全体としては以下のようなコードになります。 ```python from amplify import VariableGenerator, one_hot # 決定変数を作成 gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # q[NUM_CITIES, i] = q[0, i] となるように設定 q[-1, :] = q[0, :] # q のスライスを作成 q1 = q[:-1] q2 = q[1:] # 目的関数を計算 objective = ((q1 @ distance) * q2).sum() # 制約条件の構築 row_one_hot_constraints = one_hot(q1, axis=1) col_one_hot_constraints = one_hot(q1, axis=0) model = objective + (row_one_hot_constraints + col_one_hot_constraints) ``` この改善により、かかる時間は以下のようになります (実行環境により異なります)。 | 目的関数 | 制約条件 | 全体 | | --- | --- | --- | | **152.1 ms** | **0.870 ms** | **154.4 ms** | ## 改善その 3: 難しく考えない 改善その 2 では、目的関数を式変形して numpy のメソッドをうまく使える形に持っていくことを試みましたが、実際に式変形を考えるのは大変です。Amplify は、このような関数をアインシュタインの縮約記法を用いて機械的に定式化することができる [`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) 関数をサポートしています。 まず、「改善その 2」の場合と同様に、$q$ の上 $n$ 行からなる $n \times n$ 行列を $A$, 下 n 行からなる $n\times n$ 行列を $B$ とおくことにより、目的関数は $$ \sum_{0 \leq i, j, k < n} d_{i, j} q_{k, i} q_{k+1, j} = \sum_{0 \leq i, j, k < n} d_{i, j} A_{k, i} B_{k, j} $$ と書くことができます。この式に登場する行列 $d$, $A$, $B$ の添え字 $i$, $j$, $k$ が動く範囲は、それぞれが対応する行または列の長さと一致していることに注意してください。このような場合、[`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) 関数を適用すると目的関数の計算を以下のように書くことができます。 ``` # 目的関数を計算 objective = einsum("ij,ki,kj->", distance, q1, q2) ``` ここで、[`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) 関数の第 1 引数はアインシュタインの縮約記法による積の添え字の並びを表し、`"ij,ki,kj->"` は、$d_{i, j} A_{k, i} B_{k, j}$ という積を表しています。そして、第 2 引数以降はそれぞれの添え字に対応する配列を与えます。 全体としては以下のようなコードになります。 ```python from amplify import VariableGenerator, one_hot, einsum # 決定変数を作成 gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # q[NUM_CITIES, i] = q[0, i] となるように設定 q[-1, :] = q[0, :] # q のスライスを作成 q1 = q[:-1] q2 = q[1:] # 目的関数を計算 objective = einsum("ij,ki,kj->", distance, q1, q2) # 制約条件の構築 row_one_hot_constraints = one_hot(q1, axis=1) col_one_hot_constraints = one_hot(q1, axis=0) # モデルの作成 model = objective + (row_one_hot_constraints + col_one_hot_constraints) ``` この定式化にかかる時間は次の通りです (実行環境により異なります)。 | 目的関数 | 制約条件 | 全体 | | --- | --- | --- | | **58.11 ms** | 0.870 ms | **60.4 ms** | 以上により、目的関数と全体の計算時間は **25倍以上**、制約条件の構築は **15倍以上** の高速化が達成されました。 --- # モデルのファイル入出力 LP ファイルもしくは QPLIB ファイルから Amplify SDK の [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) を作成する機能と、逆に Amplify SDK の [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) を保存して LP ファイルもしくは QPLIB ファイルを出力する機能が提供されます。 これらは、他の数理最適化ソルバーとの連携や、[`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) の保存や再利用に用いると便利です。 ## LP ファイルフォーマット Amplify SDK が扱える LP ファイルのフォーマットは、[Gurobi LP Format](https://www.gurobi.com/documentation/current/refman/lp_format.html) に従います。 LP ファイル形式では、以下のモデルのファイル入出力に対応します。 * バイナリ変数・整数変数・実数変数を含む問題、およびこれらの変数を組み合わせた問題 * 二次以下の目的関数と制約条件で構成された問題 * LP フォーマットで表現可能な目的関数・制約を持つ問題 ### 制限事項 LP ファイルの入出力において以下の制限があります。 * LP ファイル読み込みにおいて以下の形式およびセクションには対応しません * Multi-Objective Case * Indicator Constraints * Lazy Constraints Section * User Cuts Section * SOS Section * PWLObj Section * General Constraint Section * Scenario Section * LP ファイル読み込みにおいて semi-continuous 変数には対応しません * Amplify SDK で設定した変数名や制約条件名が以下の条件に当てはまる場合には正常な LP ファイルとして出力されません * 半角スペース、および改行やタブなどの制御文字 (`\n, \r, \t, \v, \f`) を含む * 記号 `+, -, *, ^, :, /, [, ]` を含む * 上記の他に、記号 `<, >, =, ,, (, )` から始まる * Amplify SDK で設定した制約条件の重みは LP ファイルに保存されません ## QPLIB ファイルフォーマット Amplify SDK が扱える QPLIB ファイルのフォーマットは、[QPLIB: a library of quadratic programming instances](https://doi.org/10.1007/s12532-018-0147-4) 及びその [Supplementary material 1](https://static-content.springer.com/esm/art%3A10.1007%2Fs12532-018-0147-4/MediaObjects/12532_2018_147_MOESM1_ESM.pdf) に従います。 QPLIB ファイル形式では、以下のモデルのファイル入出力に対応します。 * バイナリ変数・整数変数・実数変数を含む問題、およびこれらの変数を組み合わせた問題 * 二次以下の目的関数と制約条件で構成された問題 * QPLIB フォーマットで表現可能な目的関数・制約をもつ問題 ### 制限事項 QPLIB ファイルの入出力において以下の制限があります。 * Amplify SDK で設定した変数名や制約条件名が、半角スペースおよび改行やタブなどの制御文字 (`\n, \r, \t, \v, \f`) を含む場合、正常な QPLIB ファイルとして出力されません * Amplify SDK で設定した制約条件の重みは QPLIB ファイルに保存されません * QPLIB ファイルの読み込みにおいて、変数の初期値に関する記述は無視されます ## LP/QPLIB ファイルへの出力 Amplify SDK で作成したモデルをファイルに出力するには、 [`save_lp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_lp.md#amplify.save_lp) または [`save_qplib()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_qplib.md#amplify.save_qplib) の引数に [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) とファイルパスを与えます。 ```python from amplify import VariableGenerator, Model, one_hot, save_lp gen = VariableGenerator() q = gen.array("Binary", 4) f = 2 * q[0] * q[1] + q[2] * q[3] + q[0] + q[1] + q[2] + q[3] - 1 c = one_hot(q[:3]) # q_0 + q_1 + q_2 == 1 model = Model(f, c) save_lp(model, "model.lp") ``` このとき、`model.lp` がカレントディレクトリに保存されます。 model.lp ```text Minimize 1 q_0 + 1 q_1 + 1 q_2 + 1 q_3 + [ 4 q_0 * q_1 + 2 q_2 * q_3 ] / 2 - 1 Subject To 1 q_0 + 1 q_1 + 1 q_2 = 1 Bounds q_0 free q_1 free q_2 free q_3 free Binaries q_0 q_1 q_2 q_3 Generals End ``` 同様にして、QPLIB ファイルに保存する場合は以下のようにします。 ```python from amplify import save_qplib save_qplib(model, "model.qplib") ``` このとき、`model.qplib` がカレントディレクトリに保存されます。 model.qplib ```text ! ------------------- ! problem information ! ------------------- # problem name Amplify # problem type QBL # problem sense minimize # number of variables 4 # number of constraints 1 ! ------------------ ! objective function ! ------------------ # quadratic terms 2 1 2 4 3 4 2 # linear terms 0 4 1 1 2 1 3 1 4 1 # constant -1 ! ----------- ! constraints ! ----------- # linear terms 3 1 1 1 1 2 1 1 3 1 # infinity value 1.0e+20 # lower bounds -2.0e+20 1 1 1 # upper bounds 2.0e+20 1 1 1 ! --------------- ! starting points ! --------------- # starting point for variables 0 0 # starting point for Lagrange multipliers 0 0 # starting point for dual variables 0 0 ! ----------------------------- ! variable and constraint names ! ----------------------------- # variable names 4 1 q_0 2 q_1 3 q_2 4 q_3 # constraint names 0 ``` > [!NOTE] > > **注釈** > > LP ファイルと QPLIB ファイルは、変数を名前で識別します。 > そのため、Amplify SDK での定式化において、モデルに含まれる変数の名前が重複しないように注意してください。 ## LP/QPLIB ファイルからの読み込み [`load_lp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) または [`load_qplib()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib) の引数に LP/QPLIB ファイルのパスを与えると、([`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)) のタプルが得られます。要素はそれぞれ、ファイルに記述された定式化モデルと、変数の発行に使われた変数ジェネレータを表します。 たとえば、上の [`save_lp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_lp.md#amplify.save_lp) の例で保存した `model.lp` は、以下のように読み込まれます。 ```python from amplify import load_lp model, gen = load_lp("model.lp") ``` ```pycon >>> print(model) minimize: 2 q_0 q_1 + q_2 q_3 + q_0 + q_1 + q_2 + q_3 - 1 subject to: q_0 + q_1 + q_2 == 1 (weight: 1) ``` ファイルに定義されている決定変数は以下のように確認できます。 ```pycon >>> model.variables [Variable({name: q_0, id: 0, type: Binary}), Variable({name: q_1, id: 1, type: Binary}), Variable({name: q_2, id: 2, type: Binary}), Variable({name: q_3, id: 3, type: Binary})] ``` 読み込まれたモデルは通常通り [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) に渡すことで求解が実行されます。 ```python from amplify import solve, AmplifyAEClient client = AmplifyAEClient() client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" result = solve(model, client) ``` 変数名と得られた解の値の対応関係は次のようにして辞書で取得できます。 ```python >>> {k.name: v for k,v in result.best.values.items()} {'q_0': 0.0, 'q_1': 1.0, 'q_2': 0.0, 'q_3': 0.0} ``` ### 読み込み後のモデルの変更 ファイルから読み込まれたモデルに対して、モデルに含まれる変数から多項式を作成し、モデルを変更し目的関数の改変や制約条件の追加が可能です。 次のようにして、モデルに含まれる変数を [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) のリストに変換します。 ```python from amplify import Poly # モデルの読み込み model, gen = load_lp("model.lp") # モデルに含まれる変数を Poly のリストに変換 vars = [Poly(v) for v in model.variables] # モデルの目的関数の変更と制約条件の追加 model += vars[1] * vars[2] model += one_hot(sum(vars[1:])) ``` モデル読み込み時に得られた変数ジェネレータを使って新しい変数を生成し、新たな項を追加することもできます。 ここで新しく発行する変数には、既存のモデルに含まれる変数の名前とは重複しないようしてください。 ```python # 変数ジェネレータで新しく整数変数 "n" を生成 add_vars = gen.array("Integer", 2, bounds=(1, 4), name="n") # モデルの目的関数を変更 model += 2 * add_vars[0] - add_vars[1] ``` モデルが変更されたことが確認できます。 ```pycon >>> print(model) minimize: 2 q_0 q_1 + q_1 q_2 + q_2 q_3 + q_0 + q_1 + q_2 + q_3 + 2 n_0 - n_1 - 1 subject to: q_0 + q_1 + q_2 == 1 (weight: 1), q_1 + q_2 + q_3 == 1 (weight: 1) ``` ### 制約条件の重みを設定する LP ファイルおよび QPLIB ファイルには、制約条件の重みを記述することができません。 そのため、必要であれば、モデルをロードした後に制約の重みを設定します。 (参考:「[制約条件の構築/制約条件の重みを設定する](https://amplify.fixstars.com/ja/docs/amplify/v1/constraint.md#constraint-weight)」) 先ほど変更したモデルを一度ファイルに出力し、再度読み込んで例として使用します。 ```python # モデルの出力 save_lp(model, "model.lp") # モデルの再読み込み model, gen = load_lp("model.lp") # モデルに含まれる制約条件リストを取り出す constraints = model.constraints ``` ```pycon >>> print(constraints) [q_0 + q_1 + q_2 == 1 (weight: 1), q_1 + q_2 + q_3 == 1 (weight: 1)] >>> constraints *= 2 >>> print(constraints) [q_0 + q_1 + q_2 == 1 (weight: 2), q_1 + q_2 + q_3 == 1 (weight: 2)] >>> constraints[0].weight = 5 >>> print(constraints) [q_0 + q_1 + q_2 == 1 (weight: 5), q_1 + q_2 + q_3 == 1 (weight: 2)] ``` ### ペナルティ関数の生成アルゴリズムの指定 [`load_lp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) と [`load_qplib()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib) は、第二引数に [`PenaltyFormulation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation) を与えることができます。 これは、不等式制約のペナルティを生成する際に使用するアルゴリズムであり、デフォルトは [`Default`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default) です。(参考:「[制約条件とペナルティ関数/不等式制約](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#ineq-penalty)」) ```python from amplify import VariableGenerator, Model, save_lp, load_lp, less_equal gen = VariableGenerator() q = gen.array("Binary", 3) c = less_equal(q[0] + q[1] + q[2], 2) model = Model(c) save_lp(model, "model.lp") ``` ```pycon >>> model, gen = load_lp("model.lp", "Default") >>> print(model.constraints[0].penalty) 2 q_0 q_1 + 2 q_0 q_2 - 2 q_0 n_0 + 2 q_1 q_2 - 2 q_1 n_0 - 2 q_2 n_0 + n_0^2 + q_0 + q_1 + q_2 >>> model, gen = load_lp("model.lp", "LinearRelaxation") >>> print(model.constraints[0].penalty) 0.5 q_0 + 0.5 q_1 + 0.5 q_2 ``` --- # 部分和問題 このページでは、Amplify SDK を用いた定式化と求解の簡単な例として、部分和問題を扱います。 部分和問題とは、以下のような問題です。 $N$, $K$ を正の整数とします。$N$ 個の正の整数からなる数列 $A_0, A_1, \ldots, A_{N - 1}$ があります。 この数列の部分列であって、要素の総和が $K$ に最も近くなるものを求めてください。 あるいは、以下のような言い換えが考えられます。 $N$ 本の動画があり、その長さはさまざまです。これらの中からいくつかを選んで、合計時間が $K$ 分に最も近くなるようにするには、どの動画を選ぶべきでしょうか? ## 問題の作成 Amplify SDK を用いて部分和問題を解く前に、まずは部分和問題を作成し、プログラムコード上で表現します。今回は例題として、要素数 $N=10$ の簡単な問題を扱います。 ```python import numpy as np N = 10 K = 27 A = np.array([2, 10, 3, 8, 5, 7, 9, 5, 3, 2]) ``` ## Amplify SDK による定式化 Amplify SDK による定式化を行うためには、部分和問題を多項式の最小化問題に言い換える必要があります。 まず、「部分列の要素の和が $K$ に最も近いもの」は、「部分列の要素の和と $K$ の差を 2 乗した値が最小となるもの」に言い換えられます。また、「部分列の要素の和」は、数列の $i$ 番目の要素が選ばれるなら $1$, そうでないなら $0$ をとる変数 $q_i$ を用いて、$q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1}$ と書くことができます。 したがって、部分和問題は以下のように定式化されます。 変数 $q_0, q_1, \ldots, q_{N-1}$ が $0$ または $1$ の値をとるとき、 $$ \quad (q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2 $$ を最小化してください。 上記の $\quad (q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2$ のことを目的関数とよびます。 以上を Amplify SDK 上で表現していきましょう。 決定変数 (組合せ最適化において最適化対象の変数) を作成します。まず、変数を発行するためのクラス [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) をインスタンス化します。必要な変数は、 $0$ または $1$ の値をとる変数が $N$ 個です。$0$ または $1$ の値をとる変数はバイナリ変数といい、Amplify SDK では簡単に作成できます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", N) # 第一引数に変数の種類を、第二引数に変数の数を与える q ``` $$ \displaystyle [q_0, q_1, q_2, q_3, q_4, q_5, q_6, q_7, q_8, q_9] $$ 目的関数 $\quad (q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2$ を作成します。NumPy-like な記法を用いて、以下のように書くことができます。 ```python objective = ((q * A).sum() - K) ** 2 print(objective) ``` ```text 40 q_0 q_1 + 12 q_0 q_2 + 32 q_0 q_3 + 20 q_0 q_4 + 28 q_0 q_5 + 36 q_0 q_6 + 20 q_0 q_7 + 12 q_0 q_8 + 8 q_0 q_9 + 60 q_1 q_2 + 160 q_1 q_3 + 100 q_1 q_4 + 140 q_1 q_5 + 180 q_1 q_6 + 100 q_1 q_7 + 60 q_1 q_8 + 40 q_1 q_9 + 48 q_2 q_3 + 30 q_2 q_4 + 42 q_2 q_5 + 54 q_2 q_6 + 30 q_2 q_7 + 18 q_2 q_8 + 12 q_2 q_9 + 80 q_3 q_4 + 112 q_3 q_5 + 144 q_3 q_6 + 80 q_3 q_7 + 48 q_3 q_8 + 32 q_3 q_9 + 70 q_4 q_5 + 90 q_4 q_6 + 50 q_4 q_7 + 30 q_4 q_8 + 20 q_4 q_9 + 126 q_5 q_6 + 70 q_5 q_7 + 42 q_5 q_8 + 28 q_5 q_9 + 90 q_6 q_7 + 54 q_6 q_8 + 36 q_6 q_9 + 30 q_7 q_8 + 20 q_7 q_9 + 12 q_8 q_9 - 104 q_0 - 440 q_1 - 153 q_2 - 368 q_3 - 245 q_4 - 329 q_5 - 405 q_6 - 245 q_7 - 153 q_8 - 104 q_9 + 729 ``` > [!NOTE] > > **注釈** > > もちろん、古典的な Python 風に > > ``` > objective = sum(x * a for x, a in zip(q, A)) > ``` > > などと書くこともできます。ただし、このような書き方は問題やデータサイズによっては時間がかかる場合があるため、`objective = (q * A) ** 2` のような NumPy-like な書き方を推奨しています。詳しくは [定式化の高速化](https://amplify.fixstars.com/ja/docs/amplify/v1/optimization.md) を参照してください。 作成した目的関数を使って、組合せ最適化モデルを構築します。 ```python from amplify import Model model = Model(objective) print(model) ``` ```text minimize: 40 q_0 q_1 + 12 q_0 q_2 + 32 q_0 q_3 + 20 q_0 q_4 + 28 q_0 q_5 + 36 q_0 q_6 + 20 q_0 q_7 + 12 q_0 q_8 + 8 q_0 q_9 + 60 q_1 q_2 + 160 q_1 q_3 + 100 q_1 q_4 + 140 q_1 q_5 + 180 q_1 q_6 + 100 q_1 q_7 + 60 q_1 q_8 + 40 q_1 q_9 + 48 q_2 q_3 + 30 q_2 q_4 + 42 q_2 q_5 + 54 q_2 q_6 + 30 q_2 q_7 + 18 q_2 q_8 + 12 q_2 q_9 + 80 q_3 q_4 + 112 q_3 q_5 + 144 q_3 q_6 + 80 q_3 q_7 + 48 q_3 q_8 + 32 q_3 q_9 + 70 q_4 q_5 + 90 q_4 q_6 + 50 q_4 q_7 + 30 q_4 q_8 + 20 q_4 q_9 + 126 q_5 q_6 + 70 q_5 q_7 + 42 q_5 q_8 + 28 q_5 q_9 + 90 q_6 q_7 + 54 q_6 q_8 + 36 q_6 q_9 + 30 q_7 q_8 + 20 q_7 q_9 + 12 q_8 q_9 - 104 q_0 - 440 q_1 - 153 q_2 - 368 q_3 - 245 q_4 - 329 q_5 - 405 q_6 - 245 q_7 - 153 q_8 - 104 q_9 + 729 ``` これで組合せ最適化モデルの構築が完了しました。 ## ソルバーの設定 Amplify SDK を用いて、さまざまな組合せ最適化ソルバーに求解を行わせることができます。このページでは、例として、クラウドサービスとして提供されている Fixstars Amplify AE を使用します。 まず、どのソルバーを使用するかを指定するために、Amplify AE に対応する Amplify SDK のソルバークライアント [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を作成します。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` ソルバーで求解を行うために必要なトークンと、ソルバーのパラメータを設定します。 ```python from datetime import timedelta client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` これでソルバーの設定は完了です。 ## Amplify SDK による求解 上記で作成した組合せ最適化モデルとソルバークライアントを使用して、求解を実行します。以下のコードを実行することで、Amplify AE で部分和問題を求解することができます。 ```python from amplify import solve result = solve(model, client) ``` 変数 $q = (q_0, q_1, \ldots, q_{N-1})$ の値は、以下のように得ることができます。 ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [1. 0. 1. 1. 0. 0. 1. 0. 1. 1.] ``` バイナリ変数 $q_i$ は、数列 $A$ の $i$ 番目の要素が選ばれるなら $1$、そうでないときは $0$ をとるので、部分和問題の最適解は以下のように表示できます。 ```python print(f"selected numbers: {[a for x, a in zip(q_values, A) if x == 1]}") ``` ```text selected numbers: [np.int64(2), np.int64(3), np.int64(8), np.int64(9), np.int64(3), np.int64(2)] ``` 和が $K=27$ と近い値になっていることを確かめます。 ```python print( f"{K=}, sum of selected numbers = {sum(a for x, a in zip(q_values, A) if x == 1)}" ) ``` ```text K=27, sum of selected numbers = 27 ``` --- # Max-Cut (最大カット) 問題 Max-Cut (最大カット) 問題は、代表的な組合せ最適化問題の一つです。ここでは、問題の定義から、Amplify SDK を用いた求解までを解説します。 ## 1. 問題の定義とイジング変数 Max-Cut 問題は、グラフ $G=(V, E)$ の頂点集合 $V$ を二つの部分集合 $V_1$ と $V_2$ に分割し、カットされる辺の重みの総和を最大化することを目的とします。 ### イジング変数による分割の表現 各頂点 $i \in V$ がどちらの集合に属するかを表すために、イジング変数 $s_i \in \{-1, +1\}$ を導入します。 * $s_i = +1$ の場合、頂点 $i$ は集合 $V_1$ に属する * $s_i = -1$ の場合、頂点 $i$ は集合 $V_2$ に属する ### カット条件の表現 辺 $(i, j) \in E$ がカットされるのは、頂点 $i$ と $j$ が異なる集合に属するとき、すなわち $s_i$ と $s_j$ の値が異なる場合 ($s_i s_j = -1$) です。 ここで、項 $\left(1 - s_i s_j\right)/2$ を考えると、以下のようになります。 | $s_i$ | $s_j$ | $s_i s_j$ | $\left(1 - s_i s_j\right)/2$ | 意味 (カット) | | --- | --- | --- | --- | --- | | +1 | +1 | +1 | 0 | カットされない | | -1 | -1 | +1 | 0 | カットされない | | +1 | -1 | -1 | 1 | カットされる | | -1 | +1 | -1 | 1 | カットされる | この項は辺がカットされた場合に 1、カットされない場合に 0 を取り、そのまま目的関数に利用できます。 ## 2. 定式化 ### 目的関数 (最大化) 辺 $(i, j)$ の重みを $w_{ij}$ とすると、Max-Cut 問題は以下の最大化問題として定式化されます。 $$ \text{maximize} \quad J(s) = \sum_{(i, j) \in E} w_{ij} \left( \frac{1 - s_i s_j}{2} \right) $$ ### 目的関数 (最小化 / Ising 形式) Amplify SDK はエネルギーを最小化するため、定数項を除いた以下のイジングハミルトニアンの最小化として扱います。 $$ \text{minimize} \quad H(s) = \sum_{(i, j) \in E} w_{ij} s_i s_j $$ ## 問題の作成 4 つの頂点 $\{0, 1, 2, 3\}$ を持ち、辺の重みが全て 1.0 の以下のグラフを考えます。 ![maxcut_problem](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/MaxCut-problem.drawio.svg) グラフの隣接行列を重み行列として定義します。頂点 0-1, 1-2, 2-3, 3-0 が辺で結ばれており、重みは全て 1.0 です。 ```python import numpy as np weights = np.array([ [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], ]) ``` ## Amplify SDK による定式化 ### 変数の生成 各頂点に対応するイジング変数 $s_0, s_1, s_2, s_3$ を作成します。イジング変数は $\{-1, +1\}$ の値をとる変数で、Amplify SDK では `"Ising"` を指定することで作成できます。 ```python from amplify import VariableGenerator gen = VariableGenerator() s = gen.array("Ising", 4) s ``` $$ \displaystyle [s_0, s_1, s_2, s_3] $$ ### 目的関数の作成 目的関数 $H(s) = \sum_{(i, j) \in E} w_{ij} s_i s_j$ を `einsum` を用いて構築します。 ```python from amplify import einsum objective = einsum("i,j,ij->", s, s, weights) print(objective) ``` ```text 2 s_0 s_1 + 2 s_0 s_3 + 2 s_1 s_2 + 2 s_2 s_3 ``` 作成した目的関数を使って、組合せ最適化モデルを構築します。 ```python from amplify import Model model = Model(objective) print(model) ``` ```text minimize: 2 s_0 s_1 + 2 s_0 s_3 + 2 s_1 s_2 + 2 s_2 s_3 ``` ## ソルバーの設定 ソルバークライアントを作成し、求解を行うためのソルバーの指定およびパラメータの設定を行います。本サンプルコードでは Amplify AE を使用します。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` ソルバーで求解を行うために必要なトークンと、ソルバーのパラメータを設定します。 ```python from datetime import timedelta client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` ## Amplify SDK による求解 上記で作成した組合せ最適化モデルとソルバークライアントを使用して、求解を実行します。 ```python from amplify import solve result = solve(model, client) ``` ## 結果の確認 変数 $s = (s_0, s_1, s_2, s_3)$ の値は、以下のように得ることができます。 ```python s_values = s.evaluate(result.best.values) print(f"objective: {result.best.objective}") print(f"solution: {s_values}") ``` ```text objective: -8.0 solution: [ 1. -1. 1. -1.] ``` 解 $[-1, 1, -1, 1]$ または $[1, -1, 1, -1]$ が得られます。これらは全体の符号が反転しただけで同じカット構造を表しています。いずれも頂点 $\{0, 2\}$ と $\{1, 3\}$ への分割に対応し、以下の図のようになります。 ![maxcut_answer](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/MaxCut-answer.drawio.svg) 頂点 0 と 2 が一方のグループに、頂点 1 と 3 がもう一方のグループに分割されることで、カットされる辺の重みの総和が最大化されます。 --- # 巡回セールスマン問題 Amplify の使用例として、巡回セールスマン問題を Amplify を用いて解く方法を解説します。 巡回セールスマン問題とは、いくつかの都市の集合が与えられたとき、ある都市から出発してすべての都市を 1 回ずつ訪れたあと最初の都市に戻ってくる巡回路のうち、最も長さが短いものを求める組合せ最適化問題です。 ## 巡回セールスマン問題の定式化 以下では、都市の数を `NUM_CITIES` と表記します。 ### 変数 まず、`NUM_CITIES` 個の都市のうちどの都市を訪れるかを表すために、 `NUM_CITIES` 個のバイナリ (0-1) 変数を用いることにします。都市 `i` を訪れる場合、`i` 番目のバイナリ変数を 1 、それ以外の変数を 0 とすることで表現します。 たとえば都市数が 5 であり 5 つのバイナリ変数の値が `[0, 0, 0, 1, 0]` の場合、インデックス 3 の変数のみが 1 となっているので都市 3 を訪れることの表現となっています。このように、n 個の選択肢の中からどれを選ぶかを n 個のバイナリ変数のうち 1 つを 1 にすることで表す方法を one-hot エンコーディングといい、機械学習などでもよく使われます。 | 都市 0 | 都市 1 | 都市 2 | 都市 3 | 都市 4 | | --- | --- | --- | --- | --- | | 0 | 0 | 0 | 1 | 0 | 巡回路では都市を 1 回ずつ訪れて最後に最初の都市に戻ってくるので、最初と最後も含めて `NUM_CITIES + 1` 回都市を訪れることになります。したがって、 `(NUM_CITIES + 1) * NUM_CITIES` 個のバイナリ変数を用意します。たとえば以下の例は、都市 3 → 都市 1 → 都市 4 → 都市 0 → 都市 2 → 都市 3 の順に 5 つの都市を訪れる巡回路を表現します。 バイナリ変数表 | 都市 0 | 都市 1 | 都市 2 | 都市 3 | 都市 4 | | --- | --- | --- | --- | --- | | 0 | 0 | 0 | 1 | 0 | | 0 | 1 | 0 | 0 | 0 | | 0 | 0 | 0 | 0 | 1 | | 1 | 0 | 0 | 0 | 0 | | 0 | 0 | 1 | 0 | 0 | | 0 | 0 | 0 | 1 | 0 | ### 制約条件 上の「バイナリ変数表」において、`(NUM_CITIES + 1) * NUM_CITIES` 個のバイナリ変数が好き勝手に 0 または 1 の値をとっても巡回路の表現になるとは限りません。たとえば、すべてのバイナリ変数の値が 1 であるとき、何の巡回路も表しません。したがって、バイナリ変数に制約を課す必要があります。必要な制約は以下の 3 種類です。 1. バイナリ変数表の最初の行と最後の行は、同じ値をとる。 2. バイナリ変数表の各行のうち、値が 1 となっている箇所はちょうど 1 つだけである。 3. バイナリ変数表の各列において、値が 1 となっている箇所は最後の行を除きちょうど 1 つだけである。 逆に、以上の 3 つの制約をみたしているバイナリ変数表があるとき、それはある巡回路の表現となっています。 ### 目的関数 巡回セールスマン問題の目的は、巡回路のうち最も経路長が短いものを探すことです。したがって、目的関数は巡回路の経路長となります。 都市 i と都市 j の距離が `d[i, j]` であるとします。現在のゴールは、バイナリ変数表の値から巡回路の経路長を求めることです。 バイナリ変数表の値が分かっている場合、巡回路の経路長は以下の疑似コードのようにして求められます。ただし、`k` 行 `i` 列のバイナリ変数が `q[k, i]` と書けるとします。 ``` route_length = 0 for k in range(NUM_CITIES): for i in range(NUM_CITIES): for j in range(NUM_CITIES): route_length += (d[i, j] if q[k, i] == 1 and q[k+1, j] == 1 else 0) ``` しかし Amplify で定式化を行う場合、それぞれの `q[k, i]` はバイナリ変数であることが分かっているのみでまだ何の値を取るかは分からないので、`if q[k, i] == 1 and q[k+1, j] == 1` という条件式の判定を行うことはできません。バイナリ変数や数値の足し算および掛け算で目的関数を表す必要があります。 ここで、2 つのバイナリ変数の積 `q[k, i] * q[k+1, j]` は `q[k, i] == 1 and q[k+1, j] == 1` が True のとき 1 となり、False のときは 0 となることを思い出します。すると、目的関数は ``` route_length = 0 for k in range(NUM_CITIES): for i in range(NUM_CITIES): for j in range(NUM_CITIES): route_length += d[i, j] * q[k, i] * q[k+1, j] ``` と書くことができることが分かります。 ### 定式化 以上の議論を数式で書き下すと、巡回セールスマン問題の定式化は `(NUM_CITIES + 1) * NUM_CITIES` 個のバイナリ変数を用いて $$ \begin{align} &\text{minimize} \quad & \sum_{0 \leq i, j, k < N} d_{i, j} q_{k, i} q_{k+1, j} & \\ &\text{subject to} \quad & q_{N - 1, i} = q_{0, i} \quad & \text{for} \quad 0 \leq i < N, \\ & & \sum_{0 \leq i} q_{k, i} = 1 \quad & \text{for} \quad 0 \leq k < N, \\ & & \sum_{0 \leq k} q_{k, i} = 1 \quad & \text{for} \quad 0 \leq i < N \end{align} $$ となります。ただし表記の都合上、都市数 `NUM_CITIES` を $N$ と表記しています。 ## 問題の作成 まず、問題を作成します。都市数を `NUM_CITIES` として、それぞれの都市の x 座標と y 座標を 0~100 の整数の中からランダムに選びます。以下では、都市の名前を都市 0, 都市 1, ..., 都市 `NUM_CITIES - 1` と呼ぶことにします。 本サンプルコードでは、簡単のため都市数を 5 とします。 ```python import numpy as np ``` ```python NUM_CITIES = 5 ``` ```python rng = np.random.default_rng() x = rng.integers(0, 100, NUM_CITIES) y = rng.integers(0, 100, NUM_CITIES) ``` 次に、都市間の距離を表す距離行列を作成します。距離はユークリッド距離を用います。出力は `n * n` の NumPy 配列で、`i` 行 `j` 列の要素は都市 `i` と都市 `j` 間の距離、すなわち `(x[i] - x[j]) ** 2 + (y[i] - y[j] ** 2) ** 0.5` を表します。 ```python distance = ( (x[:, np.newaxis] - x[np.newaxis, :]) ** 2 + (y[:, np.newaxis] - y[np.newaxis, :]) ** 2 ) ** 0.5 print(distance) ``` ```text [[ 0. 63.348 74.33 93.606 115.109] [ 63.348 0. 37.656 48.836 76.792] [ 74.33 37.656 0. 19.416 42.953] [ 93.606 48.836 19.416 0. 28.071] [115.109 76.792 42.953 28.071 0. ]] ``` ## Amplify SDK による定式化 Amplify SDK を用いた定式化を行います。 ### 変数の生成 まず、決定変数を作成します。`(NUM_CITIES + 1) * NUM_CITIES` 個のバイナリ変数が必要です。Amplify SDK では、[`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) を使用することにより 2 次元配列の形で変数を生成することができます。 ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", (NUM_CITIES + 1, NUM_CITIES)) ``` バイナリ変数 `q` を表示してみると、以下のようになります。 ```python q ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}& q_{0,4}\\q_{1,0}& q_{1,1}& q_{1,2}& q_{1,3}& q_{1,4}\\q_{2,0}& q_{2,1}& q_{2,2}& q_{2,3}& q_{2,4}\\q_{3,0}& q_{3,1}& q_{3,2}& q_{3,3}& q_{3,4}\\q_{4,0}& q_{4,1}& q_{4,2}& q_{4,3}& q_{4,4}\\q_{5,0}& q_{5,1}& q_{5,2}& q_{5,3}& q_{5,4}\end{matrix}\right]\end{aligned} $$ ### 制約条件の作成 次に、制約条件を作成します。[前述](#tsp-formulation-constraint)の通り、作成するべき制約条件は以下の 3 種類です。 1. バイナリ変数表の最初の行と最後の行は、同じ値をとる。 2. バイナリ変数表の各行のうち、値が 1 となっている箇所はちょうど 1 つだけである。 3. バイナリ変数表の各列において、値が 1 となっている箇所は最後の行を除きちょうど 1 つだけである。 #### 1 つ目の制約条件 1 つ目の制約条件「バイナリ変数表の最初の行と最後の行は、同じ値をとる。」を作成します。最後の行を最初の行と同じ値に固定したいので、`q` の最後の行に最初の行を代入します。`q` の最初の行は `q[0]`、`q` の最後の行は `q[-1]` と書くことができます。 ```python q[-1] = q[0] q ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}& q_{0,4}\\q_{1,0}& q_{1,1}& q_{1,2}& q_{1,3}& q_{1,4}\\q_{2,0}& q_{2,1}& q_{2,2}& q_{2,3}& q_{2,4}\\q_{3,0}& q_{3,1}& q_{3,2}& q_{3,3}& q_{3,4}\\q_{4,0}& q_{4,1}& q_{4,2}& q_{4,3}& q_{4,4}\\q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}& q_{0,4}\end{matrix}\right]\end{aligned} $$ これで 1 つ目の制約条件を表現することができました。 > [!WARNING] > > **注意** > > このように代入により変数を固定する操作を行う場合、目的関数や他の制約条件を構築する前に行ってください。 これ以降の制約条件の作成においては、バイナリ変数配列 `q` の最後の行のことは考える必要がないため、`q` の上から `NUM_CITIES` 行を切り出した配列を作成しておきます。 ```python q_upper = q[:-1] q_upper ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}& q_{0,4}\\q_{1,0}& q_{1,1}& q_{1,2}& q_{1,3}& q_{1,4}\\q_{2,0}& q_{2,1}& q_{2,2}& q_{2,3}& q_{2,4}\\q_{3,0}& q_{3,1}& q_{3,2}& q_{3,3}& q_{3,4}\\q_{4,0}& q_{4,1}& q_{4,2}& q_{4,3}& q_{4,4}\end{matrix}\right]\end{aligned} $$ #### 2 つ目の制約条件 2 つ目の制約条件「バイナリ変数表の各行のうち、値が 1 となっている箇所はちょうど 1 つだけである。」を作成します。いくつかのバイナリ変数のうちちょうど 1 つだけが 1 であるという制約条件を課したい場合、[`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数を使います。変数配列の各行に対して one-hot 制約を課したい場合、[`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数の `axis` キーワード引数に 1 を与えます。 ```python from amplify import one_hot constraints2 = one_hot(q_upper, axis=1) constraints2 ``` $$ \displaystyle \begin{array}{l}q_{0,0} + q_{0,1} + q_{0,2} + q_{0,3} + q_{0,4} = 1\ (\text{weight}\colon\ 1)\\q_{1,0} + q_{1,1} + q_{1,2} + q_{1,3} + q_{1,4} = 1\ (\text{weight}\colon\ 1)\\q_{2,0} + q_{2,1} + q_{2,2} + q_{2,3} + q_{2,4} = 1\ (\text{weight}\colon\ 1)\\q_{3,0} + q_{3,1} + q_{3,2} + q_{3,3} + q_{3,4} = 1\ (\text{weight}\colon\ 1)\\q_{4,0} + q_{4,1} + q_{4,2} + q_{4,3} + q_{4,4} = 1\ (\text{weight}\colon\ 1)\end{array} $$ `NUM_CITIES` (= 5) 個の制約条件が一気に生成されました。 #### 3 つ目の制約条件 3 つ目の制約条件「バイナリ変数表の各列において、値が 1 となっている箇所は最後の行を除きちょうど 1 つだけである。」を作成します。2 つ目の制約条件と同様に、[`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数を使います。変数配列の各列に対して one-hot 制約を課したい場合、[`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) 関数の `axis` キーワード引数に 0 を与えます。 ```python constraints3 = one_hot(q_upper, axis=0) constraints3 ``` $$ \displaystyle \begin{array}{l}q_{0,0} + q_{1,0} + q_{2,0} + q_{3,0} + q_{4,0} = 1\ (\text{weight}\colon\ 1)\\q_{0,1} + q_{1,1} + q_{2,1} + q_{3,1} + q_{4,1} = 1\ (\text{weight}\colon\ 1)\\q_{0,2} + q_{1,2} + q_{2,2} + q_{3,2} + q_{4,2} = 1\ (\text{weight}\colon\ 1)\\q_{0,3} + q_{1,3} + q_{2,3} + q_{3,3} + q_{4,3} = 1\ (\text{weight}\colon\ 1)\\q_{0,4} + q_{1,4} + q_{2,4} + q_{3,4} + q_{4,4} = 1\ (\text{weight}\colon\ 1)\end{array} $$ ### 目的関数の作成 次に、目的関数を作成します。[前述](#tsp-formulation-objective)の通り、目的関数は巡回路の経路長であり、以下のように書くことができます。 ```python route_length = 0 for k in range(NUM_CITIES): for i in range(NUM_CITIES): for j in range(NUM_CITIES): route_length += distance[i, j] * q[k, i] * q[k + 1, j] print(route_length) ``` ```text 63.3482438588474 q_{0,0} q_{1,1} + 74.3303437365925 q_{0,0} q_{1,2} + 93.6055553906925 q_{0,0} q_{1,3} + 115.108644332213 q_{0,0} q_{1,4} + 63.3482438588474 q_{0,0} q_{4,1} + 74.3303437365925 q_{0,0} q_{4,2} + 93.6055553906925 q_{0,0} q_{4,3} + 115.108644332213 q_{0,0} q_{4,4} + 63.3482438588474 q_{0,1} q_{1,0} + 37.6563407675255 q_{0,1} q_{1,2} + 48.8364617882991 q_{0,1} q_{1,3} + 76.791926658992 q_{0,1} q_{1,4} + 63.3482438588474 q_{0,1} q_{4,0} + 37.6563407675255 q_{0,1} q_{4,2} + 48.8364617882991 q_{0,1} q_{4,3} + 76.791926658992 q_{0,1} q_{4,4} + 74.3303437365925 q_{0,2} q_{1,0} + 37.6563407675255 q_{0,2} q_{1,1} + 19.4164878389476 q_{0,2} q_{1,3} + 42.9534631898291 q_{0,2} q_{1,4} + 74.3303437365925 q_{0,2} q_{4,0} + 37.6563407675255 q_{0,2} q_{4,1} + 19.4164878389476 q_{0,2} q_{4,3} + 42.9534631898291 q_{0,2} q_{4,4} + 93.6055553906925 q_{0,3} q_{1,0} + 48.8364617882991 q_{0,3} q_{1,1} + 19.4164878389476 q_{0,3} q_{1,2} + 28.0713376952364 q_{0,3} q_{1,4} + 93.6055553906925 q_{0,3} q_{4,0} + 48.8364617882991 q_{0,3} q_{4,1} + 19.4164878389476 q_{0,3} q_{4,2} + 28.0713376952364 q_{0,3} q_{4,4} + 115.108644332213 q_{0,4} q_{1,0} + 76.791926658992 q_{0,4} q_{1,1} + 42.9534631898291 q_{0,4} q_{1,2} + 28.0713376952364 q_{0,4} q_{1,3} + 115.108644332213 q_{0,4} q_{4,0} + 76.791926658992 q_{0,4} q_{4,1} + 42.9534631898291 q_{0,4} q_{4,2} + 28.0713376952364 q_{0,4} q_{4,3} + 63.3482438588474 q_{1,0} q_{2,1} + 74.3303437365925 q_{1,0} q_{2,2} + 93.6055553906925 q_{1,0} q_{2,3} + 115.108644332213 q_{1,0} q_{2,4} + 63.3482438588474 q_{1,1} q_{2,0} + 37.6563407675255 q_{1,1} q_{2,2} + 48.8364617882991 q_{1,1} q_{2,3} + 76.791926658992 q_{1,1} q_{2,4} + 74.3303437365925 q_{1,2} q_{2,0} + 37.6563407675255 q_{1,2} q_{2,1} + 19.4164878389476 q_{1,2} q_{2,3} + 42.9534631898291 q_{1,2} q_{2,4} + 93.6055553906925 q_{1,3} q_{2,0} + 48.8364617882991 q_{1,3} q_{2,1} + 19.4164878389476 q_{1,3} q_{2,2} + 28.0713376952364 q_{1,3} q_{2,4} + 115.108644332213 q_{1,4} q_{2,0} + 76.791926658992 q_{1,4} q_{2,1} + 42.9534631898291 q_{1,4} q_{2,2} + 28.0713376952364 q_{1,4} q_{2,3} + 63.3482438588474 q_{2,0} q_{3,1} + 74.3303437365925 q_{2,0} q_{3,2} + 93.6055553906925 q_{2,0} q_{3,3} + 115.108644332213 q_{2,0} q_{3,4} + 63.3482438588474 q_{2,1} q_{3,0} + 37.6563407675255 q_{2,1} q_{3,2} + 48.8364617882991 q_{2,1} q_{3,3} + 76.791926658992 q_{2,1} q_{3,4} + 74.3303437365925 q_{2,2} q_{3,0} + 37.6563407675255 q_{2,2} q_{3,1} + 19.4164878389476 q_{2,2} q_{3,3} + 42.9534631898291 q_{2,2} q_{3,4} + 93.6055553906925 q_{2,3} q_{3,0} + 48.8364617882991 q_{2,3} q_{3,1} + 19.4164878389476 q_{2,3} q_{3,2} + 28.0713376952364 q_{2,3} q_{3,4} + 115.108644332213 q_{2,4} q_{3,0} + 76.791926658992 q_{2,4} q_{3,1} + 42.9534631898291 q_{2,4} q_{3,2} + 28.0713376952364 q_{2,4} q_{3,3} + 63.3482438588474 q_{3,0} q_{4,1} + 74.3303437365925 q_{3,0} q_{4,2} + 93.6055553906925 q_{3,0} q_{4,3} + 115.108644332213 q_{3,0} q_{4,4} + 63.3482438588474 q_{3,1} q_{4,0} + 37.6563407675255 q_{3,1} q_{4,2} + 48.8364617882991 q_{3,1} q_{4,3} + 76.791926658992 q_{3,1} q_{4,4} + 74.3303437365925 q_{3,2} q_{4,0} + 37.6563407675255 q_{3,2} q_{4,1} + 19.4164878389476 q_{3,2} q_{4,3} + 42.9534631898291 q_{3,2} q_{4,4} + 93.6055553906925 q_{3,3} q_{4,0} + 48.8364617882991 q_{3,3} q_{4,1} + 19.4164878389476 q_{3,3} q_{4,2} + 28.0713376952364 q_{3,3} q_{4,4} + 115.108644332213 q_{3,4} q_{4,0} + 76.791926658992 q_{3,4} q_{4,1} + 42.9534631898291 q_{3,4} q_{4,2} + 28.0713376952364 q_{3,4} q_{4,3} ``` あるいは、以下のように書いても同じ効果があります。こちらの方が Amplify SDK の機能をフルに活用しているため高速で、NumPy ライブラリに馴染みがある方には特におすすめです。詳細は[定式化の高速化](https://amplify.fixstars.com/ja/docs/amplify/v1/optimization.md)を参照してください。 ```python from amplify import Poly, einsum q1 = q[:-1] q2 = q[1:] route_length: Poly = einsum("ij,ki,kj->", distance, q1, q2) # type: ignore print(route_length) ``` ```text 63.3482438588474 q_{0,0} q_{1,1} + 74.3303437365925 q_{0,0} q_{1,2} + 93.6055553906925 q_{0,0} q_{1,3} + 115.108644332213 q_{0,0} q_{1,4} + 63.3482438588474 q_{0,0} q_{4,1} + 74.3303437365925 q_{0,0} q_{4,2} + 93.6055553906925 q_{0,0} q_{4,3} + 115.108644332213 q_{0,0} q_{4,4} + 63.3482438588474 q_{0,1} q_{1,0} + 37.6563407675255 q_{0,1} q_{1,2} + 48.8364617882991 q_{0,1} q_{1,3} + 76.791926658992 q_{0,1} q_{1,4} + 63.3482438588474 q_{0,1} q_{4,0} + 37.6563407675255 q_{0,1} q_{4,2} + 48.8364617882991 q_{0,1} q_{4,3} + 76.791926658992 q_{0,1} q_{4,4} + 74.3303437365925 q_{0,2} q_{1,0} + 37.6563407675255 q_{0,2} q_{1,1} + 19.4164878389476 q_{0,2} q_{1,3} + 42.9534631898291 q_{0,2} q_{1,4} + 74.3303437365925 q_{0,2} q_{4,0} + 37.6563407675255 q_{0,2} q_{4,1} + 19.4164878389476 q_{0,2} q_{4,3} + 42.9534631898291 q_{0,2} q_{4,4} + 93.6055553906925 q_{0,3} q_{1,0} + 48.8364617882991 q_{0,3} q_{1,1} + 19.4164878389476 q_{0,3} q_{1,2} + 28.0713376952364 q_{0,3} q_{1,4} + 93.6055553906925 q_{0,3} q_{4,0} + 48.8364617882991 q_{0,3} q_{4,1} + 19.4164878389476 q_{0,3} q_{4,2} + 28.0713376952364 q_{0,3} q_{4,4} + 115.108644332213 q_{0,4} q_{1,0} + 76.791926658992 q_{0,4} q_{1,1} + 42.9534631898291 q_{0,4} q_{1,2} + 28.0713376952364 q_{0,4} q_{1,3} + 115.108644332213 q_{0,4} q_{4,0} + 76.791926658992 q_{0,4} q_{4,1} + 42.9534631898291 q_{0,4} q_{4,2} + 28.0713376952364 q_{0,4} q_{4,3} + 63.3482438588474 q_{1,0} q_{2,1} + 74.3303437365925 q_{1,0} q_{2,2} + 93.6055553906925 q_{1,0} q_{2,3} + 115.108644332213 q_{1,0} q_{2,4} + 63.3482438588474 q_{1,1} q_{2,0} + 37.6563407675255 q_{1,1} q_{2,2} + 48.8364617882991 q_{1,1} q_{2,3} + 76.791926658992 q_{1,1} q_{2,4} + 74.3303437365925 q_{1,2} q_{2,0} + 37.6563407675255 q_{1,2} q_{2,1} + 19.4164878389476 q_{1,2} q_{2,3} + 42.9534631898291 q_{1,2} q_{2,4} + 93.6055553906925 q_{1,3} q_{2,0} + 48.8364617882991 q_{1,3} q_{2,1} + 19.4164878389476 q_{1,3} q_{2,2} + 28.0713376952364 q_{1,3} q_{2,4} + 115.108644332213 q_{1,4} q_{2,0} + 76.791926658992 q_{1,4} q_{2,1} + 42.9534631898291 q_{1,4} q_{2,2} + 28.0713376952364 q_{1,4} q_{2,3} + 63.3482438588474 q_{2,0} q_{3,1} + 74.3303437365925 q_{2,0} q_{3,2} + 93.6055553906925 q_{2,0} q_{3,3} + 115.108644332213 q_{2,0} q_{3,4} + 63.3482438588474 q_{2,1} q_{3,0} + 37.6563407675255 q_{2,1} q_{3,2} + 48.8364617882991 q_{2,1} q_{3,3} + 76.791926658992 q_{2,1} q_{3,4} + 74.3303437365925 q_{2,2} q_{3,0} + 37.6563407675255 q_{2,2} q_{3,1} + 19.4164878389476 q_{2,2} q_{3,3} + 42.9534631898291 q_{2,2} q_{3,4} + 93.6055553906925 q_{2,3} q_{3,0} + 48.8364617882991 q_{2,3} q_{3,1} + 19.4164878389476 q_{2,3} q_{3,2} + 28.0713376952364 q_{2,3} q_{3,4} + 115.108644332213 q_{2,4} q_{3,0} + 76.791926658992 q_{2,4} q_{3,1} + 42.9534631898291 q_{2,4} q_{3,2} + 28.0713376952364 q_{2,4} q_{3,3} + 63.3482438588474 q_{3,0} q_{4,1} + 74.3303437365925 q_{3,0} q_{4,2} + 93.6055553906925 q_{3,0} q_{4,3} + 115.108644332213 q_{3,0} q_{4,4} + 63.3482438588474 q_{3,1} q_{4,0} + 37.6563407675255 q_{3,1} q_{4,2} + 48.8364617882991 q_{3,1} q_{4,3} + 76.791926658992 q_{3,1} q_{4,4} + 74.3303437365925 q_{3,2} q_{4,0} + 37.6563407675255 q_{3,2} q_{4,1} + 19.4164878389476 q_{3,2} q_{4,3} + 42.9534631898291 q_{3,2} q_{4,4} + 93.6055553906925 q_{3,3} q_{4,0} + 48.8364617882991 q_{3,3} q_{4,1} + 19.4164878389476 q_{3,3} q_{4,2} + 28.0713376952364 q_{3,3} q_{4,4} + 115.108644332213 q_{3,4} q_{4,0} + 76.791926658992 q_{3,4} q_{4,1} + 42.9534631898291 q_{3,4} q_{4,2} + 28.0713376952364 q_{3,4} q_{4,3} ``` ### 組合せ最適化モデルの作成 [制約条件の作成](#tsp-constraint)、[目的関数の作成](#tsp-objective) で作成した目的関数と制約条件を組み合わせて、組合せ最適化のモデルを作成します。 ```python model = route_length + (constraints2 + constraints3) * np.max(distance) print(model) ``` ```text minimize: 63.3482438588474 q_{0,0} q_{1,1} + 74.3303437365925 q_{0,0} q_{1,2} + 93.6055553906925 q_{0,0} q_{1,3} + 115.108644332213 q_{0,0} q_{1,4} + 63.3482438588474 q_{0,0} q_{4,1} + 74.3303437365925 q_{0,0} q_{4,2} + 93.6055553906925 q_{0,0} q_{4,3} + 115.108644332213 q_{0,0} q_{4,4} + 63.3482438588474 q_{0,1} q_{1,0} + 37.6563407675255 q_{0,1} q_{1,2} + 48.8364617882991 q_{0,1} q_{1,3} + 76.791926658992 q_{0,1} q_{1,4} + 63.3482438588474 q_{0,1} q_{4,0} + 37.6563407675255 q_{0,1} q_{4,2} + 48.8364617882991 q_{0,1} q_{4,3} + 76.791926658992 q_{0,1} q_{4,4} + 74.3303437365925 q_{0,2} q_{1,0} + 37.6563407675255 q_{0,2} q_{1,1} + 19.4164878389476 q_{0,2} q_{1,3} + 42.9534631898291 q_{0,2} q_{1,4} + 74.3303437365925 q_{0,2} q_{4,0} + 37.6563407675255 q_{0,2} q_{4,1} + 19.4164878389476 q_{0,2} q_{4,3} + 42.9534631898291 q_{0,2} q_{4,4} + 93.6055553906925 q_{0,3} q_{1,0} + 48.8364617882991 q_{0,3} q_{1,1} + 19.4164878389476 q_{0,3} q_{1,2} + 28.0713376952364 q_{0,3} q_{1,4} + 93.6055553906925 q_{0,3} q_{4,0} + 48.8364617882991 q_{0,3} q_{4,1} + 19.4164878389476 q_{0,3} q_{4,2} + 28.0713376952364 q_{0,3} q_{4,4} + 115.108644332213 q_{0,4} q_{1,0} + 76.791926658992 q_{0,4} q_{1,1} + 42.9534631898291 q_{0,4} q_{1,2} + 28.0713376952364 q_{0,4} q_{1,3} + 115.108644332213 q_{0,4} q_{4,0} + 76.791926658992 q_{0,4} q_{4,1} + 42.9534631898291 q_{0,4} q_{4,2} + 28.0713376952364 q_{0,4} q_{4,3} + 63.3482438588474 q_{1,0} q_{2,1} + 74.3303437365925 q_{1,0} q_{2,2} + 93.6055553906925 q_{1,0} q_{2,3} + 115.108644332213 q_{1,0} q_{2,4} + 63.3482438588474 q_{1,1} q_{2,0} + 37.6563407675255 q_{1,1} q_{2,2} + 48.8364617882991 q_{1,1} q_{2,3} + 76.791926658992 q_{1,1} q_{2,4} + 74.3303437365925 q_{1,2} q_{2,0} + 37.6563407675255 q_{1,2} q_{2,1} + 19.4164878389476 q_{1,2} q_{2,3} + 42.9534631898291 q_{1,2} q_{2,4} + 93.6055553906925 q_{1,3} q_{2,0} + 48.8364617882991 q_{1,3} q_{2,1} + 19.4164878389476 q_{1,3} q_{2,2} + 28.0713376952364 q_{1,3} q_{2,4} + 115.108644332213 q_{1,4} q_{2,0} + 76.791926658992 q_{1,4} q_{2,1} + 42.9534631898291 q_{1,4} q_{2,2} + 28.0713376952364 q_{1,4} q_{2,3} + 63.3482438588474 q_{2,0} q_{3,1} + 74.3303437365925 q_{2,0} q_{3,2} + 93.6055553906925 q_{2,0} q_{3,3} + 115.108644332213 q_{2,0} q_{3,4} + 63.3482438588474 q_{2,1} q_{3,0} + 37.6563407675255 q_{2,1} q_{3,2} + 48.8364617882991 q_{2,1} q_{3,3} + 76.791926658992 q_{2,1} q_{3,4} + 74.3303437365925 q_{2,2} q_{3,0} + 37.6563407675255 q_{2,2} q_{3,1} + 19.4164878389476 q_{2,2} q_{3,3} + 42.9534631898291 q_{2,2} q_{3,4} + 93.6055553906925 q_{2,3} q_{3,0} + 48.8364617882991 q_{2,3} q_{3,1} + 19.4164878389476 q_{2,3} q_{3,2} + 28.0713376952364 q_{2,3} q_{3,4} + 115.108644332213 q_{2,4} q_{3,0} + 76.791926658992 q_{2,4} q_{3,1} + 42.9534631898291 q_{2,4} q_{3,2} + 28.0713376952364 q_{2,4} q_{3,3} + 63.3482438588474 q_{3,0} q_{4,1} + 74.3303437365925 q_{3,0} q_{4,2} + 93.6055553906925 q_{3,0} q_{4,3} + 115.108644332213 q_{3,0} q_{4,4} + 63.3482438588474 q_{3,1} q_{4,0} + 37.6563407675255 q_{3,1} q_{4,2} + 48.8364617882991 q_{3,1} q_{4,3} + 76.791926658992 q_{3,1} q_{4,4} + 74.3303437365925 q_{3,2} q_{4,0} + 37.6563407675255 q_{3,2} q_{4,1} + 19.4164878389476 q_{3,2} q_{4,3} + 42.9534631898291 q_{3,2} q_{4,4} + 93.6055553906925 q_{3,3} q_{4,0} + 48.8364617882991 q_{3,3} q_{4,1} + 19.4164878389476 q_{3,3} q_{4,2} + 28.0713376952364 q_{3,3} q_{4,4} + 115.108644332213 q_{3,4} q_{4,0} + 76.791926658992 q_{3,4} q_{4,1} + 42.9534631898291 q_{3,4} q_{4,2} + 28.0713376952364 q_{3,4} q_{4,3} subject to: q_{0,0} + q_{0,1} + q_{0,2} + q_{0,3} + q_{0,4} == 1 (weight: 115.10864433221339), q_{1,0} + q_{1,1} + q_{1,2} + q_{1,3} + q_{1,4} == 1 (weight: 115.10864433221339), q_{2,0} + q_{2,1} + q_{2,2} + q_{2,3} + q_{2,4} == 1 (weight: 115.10864433221339), q_{3,0} + q_{3,1} + q_{3,2} + q_{3,3} + q_{3,4} == 1 (weight: 115.10864433221339), q_{4,0} + q_{4,1} + q_{4,2} + q_{4,3} + q_{4,4} == 1 (weight: 115.10864433221339), q_{0,0} + q_{1,0} + q_{2,0} + q_{3,0} + q_{4,0} == 1 (weight: 115.10864433221339), q_{0,1} + q_{1,1} + q_{2,1} + q_{3,1} + q_{4,1} == 1 (weight: 115.10864433221339), q_{0,2} + q_{1,2} + q_{2,2} + q_{3,2} + q_{4,2} == 1 (weight: 115.10864433221339), q_{0,3} + q_{1,3} + q_{2,3} + q_{3,3} + q_{4,3} == 1 (weight: 115.10864433221339), q_{0,4} + q_{1,4} + q_{2,4} + q_{3,4} + q_{4,4} == 1 (weight: 115.10864433221339) ``` 制約条件に距離行列の最大値をかけているのは、制約条件に重みをつけるためです。今回使用するソルバーである Amplify AE においては、制約条件に適切な重みを指定しないと、ソルバーが制約条件をみたそうとするよりも目的関数を小さくする方向に動いてしまい、良い解を発見することができなくなってしまいます。詳しくは [制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md) を参照してください。 ## ソルバークライアントの作成 ソルバークライアントを作成し、求解を行うためのソルバーの指定およびソルバーのパラメータの設定を行います。Amplify SDK はさまざまなソルバーに対応していますが、本サンプルコードでは Amplify AE を使用します。Amplify AE に対応するソルバークライアントクラスは [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) クラスです。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` Amplify AE の実行に必要な API トークンを設定します。 > [!TIP] > > **Tip** > > [ユーザ登録](https://amplify.fixstars.com/register)を行うと、評価・検証目的に使える API トークンを無料で入手できます。 ```python client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` ソルバーのタイムアウト値を設定します。Amplify AE のタイムアウト値の単位は ms ですが、タイムアウト値の単位はソルバーによって様々なため、[`datetime`](https://docs.python.org/3/library/datetime.html#module-datetime) モジュールを使用して統一的にタイムアウト値を指定できます。 ```python import datetime client.parameters.time_limit_ms = datetime.timedelta(seconds=1) ``` これでソルバーの設定は完了です。 ## 求解の実行 作成した組合せ最適化モデルとソルバークライアントを使用してソルバーの実行を行い、巡回セールスマン問題の解を求めます。 ```python from amplify import solve result = solve(model, client) ``` 目的関数の値、つまり巡回路の長さは以下のように表示できます。 ```python result.best.objective ``` ```text 257.5398502688045 ``` 最適解における変数の値は、NumPy の多次元配列の形式で以下のようにして取得できます。 ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [[0. 1. 0. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.] [0. 0. 1. 0. 0.] [1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.]] ``` ## 結果の確認 Amplify SDK のチュートリアルとしては以上で十分ですが、結果が正しそうであることを可視化しておきます。 ```python import matplotlib.pyplot as plt %matplotlib inline ``` まず、都市の位置を可視化します。 ```python plt.scatter(x, y) plt.show() ``` ![_images/89368003ac52ca42bc7ee8c76de61e9610e1e0a721b87a1ca653e72a5b789fd6.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/89368003ac52ca42bc7ee8c76de61e9610e1e0a721b87a1ca653e72a5b789fd6.png) 次に、巡回路を可視化します。`q_values` は置換行列 (の最後に 1 行足したもの) と見なせるので、各都市を順に並べたベクトルに `q_values` を左から掛けることにより、巡回路で訪問する順に並び替えることができます。 ```python route_x = q_values @ x # 移動ルートの x 座標を取得 route_y = q_values @ y # 移動ルートの y 座標を取得 plt.scatter(x, y) plt.plot(route_x, route_y) plt.show() ``` ![_images/93c2afb86b0214086c7cea2c143f91da676c3b5f043327091719f9d653926640.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/93c2afb86b0214086c7cea2c143f91da676c3b5f043327091719f9d653926640.png) 最短路が求められていることが分かります。 --- # 二次割当問題 二次割当問題は、以下のような問題です。 **二次割当問題** $N$ を正の整数とする。$N$ 個の工場建設候補地に $N$ 個の工場を建設することを考える。それぞれの工場は、どの建設候補地に建設されても良い。どの 2 つの工場にも、それらを行き来するトラックが走っており、その輸送量はあらかじめ分かっている。輸送量 x 走行距離の和を最小化するにはどうすればよいか。 応用として、集会の座席表を仲が良い人同士が近くなるように決定することなどが考えられます。 ## 定式化 $N$ 個の工場建設候補地を 土地 $0$, 土地 $1$, ..., 土地 $N-1$ と表記し、$N$ 個の工場を工場 $0$, 工場 $1$, ..., 工場 $N-1$ と表記します。また土地 $i$ と土地 $j$ の距離を $D_{i, j}$, 工場 $k$ と工場 $l$ の間の輸送量を $F_{k, l}$ とします。 ### 変数 $N \times N$ 個のバイナリ変数 $q$ を用意し、$q_{i, k}$ は工場 $k$ を土地 $i$ に建設するかどうかを表すことにします。 たとえば、$q$ が以下のような値をとるとき、土地 $0$ には 工場 $3$ が建設されます。 バイナリ変数テーブル | | 工場 0 | 工場 1 | 工場 2 | 工場 3 | 工場 4 | | --- | --- | --- | --- | --- | --- | | 土地 0 | 0 | 0 | 0 | 1 | 0 | | 土地 1 | 0 | 1 | 0 | 0 | 0 | | 土地 2 | 0 | 0 | 0 | 0 | 1 | | 土地 3 | 1 | 0 | 0 | 0 | 0 | | 土地 4 | 0 | 0 | 1 | 0 | 0 | ### 制約条件 バイナリ変数テーブルのそれぞれの行と列には 1 となる値がちょうど 1 個である必要があります。したがって、各行各列に one-hot 制約をかけます。逆に、これらがみたされていれば、どの土地にどの工場を建設するかが 1 通りに定まります。 ### 目的関数 目的関数は、工場と工場の間の輸送量 x 距離の総和です。これは $q$ を用いて数式で表すと $$ \sum_{q_{i, k} = 1, q_{j, l} = 1} D_{i, j} \ F_{k, l} = \sum_{i, j, k, l} q_{i, k} \ q_{j, l} \ D_{i, j} \ F_{k, l} $$ となります。 ### 数式 以上の定式化は、$N\times N$ 個のバイナリ変数 $q$ を用いて $$ \begin{align} \text{minimize} \quad &\sum_{i, j, k, l} q_{i, k} \ q_{j, l} \ D_{i, j} \ F_{k, l} \\ \text{subject to} \quad &\sum_k q_{i, k} = 1 \quad \text{for} \quad i \in \{0, 1, \ldots, N - 1\}, \\ &\sum_i q_{i, k} = 1 \quad \text{for} \quad k \in \{0, 1, \ldots, N - 1\}, \\ &q_{i, k} \in \{0, 1\} \quad \text{for} \quad i, k \in \{0, 1, \ldots, N - 1\} \end{align} $$ と書くことができます。 ## 問題の作成 Amplify SDK による定式化を行う前に、問題を作成しておきます。簡単のため工場の数 $N$ を 10 とします。 ```python import numpy as np ``` ```python N = 10 ``` 土地間の距離を表す行列 $D$ を作成します。土地はユークリッド平面上にランダムに生成します。距離行列は 2 次元の [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) として作成します。名前は `distance` とします。 ```python rng = np.random.default_rng() x = rng.integers(0, 100, size=(N,)) y = rng.integers(0, 100, size=(N,)) distance = ( (x[:, np.newaxis] - x[np.newaxis, :]) ** 2 + (y[:, np.newaxis] - y[np.newaxis, :]) ** 2 ) ** 0.5 print(distance) ``` ```text [[ 0. 74.431 17.117 34.132 20.248 37.216 36.249 91.81 64.885 15.232] [ 74.431 0. 57.315 87.71 57.009 83.217 41.593 42.107 28.601 82.97 ] [ 17.117 57.315 0. 41.183 9.22 41.11 20.616 76.837 49.406 28.018] [ 34.132 87.71 41.183 0. 34.828 7.616 60.803 116. 88.459 20.224] [ 20.248 57.009 9.22 34.828 0. 33.541 26.077 81.32 53.74 25.962] [ 37.216 83.217 41.11 7.616 33.541 0. 59.54 113.569 86.215 25.08 ] [ 36.249 41.593 20.616 60.803 26.077 59.54 0. 56.223 28.844 48.6 ] [ 91.81 42.107 76.837 116. 81.32 113.569 56.223 0. 27.586 104.809] [ 64.885 28.601 49.406 88.459 53.74 86.215 28.844 27.586 0. 77.421] [ 15.232 82.97 28.018 20.224 25.962 25.08 48.6 104.809 77.421 0. ]] ``` 工場間の輸送量を表す行列 $F$ を作成します。2 次元の対称行列をランダムに作成し、名前は `flow` とします。 ```python flow = np.zeros((N, N), dtype=int) for i in range(N): for j in range(i + 1, N): flow[i, j] = flow[j, i] = rng.integers(0, 100) print(flow) ``` ```text [[ 0 56 51 81 14 32 5 19 42 80] [56 0 75 15 93 73 48 3 72 47] [51 75 0 16 47 18 21 17 94 55] [81 15 16 0 87 7 76 11 79 95] [14 93 47 87 0 24 66 62 95 22] [32 73 18 7 24 0 63 67 91 48] [ 5 48 21 76 66 63 0 67 96 49] [19 3 17 11 62 67 67 0 10 38] [42 72 94 79 95 91 96 10 0 57] [80 47 55 95 22 48 49 38 57 0]] ``` ## Amplify SDK による定式化 Amplify SDK による定式化を行います。定式化において、どの 2 つのバイナリ変数からなる 2 次項も目的関数に現れるので、[`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスを使うと効率的な定式化を行うことができます。 ### 変数の作成 [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスを使用した定式化を行うためには、[`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) の [`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) メソッドを使用して変数を発行します。 ```python from amplify import VariableGenerator gen = VariableGenerator() matrix = gen.matrix("Binary", N, N) # coefficient matrix q = matrix.variable_array # variables q ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}& q_{0,4}& q_{0,5}& q_{0,6}& q_{0,7}& q_{0,8}& q_{0,9}\\q_{1,0}& q_{1,1}& q_{1,2}& q_{1,3}& q_{1,4}& q_{1,5}& q_{1,6}& q_{1,7}& q_{1,8}& q_{1,9}\\q_{2,0}& q_{2,1}& q_{2,2}& q_{2,3}& q_{2,4}& q_{2,5}& q_{2,6}& q_{2,7}& q_{2,8}& q_{2,9}\\q_{3,0}& q_{3,1}& q_{3,2}& q_{3,3}& q_{3,4}& q_{3,5}& q_{3,6}& q_{3,7}& q_{3,8}& q_{3,9}\\q_{4,0}& q_{4,1}& q_{4,2}& q_{4,3}& q_{4,4}& q_{4,5}& q_{4,6}& q_{4,7}& q_{4,8}& q_{4,9}\\q_{5,0}& q_{5,1}& q_{5,2}& q_{5,3}& q_{5,4}& q_{5,5}& q_{5,6}& q_{5,7}& q_{5,8}& q_{5,9}\\q_{6,0}& q_{6,1}& q_{6,2}& q_{6,3}& q_{6,4}& q_{6,5}& q_{6,6}& q_{6,7}& q_{6,8}& q_{6,9}\\q_{7,0}& q_{7,1}& q_{7,2}& q_{7,3}& q_{7,4}& q_{7,5}& q_{7,6}& q_{7,7}& q_{7,8}& q_{7,9}\\q_{8,0}& q_{8,1}& q_{8,2}& q_{8,3}& q_{8,4}& q_{8,5}& q_{8,6}& q_{8,7}& q_{8,8}& q_{8,9}\\q_{9,0}& q_{9,1}& q_{9,2}& q_{9,3}& q_{9,4}& q_{9,5}& q_{9,6}& q_{9,7}& q_{9,8}& q_{9,9}\end{matrix}\right]\end{aligned} $$ ### 目的関数の作成 上で作成した `matrix` は [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスのインスタンスであり、 * [`quadratic`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) * [`linear`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear) * [`constant`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) の 3 種類のプロパティを持ちます。 [`quadratic`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) は 2 次の項の係数を表す [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) で、その [`shape`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape) は今回は `(N, N, N, N)` となっています。`quadratic[i, k, j, l]` は `q[i, k] * q[j, l]` の係数に対応します。つまり [`quadratic`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) には `quadratic[i, k, j, l] = distance[i, j] * flow[k, l]` となるように 4 次元 NumPy 配列を設定する必要があります。 [`linear`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear) と [`constant`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) はそれぞれ線形項の係数と定数項を表しますが、今回使用する目的関数には 2 次の項しか含まれないため、設定しません。 ```python np.einsum("ij,kl->ikjl", distance, flow, out=matrix.quadratic) ``` ### 制約条件の作成 [変数の作成](#creating-variables) で作成した変数配列 `q` の各行各列に one-hot 制約をかけます。 ```python from amplify import one_hot constraints = one_hot(q, axis=1) + one_hot(q, axis=0) ``` ### 組合せ最適化モデルの作成 目的関数と制約条件を組み合わせて、モデルを作成します。 ```python penalty_weight = np.max(distance) * np.max(flow) * (N - 1) model = matrix + penalty_weight * constraints ``` 制約条件に `penalty_weight` をかけているのは、制約条件に重みをつけるためです。今回使用するソルバーである Amplify AE においては、制約条件に適切な重みを指定しないと、ソルバーが制約条件をみたそうとするよりも目的関数を小さくする方向に動いてしまい、良い解を発見することができなくなってしまいます。詳しくは [制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md) を参照してください。 ## ソルバークライアントの作成 Amplify AE を用いて組合せ最適化を実行するために、ソルバークライアントを作成します。Amplify AE に対応するソルバークライアントクラスは [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) クラスです。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` Amplify AE の実行に必要な API トークンを設定します。 > [!TIP] > > **Tip** > > [ユーザ登録](https://amplify.fixstars.com/register)を行うと、評価・検証目的に使える API トークンを無料で入手できます。 ```python client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` ソルバーのタイムアウト値を設定します。 ```python import datetime client.parameters.time_limit_ms = datetime.timedelta(seconds=1) ``` ## 求解の実行 作成した組合せ最適化モデルとソルバークライアントを使用してソルバーの実行を行い、二次計画問題の解を求めます。 ```python from amplify import solve result = solve(model, client) ``` 目的関数の値は以下のように表示できます。 ```python result.best.objective ``` ```text 190260.64186051858 ``` 最適解における変数の値は、NumPy の多次元配列の形式で以下のようにして取得できます。 ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]] ``` ## 結果の確認 matplotlib を用いて結果を可視化します。 ```python import itertools import matplotlib.pyplot as plt ``` ```python plt.scatter(x, y) factory_indices = (q_values @ np.arange(N)).astype(int) for i, j in itertools.combinations(range(N), 2): plt.plot( [x[i], x[j]], [y[i], y[j]], c="b", alpha=flow[factory_indices[i], factory_indices[j]] / 100, ) ``` ![_images/3649990bfd68fb91a3bc845f04cb38b1a56c6d8d64f05f8a0fab7ee84196930f.png](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/3649990bfd68fb91a3bc845f04cb38b1a56c6d8d64f05f8a0fab7ee84196930f.png) --- # 型ヒントサポート ![_images/type_hints.gif](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/type_hints.gif) Amplify SDK は全ての関数、メソッド、アトリビュートに型アノテーションを定義しています。これにより、Visual Studio Code 等の IDE や Google Colaboratory において、コードの補完や型チェックによるコードのエラーを検出することができます。 > [!TIP] > > **ヒント** > > Visual Studio Code を使用している場合は [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) 拡張機能をインストールし、次の設定を追加することでコード補完と型チェックが有効になります。 > > `settings.json` > > ```json > { > "python.languageServer": "Pylance", > "python.analysis.typeCheckingMode": "basic", > } > ``` > [!TIP] > > **ヒント** > > 呼び出すメソッドや関数によっては必ずしも型や配列の次元が確定できないことがあります。 > > 例えば [`amplify.einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) 関数は、引数の値によって [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) または [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) を返すため、型を確定できず型チェッカーによるエラーや警告が発生することがあります。このような場合は、次のように型を明示的に指定することでエラーを回避することができます。 > > ```python > from amplify import Poly, einsum > > # 引数 "ij,ki,kj->" により Poly (スカラー) を返すことが期待されるが型チェッカーには判別できない > objective: Poly = einsum("ij,ki,kj->", d, q1, q2) # type: ignore > ``` --- # プロキシサーバの設定 インターネット接続を行う際にプロキシサーバを経由する場合、Amplify SDK からクラウドサービスを実行するプログラムコード上でプロキシサーバを設定する必要があります。 > [!NOTE] > > **注釈** > > インターネット接続を行う際にプロキシサーバを経由しない場合は、このページを読む必要はありません。 ## Amplify SDK をインストールする pip コマンドを使用する際にプロキシを指定する必要があります。 ```bash $ python3 -m pip install --proxy http://user:password@xxx.xxx.xxx.xxx:xxxx -U amplify ``` ## Amplify SDK からソルバーを実行する 使用するソルバーがクラウドサービスとして提供されている場合、ソルバークライアントにプロキシを設定する必要があります。 > [!NOTE] > > **注釈** > > クラウドサービスとして提供されるソルバーは、[こちら](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md#solver-clients)のページのソルバーの一覧で ☁️ Cloud タグがついているソルバーです。💻 Local タグがついているソルバーの実行にはインターネットアクセスを伴わないため、プロキシの設定は必要ありません。 ソルバークライアントの構築時に `proxy` キーワード引数にプロキシを指定します。以下の例ではソルバークライアントとして [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を使用していますが、他のソルバークライアントを使用する場合も同様です。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient(proxy="http://user:password@xxx.xxx.xxx.xxx:xxxx") ``` プロキシはあとから指定することもできます。 ```python from amplify import AmplifyAEClient client = AmplifyAEClient() client.proxy = "http://user:password@xxx.xxx.xxx.xxx:xxxx" ``` --- # 数式の整形表示 Jupyter Notebook, Visual Studio Code など、LaTeX による数式表示に対応した IPython のフロントエンド環境では Amplify SDK の数式は自動的に LaTeX で描画されます。 多項式、多項式配列、係数行列、制約条件、モデルは次のように数式として表示されます。 ## 変数配列 ```python import amplify gen = amplify.VariableGenerator() q = gen.array("Binary", shape=(4, 4)) q ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0}& q_{0,1}& q_{0,2}& q_{0,3}\\q_{1,0}& q_{1,1}& q_{1,2}& q_{1,3}\\q_{2,0}& q_{2,1}& q_{2,2}& q_{2,3}\\q_{3,0}& q_{3,1}& q_{3,2}& q_{3,3}\end{matrix}\right]\end{aligned} $$ ## 多項式 ```python p = 2 * (q[0] * q[1]).sum() p ``` $$ \displaystyle 2 q_{0,0} q_{1,0} + 2 q_{0,1} q_{1,1} + 2 q_{0,2} q_{1,2} + 2 q_{0,3} q_{1,3} $$ ## 多項式配列 ```python q[0:2] + q[2:] ``` $$ \displaystyle \begin{aligned}&\left[\begin{matrix}q_{0,0} + q_{2,0}& q_{0,1} + q_{2,1}& q_{0,2} + q_{2,2}& q_{0,3} + q_{2,3}\\q_{1,0} + q_{3,0}& q_{1,1} + q_{3,1}& q_{1,2} + q_{3,2}& q_{1,3} + q_{3,3}\end{matrix}\right]\end{aligned} $$ ## 制約条件 ```python c1 = amplify.one_hot(q, axis=1) c1 ``` $$ \displaystyle \begin{array}{l}q_{0,0} + q_{0,1} + q_{0,2} + q_{0,3} = 1\ (\text{weight}\colon\ 1)\\q_{1,0} + q_{1,1} + q_{1,2} + q_{1,3} = 1\ (\text{weight}\colon\ 1)\\q_{2,0} + q_{2,1} + q_{2,2} + q_{2,3} = 1\ (\text{weight}\colon\ 1)\\q_{3,0} + q_{3,1} + q_{3,2} + q_{3,3} = 1\ (\text{weight}\colon\ 1)\end{array} $$ ## 係数行列 ```python import numpy as np m = gen.matrix("Binary", 4) m.quadratic = np.array([[1, 2, 3, 4], [0, 5, 6, 7], [0, 0, 8, 9], [0, 0, 0, 10]]) m.linear = np.array([1, 2, 3, 4]) c2 = amplify.one_hot(m.variable_array) m ``` $$ \displaystyle \begin{array}{l}x^\top Qx + p^\top x + c\\\text{where:}\\\quad\begin{aligned}x=&\left[\begin{matrix}q'_0& q'_1& q'_2& q'_3\end{matrix}\right],\\Q=&\left[\begin{matrix} 1.& 2.& 3.& 4.\\ 0.& 5.& 6.& 7.\\ 0.& 0.& 8.& 9.\\ 0.& 0.& 0.& 10.\end{matrix}\right],\\p=&\left[\begin{matrix} 1.& 2.& 3.& 4.\end{matrix}\right],\\c=&\ 0\end{aligned}\end{array} $$ ## モデル ```python model = p + c1 model ``` $$ \displaystyle \begin{array}{l}\text{minimize:}\\\quad 2 q_{0,0} q_{1,0} + 2 q_{0,1} q_{1,1} + 2 q_{0,2} q_{1,2} + 2 q_{0,3} q_{1,3}\\\text{subject to:}\\\quad \begin{array}{l}q_{0,0} + q_{0,1} + q_{0,2} + q_{0,3} = 1\ (\text{weight}\colon\ 1)\\q_{1,0} + q_{1,1} + q_{1,2} + q_{1,3} = 1\ (\text{weight}\colon\ 1)\\q_{2,0} + q_{2,1} + q_{2,2} + q_{2,3} = 1\ (\text{weight}\colon\ 1)\\q_{3,0} + q_{3,1} + q_{3,2} + q_{3,3} = 1\ (\text{weight}\colon\ 1)\end{array}\end{array} $$ ```python model = m + c2 model ``` $$ \displaystyle \begin{array}{l}\text{minimize:}\\\quad \begin{array}{l}x^\top Qx + p^\top x + c\\\text{where:}\\\quad\begin{aligned}x=&\left[\begin{matrix}q'_0& q'_1& q'_2& q'_3\end{matrix}\right],\\Q=&\left[\begin{matrix} 1.& 2.& 3.& 4.\\ 0.& 5.& 6.& 7.\\ 0.& 0.& 8.& 9.\\ 0.& 0.& 0.& 10.\end{matrix}\right],\\p=&\left[\begin{matrix} 1.& 2.& 3.& 4.\end{matrix}\right],\\c=&\ 0\end{aligned}\end{array}\\\text{subject to:}\\\quad \begin{array}{l}q'_0 + q'_1 + q'_2 + q'_3 = 1\ (\text{weight}\colon\ 1)\end{array}\end{array} $$ --- # 旧バージョンからの移行 Amplify SDK v1 は v0 とは一部の互換性が失われています。これまで旧バージョンを使っていた場合に、今後も動作し続けるようにコードを維持するための方法について説明します。 ## Amplify SDK v0 を使い続ける 現在のコードの動作環境を全く変更せず維持するために、Amplify SDK v0 を使い続けることができます。Amplify SDK モジュールのインストール時に次のようにしてバージョンに制限をかけることで実現できます。 ```bash $ python3 -m pip install -U 'amplify<1.0.0' ``` 追加のパッケージを含める場合は、次のようにします。 ```bash $ python3 -m pip install -U 'amplify[extra]<1.0.0' ``` Amplify SDK v0 のドキュメントは次の URL で参照できます。 > [!IMPORTANT] > > **重要** > > Amplify SDK v0 は今後も継続的に動作することは保証されません。クリティカルなバグ修正以外の機能追加や、対応ソルバーのアップデートなどは行われません。 > > また、Python の新バージョンのリリースやソルバーの仕様変更など、周辺環境の変化によっても動作しなくなる可能性があるため注意してください。 ## Amplify SDK v1 に移行する 次のような方針で v0 で書かれたコードを v1 に移行することができます。 ### 決定変数の作成 [`BinarySymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator) と [`IsingSymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) は整数変数、実数変数の追加に伴い [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) に置き換えられました。変数の種類は [`array()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array), [`scalar()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar), [`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) メソッドの引数で指定します。 従来の書き方: ```python from amplify import BinarySymbolGenerator, IsingSymbolGenerator gen = BinarySymbolGenerator() q = gen.array(10) gen = IsingSymbolGenerator() s = gen.array(shape=(4, 4)) ``` 新しい書き方: ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", 10) s = gen.array("Ising", shape=(4, 4)) n = gen.array("Integer", shape=(3, 3), bounds=(0, 10)) x = gen.array("Real", shape=(2, 4), bounds=(-0.5, 0.5)) ``` ### 目的関数の作成 上記のように変数を作成すれば、多項式の構築は以前のバージョンと同様に行えます。ただし、[辞書を用いた構築](https://amplify.fixstars.com/ja/docs/amplify/v0/polynomial.html#id2) は廃止されたため、今後は利用出来ません。 行列形式の目的関数の構築は、直接 Matrix クラスを作成するのではなく、[`matrix()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) メソッドを用いて作成するように変更されました。また、[`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) クラスは係数の二次、一次、定数の項と含まれる変数を内包するようになりました。詳しくは [係数行列による目的関数の作成](https://amplify.fixstars.com/ja/docs/amplify/v1/matrix.md) を参照してください。 従来の書き方 (現在は動作しません): ```python from amplify import BinaryMatrix m = BinaryMatrix(3) m[0, 0] = -2 m[0, 1] = 1 m[1, 2] = -1 m[2, 2] = 1 ``` 新しい書き方: ```python from amplify import VariableGenerator gen = VariableGenerator() m = gen.matrix("Binary", shape=3) # 二次の項を取得する m.quadratic[0, 0] = -2 m.quadratic[0, 1] = 1 m.quadratic[1, 2] = -1 m.quadratic[2, 2] = 1 # 係数行列に対応する変数を取得する q = m.variable_array ``` ### 制約条件の作成 制約条件を作成するための関数やクラスは、`amplify.constraint` サブモジュールから `amplify` モジュールに移動されました。また、`penalty` 関数は廃止され、ユーザ自身でペナルティ関数を定義する場合は [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) クラスの構築で行うようになりました。詳しくは [ペナルティ関数の指定](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#specify-penalty) を参照してください。その他のヘルパー関数についてはモジュールの変更のみで全て利用可能です。 従来の書き方: ```python from amplify.constraint import equal_to, penalty c = equal_to(q.sum(), 1) p = penalty(q[0] * q[1]) ``` 新しい書き方: ```python from amplify import Constraint, equal_to c = equal_to(q.sum(), 1) p = Constraint(q[0] + q[1], le=1, penalty=q[0] * q[1]) ``` ### モデルの作成 以前と同様に、Amplify SDK v1 でのモデルクラス [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) を明示的に構築するか、あるいは目的関数と制約条件の和を取ることで、モデルを作成することができます。 以前のバージョンでは [`BinaryQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) と [`IsingQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) がモデルを表すクラスとして、変数の種類に応じた二次のモデルへの変換も担っていました。しかし Amplify SDK v1 では、モデルは様々な変数の種類や次数を扱えるソルバーに対応するため、モデル自身に変数の種類や次数への縛りを持たなくなりました。そのため、モデル構築時にはモデル変換処理は行われず、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数に実行したいソルバーに対応したクライアントを渡すことで、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の内部でソルバーに最適な変換処理が行われるようになりました。 従来の書き方: ```python from amplify import BinaryQuadraticModel model = BinaryQuadraticModel(q.sum() ** 2, c) ``` 新しい書き方: ```python from amplify import Model model = Model(q.sum() ** 2, c) ``` 従来、二次のモデルへの変換結果は [`BinaryQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) と [`IsingQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) のアトリビュートから取得可能でしたが、Amplify SDK v1 では [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の返り値である [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのアトリビュートから取得するか、あるいは明示的にモデル変換メソッドを呼び出して確認できるようになりました。詳しくは 「[変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md)」 を参照してください。 ### ソルバーの実行 ソルバークライアントは `amplify.client` サブモジュールから `amplify` モジュールに移動されました。また、[`Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) クラスは廃止され、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数にモデルとソルバークライアントを渡すことで実行されるようになりました。モデル変換やグラフ埋め込みに関するパラメータは、モデルやソルバークラスのアトリビュートではなく、全て [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数のパラメータとして与えるように変更されました。 [`FixstarsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) は Amplify SDK v1 でも引き続き提供されますが、新しいバージョンの Amplify AE ソルバーに対応した [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) を使うことが推奨されます。詳しくは 「[Fixstars Amplify](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md)」 を参照してください。 従来の書き方: ```python from amplify import Solver, QuadratizationMethod from amplify.client import FixstarsClient client = FixstarsClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.timeout = 1000 model = BinaryQuadraticModel(q.sum() **2, c, method=QuadratizationMethod.SUBSTITUTION) solver = Solver(client) solver.filter_solution = False result = solver.solve(model) ``` 新しい書き方: ```python from amplify import AmplifyAEClient, solve client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = 1000 model = Model(q.sum() **2, c) result = solve(model, client, quadratization_method="Substitute", filter_solution=False) ``` また、中間モデル (旧論理モデル) の解や、グラフ埋め込みの結果なども [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の返り値である [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのアトリビュートに設定されるようになりました。詳しくは 「[変数変換と次数下げ](https://amplify.fixstars.com/ja/docs/amplify/v1/intermediate.md)」 と 「[グラフ埋め込み](https://amplify.fixstars.com/ja/docs/amplify/v1/graph.md)」 を参照してください。 ## 後方互換 API を使う Amplify SDK v1 でも v0 で書かれたコードが動作するように、従来の API を v1 の後方互換 API として提供しています。後方互換 API は 100% の互換性を保証するものではありませんが、よく使われる機能については互換性を維持しているため、多くの場合はそのままで動作するはずです。 > [!IMPORTANT] > > **重要** > > 後方互換 API は将来のバージョンで削除される可能性があるため、早めに v1 API に移行することを推奨します。 > > このことは実行時に警告 ([`DeprecationWarning`](https://docs.python.org/3/library/exceptions.html#DeprecationWarning)) として送出されます。 次のような方針で後方互換 API を提供しています。 ### クラス | Amplify SDK v0 (リンク先は v1 互換 API) | 後方互換 API 詳細 | | --- | --- | | [`BinaryPoly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md#amplify.BinaryPoly), [`IsingPoly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPoly.md#amplify.IsingPoly) | [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) のエイリアスとしてサブクラス化されていますが、それぞれバイナリ変数、イジング変数には制限されません。また、コンストラクタや一部のメソッドに互換性がありません。 | | [`BinaryPolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md#amplify.BinaryPolyArray), [`IsingPolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md#amplify.IsingPolyArray) | [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) のエイリアスとしてサブクラス化されていますが、それぞれバイナリ変数、イジング変数には制限されません。また、コンストラクタや一部のメソッドに互換性がありません。 | | `BinaryIntPoly`, `IsingIntPoly`, `BinaryIntPolyArray`, `IsingIntPolyArray` | 提供されません。 | | [`BinarySymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator), [`IsingSymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | それぞれ バイナリ変数、イジング変数専用の [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) として機能します。 | | `BinaryIntSymbolGenerator`, `IsingIntSymbolGenerator` | 提供されません。 | | [`BinaryMatrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md#amplify.BinaryMatrix), [`IsingMatrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md#amplify.IsingMatrix) | [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) のエイリアスとしてサブクラス化されていますが、それぞれバイナリ変数、イジング変数には制限されません。また、インターフェースに互換性はありません。 | | `BinaryIntMatrix`, `IsingIntMatrix` | 提供されません。 | | [`BinaryQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel), [`IsingQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) | これらは明示的にコンストラクタを呼び出さない限り作成されません。それぞれ バイナリ変数とイジング変数の二次の中間モデル (旧論理モデル) を取得することのできる v0 と互換性のあるモデルとして機能します。しかし、新しい [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数には渡せず、後方互換用の [`Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) クラス専用です。 | | `BinaryIntQuadraticModel`, `IsingIntQuadraticModel` | 提供されません。 | | [`Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver), [`SolverResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverResult.md#amplify.SolverResult), [`SolverSolution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverSolution.md#amplify.SolverSolution) | [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数のラッパークラスとして v0 と同様のインターフェースを提供します。メソッドやプロパティの返却値は対応する v1 のクラスに変更されています。 | ### 関数 | Amplify SDK v0 (リンク先は v1 互換 API) | 後方互換 API 詳細 | | --- | --- | | `replace_all()` | 提供されません | | [`sum_poly()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum_poly.md#amplify.sum_poly) | [`sum`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) のエイリアスとします。 | | `pair_sum()` | 提供されません | | `product()` | 提供されません | | `intersection()` | 提供されません | | `union()` | 提供されません | | `symmetric_difference()` | 提供されません | | [`SymbolGenerator()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md#amplify.SymbolGenerator) | [`VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) のエイリアスとします。 | | `gen_symbols` | 提供されません。 | | [`decode_solution()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.decode_solution.md#amplify.decode_solution) | [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) の関数版として機能します。 | | `convert_to_matrix` | 提供されません。 | ### 名前空間 | Amplify SDK v0 (リンク先は v1 互換 API) | 後方互換 API 詳細 | | --- | --- | | `amplify.constraint` | 互換性のために提供されます。 | | `amplify.client` | 互換性のために提供されます。 | | `amplify.client.ocean` | 互換性のために提供されます。 | --- # 定式化ベンチマーク Python のライブラリとして提供される数理最適化モデルについて、Amplify SDK との比較として定式化のベンチマークを取得しています。ここでは QUBO ソルバーの実行を前提として、[巡回セールスマン問題の定式化](https://amplify.fixstars.com/ja/docs/amplify/v1/tsp.md) を例にモデルの作成し QUBO として出力するまでの実行時間を計測しました。 ただし、Amplify SDK を含む各ライブラリはそれぞれのカバーする機能が定式化の方法によっても異なります。ここでは次のように定式化を行い、それぞれの機能と方針についてまとめました。 | - | [Amplify](https://amplify.fixstars.com/docs/amplify/v1/) | [PyQUBO](https://pyqubo.readthedocs.io/en/latest/) | [dimod](https://docs.ocean.dwavesys.com/en/stable/docs_dimod/) BQM (index) | [dimod](https://docs.ocean.dwavesys.com/en/stable/docs_dimod/) BQM (symbol) | [dimod](https://docs.ocean.dwavesys.com/en/stable/docs_dimod/) CQM\* | | --- | --- | --- | --- | --- | --- | | 記号演算 | ✅ | ✅ | ❌ | ✅ | ✅ | | 目的関数 | ✅ | ✅ | ✅ | ✅ | ✅ | | 制約条件 | ✅ | ✅\*\* | ❌\*\*\* | ❌\*\*\* | ✅\* | | 高次多項式 | ✅ | ✅ | ❌ | ❌ | ❌ | | 係数行列 | ✅ | ❌ | ❌ | ❌ | ❌ | | 変数タイプ | B/S/I/R | B/S | B/S | B/S | B/S/I/R | | 対応マシン | さまざま | ユーザ次第 | D-Wave のみ | D-Wave のみ | D-Wave のみ | B: Binary, S: Ising Spin, I: Integer, R: Real \*: QUBO 出力 (制約条件のペナルティ関数化) ができないためモデル作成のみ計測 \*\*: ペナルティ関数を定義する必要あり \*\*\*: ペナルティ関数を目的関数に足すことで表現 Amplify ```python import amplify def tsp_for_amplify(ncity: int, distances: np.ndarray, dmax: float): q = amplify.VariableGenerator().array("Binary", ncity + 1, ncity) q[-1, :] = q[0, :] # 目的関数 objective: amplify.Poly = amplify.einsum( "ij,ki,kj->", distances, q[:-1], q[1:] ) # 制約条件 constraints: amplify.ConstraintList = amplify.one_hot( q[:-1], axis=1 ) + amplify.one_hot(q[:-1], axis=0) return objective + dmax * constraints class BenchTspAmplify: def create_model(self, ncity: int, distances: np.ndarray, dmax: float): self.model = tsp_for_amplify(ncity, distances, dmax) def to_qubo(self): self.model.to_unconstrained_poly() ``` PyQUBO ```python import pyqubo def tsp_for_pyqubo(ncity: int, distances: np.ndarray, dmax: float): # from https://github.com/recruit-communications/pyqubo/blob/master/notebooks/TSP.ipynb # NOTE: https://github.com/recruit-communications/pyqubo/blob/master/benchmark/benchmark.py # is not valid for TSP x = pyqubo.Array.create("c", (ncity, ncity), "BINARY") # Constraint not to visit more than two cities at the same time. time_const = 0.0 for i in range(ncity): # If you wrap the hamiltonian by Const(...), this part is recognized as constraint time_const += pyqubo.Constraint( (sum(x[i, j] for j in range(ncity)) - 1) ** 2, label=f"time{i}" ) # Constraint not to visit the same city more than twice. city_const = 0.0 for j in range(ncity): city_const += pyqubo.Constraint( (sum(x[i, j] for i in range(ncity)) - 1) ** 2, label=f"city{j}" ) # distance of route feed_dict = {} distance = 0.0 for i in range(ncity): for j in range(ncity): for k in range(ncity): # we set the constant distance distance += distances[i, j] * x[k, i] * x[(k + 1) % ncity, j] # Construct hamiltonian A = pyqubo.Placeholder("A") H = distance + A * (time_const + city_const) feed_dict["A"] = dmax # Compile model return H.compile(), feed_dict class BenchTspPyQubo: def create_model(self, ncity: int, distances: np.ndarray, dmax: float): self.model, self._feed_dict = tsp_for_pyqubo(ncity, distances, dmax) def to_qubo(self): self.model.to_qubo(index_label=False, feed_dict=self._feed_dict) ``` dimod BQM (index) ```python import dimod def tsp_for_dimod_bqm(ncity: int, distances: np.ndarray, dmax: float): bqm = dimod.BinaryQuadraticModel(ncity * ncity, dimod.BINARY) # 目的関数 for n in range(ncity): for i in range(ncity): for j in range(ncity): bqm.add_quadratic( n * ncity + i, ((n + 1) % ncity) * ncity + j, distances[i, j], ) # 行に対する制約 for n in range(ncity): left = [(n * ncity + i, 1) for i in range(ncity)] bqm.add_linear_equality_constraint(left, dmax, -1) # 列に対する制約 for i in range(ncity): left = [(n * ncity + i, 1) for n in range(ncity)] bqm.add_linear_equality_constraint(left, dmax, -1) return bqm class BenchTspDimodBQM: def create_model(self, ncity: int, distances: np.ndarray, dmax: float): self.model = tsp_for_dimod_bqm(ncity, distances, dmax) def to_qubo(self): self.model.to_qubo() ``` dimod BQM (symbol math) ```python import dimod def tsp_for_dimod_bqm_sym( ncity: int, distances: np.ndarray, dmax: float ) -> dimod.BinaryQuadraticModel: bqm = dimod.BinaryQuadraticModel(ncity * ncity, dimod.BINARY) vars = [ [dimod.Binary(f"{n},{i}") for i in range(ncity)] for n in range(ncity) ] # 目的関数 for n in range(ncity): for i in range(ncity): for j in range(ncity): bqm += distances[i, j] * vars[n][i] * vars[(n + 1) % ncity][j] # 行に対する制約 for n in range(ncity): bqm += dmax * (sum(vars[n][i] for i in range(ncity)) - 1) ** 2 # 列に対する制約 for i in range(ncity): bqm += dmax * (sum(vars[n][i] for n in range(ncity)) - 1) ** 2 return bqm # type: ignore class BenchTspDimodBQMSym: def create_model(self, ncity: int, distances: np.ndarray, dmax: float): self.model = tsp_for_dimod_bqm_sym(ncity, distances, dmax) def to_qubo(self): self.model.to_qubo() ``` dimod CQM ```python import dimod def tsp_for_dimod_cqm(ncity: int, distances: np.ndarray, dmax: float): cqm = dimod.ConstrainedQuadraticModel() vars = [ [dimod.Binary(f"{n},{i}") for i in range(ncity)] for n in range(ncity) ] # 目的関数 obj = 0.0 for n in range(ncity): for i in range(ncity): for j in range(ncity): obj += distances[i, j] * vars[n][i] * vars[(n + 1) % ncity][j] cqm.set_objective(obj) # 行に対する制約 for n in range(ncity): cqm.add_constraint(sum(vars[n]) == 1) # 列に対する制約 for i in range(ncity): cqm.add_constraint(sum(vars[n][i] for n in range(ncity)) == 1) return cqm class BenchTspDimodCQM: def create_model(self, ncity: int, distances: np.ndarray, dmax: float): self.model = tsp_for_dimod_cqm(ncity, distances, dmax) def to_qubo(self): pass ``` ベンチマークコード ```python import time def make_distance(ncity: int) -> tuple[np.ndarray, float]: rng = np.random.default_rng(12345) x = rng.random(ncity) y = rng.random(ncity) distances = ( (x[:, np.newaxis] - x[np.newaxis, :]) ** 2 + (y[:, np.newaxis] - y[np.newaxis, :]) ** 2 ) ** 0.5 dmax: float = np.max(distances) # type: ignore return distances, dmax for ncity in [32, 100, 317]: distances, dmax = make_distance(ncity) for bench_class in [ BenchTspAmplify, BenchTspPyQubo, BenchTspDimodBQM, BenchTspDimodBQMSym, BenchTspDimodCQM, ]: bench = bench_class() start = time.time() bench.create_model(ncity, distances, dmax) end = time.time() t1 = end - start start = time.time() bench.to_qubo() end = time.time() t2 = end - start print(f"{t1} {t2}") ``` **ベンチマーク環境** **CPU** IntelR CoreTM i9-12900K (E-Cores disabled) **OS** Ubuntu 22.04 **Python 3.11** * amplify 1.0.0 * pyqubo 1.4.0 * dimod 0.12.14 ## ベンチマーク結果 *対話的なグラフです。HTML 版でのみ表示されます。* ### 32 都市 (1,024 バイナリ変数) | 定式化 | モデル作成時間 | QUBO 作成時間 | 合計時間 | | --- | --- | --- | --- | | [Amplify](#amplify-tsp-bench) | **1.309 ms** | **0.998 ms** | **2.307 ms** 🏆 | | [PyQUBO](#pyqubo-tsp-bench) | 266.8 ms | 24.63 ms | 291.5 ms (x126.3) | | [dimod BQM (index)](#dimod-bqm-idx-tsp-bench) | 22.53 ms | 41.58 ms | 64.12 ms (x27.8) | | [dimod BQM (symbol)](#dimod-bqm-sym-tsp-bench) | 1028 ms | 58.48 ms | 1087 ms (x471.2) | | [dimod CQM](#dimod-cqm-tsp-bench) | 895.9 ms | N/A ms | 895.9 ms (x388.4) | ### 100 都市 (10,000 バイナリ変数) | 定式化 | モデル作成時間 | QUBO 作成時間 | 合計時間 | | --- | --- | --- | --- | | [Amplify](#amplify-tsp-bench) | **0.063 s** | **0.077 s** | **0.140 s** 🏆 | | [PyQUBO](#pyqubo-tsp-bench) | 8.519 s | 1.360 s | 9.879 s (x70.7) | | [dimod BQM (index)](#dimod-bqm-idx-tsp-bench) | 0.706 s | 1.419 s | 2.126 s (x15.2) | | [dimod BQM (symbol)](#dimod-bqm-sym-tsp-bench) | 30.83 s | 1.935 s | 32.77 s (x234.6) | | [dimod CQM](#dimod-cqm-tsp-bench) | 26.93 s | N/A | 26.93 s (x192.8) | ### 317 都市 (100,489 バイナリ変数) | 定式化 | モデル作成時間 | QUBO 作成時間 | 合計時間 | | --- | --- | --- | --- | | [Amplify](#amplify-tsp-bench) | **2.992 s** | **2.946 s** | **5.938 s** 🏆 | | [PyQUBO](#pyqubo-tsp-bench) | 279.7 s | 69.23 s | 349.0 s (x58.8) | | [dimod BQM (index)](#dimod-bqm-idx-tsp-bench) | 31.05 s | 52.05 s | 83.10 s (x14.0) | | [dimod BQM (symbol)](#dimod-bqm-sym-tsp-bench) | 991.5 s | 70.83 s | 1062 s (x178.9) | | [dimod CQM](#dimod-cqm-tsp-bench) | 855.3 s | N/A | 855.3 s (x144.0) | --- # Fixstars Amplify AE Fixstars Amplify Annealing Engine (以下 Amplify AE) は Fixstars Amplify 社の提供するソルバーです。シミュレーテッドアニーリングをベースとしたヒューリスティックアルゴリズムが GPU 上に実装されており、GPU の持つ並列計算技術を活用して解を高速・高精度に探索します。 目的関数と制約条件から構成されるバイナリ変数の最適化問題を扱えるため、実用的な問題に対応できます。Amplify SDK と組み合わせれば、さらに幅広く一般的な最適化問題の求解に活用できます。また、量子アニーリングやイジングマシンの研究者向けに、理想的に動作する高精度な QUBOソルバーとしての利用も可能です。 Amplify SDK からの利用については [クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 ## Amplify AE の特長 Amplify AE は、アニーリング法 (焼きなまし法) をベースとしたヒューリスティックアルゴリズムを用いて、入力された最適化問題の解を探索するソルバーです。特に独自性の高い点として、AI 半導体として知られる GPU の並列計算技術を活用することがあげられます。求解の高度な並列化により GPU のポテンシャル性能を活かし、高速かつ高精度に目的関数の最小化を行います。 クラウド版の Amplify AE の機能仕様は以下の通りです。 | | | | --- | --- | | 変数タイプ | バイナリ | | 最大問題サイズ (全結合) | 8,192 変数 (Basic) / 65,536 変数 (Standard) / 131,072 変数 (Premium) | | 最大次数 | 4 次 (目的関数) / 4 次 (制約条件) | | 制約条件タイプ | 等式・不等式 (Constraint モード) / ペナルティ関数 (PUBO モード) | | 精度 | 入力: 64 bit 実数 (入力) / 計算: 64 bit 実数 / データ: 32bit 実数 | | 最大実行時間 | 10秒 (Basic) / 10分以上 (Standard, Premium) | | 対応 GPU | NVIDIA Volta (Basic, Standard) / NVIDIA Ampere (Premium) / NVIDIA Hopper (Premium) | | マルチ GPU 対応 | 1 基 (Basic) / 最大 8 基 (Standard, Premium) | | エンドポイントURL | https://optigan.fixstars.com | Basic, Standard, Premium: Amplify の契約プラン (Basic は無償) Enterprise プランでは最大実行時間は無制限でユーザ設定が可能です。また、問題サイズの上限は GPU に搭載されたメモリ量に依存し 131,072 変数を超えて対応します。 対応する GPU は NVIDIA Volta / Ampere / Hopper と最新の NVIDIA Blackwell (準備中) です。これらの GPU を用いた Amplify AE の利用は、Fixstars Amplify 社のクラウドサービスを通じて提供されるほか、オンプレミス環境でも提供されます。 > [!TIP] > > **Changed in version 1.0.0** > > *Fixstars Amplify AE* はバージョン 1.0.0 で大きなアップデートを行い、高次多項式対応・制約条件対応・求解性能の向上が行われました。旧バージョンでは 2次多項式の目的関数とペナルティ関数のみに対応していましたが、新たに 4 次多項式の目的関数と等式・不等式制約条件に対応し、ペナルティ関数の重みパラメータの自動調整機能の性能も向上しました。 > これにより、より幅広い用途において複雑な最適化問題の求解が可能になりました。移行期間を設けているため、以前のバージョンもしばらくは引き続き利用可能です。 ### 入力の仕様 実数係数のバイナリ変数の多項式を入力として受け付けます。目的関数と制約条件 (あるいはペナルティ関数) で構成された問題に対応し、双方共に 4次までの多項式の指定が可能です。バイナリ変数の最大数は 131,072 まで対応していますが、これは全結合モデル (変数が全ての変数と結合されているモデル) においての最大値です。疎結合形式での入力が可能なので、結合数が少ない問題ではより大きな問題サイズの求解が可能です。制約条件は等式・不等式制約の両方に対応しており (Constraint モード)、後述する PUBO モードではペナルティ関数を用いた制約条件の設定も可能です。 求解要求は JSON 形式で WEB API へのリクエストとして行います。API 仕様については [API Reference](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/api_reference.md) を参照してください。 ### 求解モード Amplify AE は2つの求解モードを備えています。1つめはデフォルトの Constraint モードで、2つめは PUBO (Polynomial Unconstrained Binary Optimization) モードです。通常の用途では、デフォルトの Constraint モードの利用を推奨します。これに対して PUBO モードは、量子アニーリングあるいはデジタル回路によるアニーリングハードウェアのシミュレータとして利用する研究者向けを想定しています。両者の大きな違いとして制約条件の取り扱いがあります。デフォルトの Constraint モードは等式・不等式制約条件をソルバーが直接扱えるのに対して、PUBO モードでは課したい制約条件に相当する目的関数へのペナルティ関数をユーザが設定して求解します。Amplify AE の動作アルゴリズムに則ったこれらの技術的な差異は、[求解のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/algorithm.md) を参照してください。 Amplify SDK の機能を使うと、制約条件・ペナルティ関数の設定は Amplify SDK が自動で行います。また、Constraint モードと PUBO モードの切り替えも容易に可能です。詳細は[クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 > [!TIP] > > **Changed in version 1.1.0** > > バージョン 1.1.0 で、項数が多い 2 次の大規模問題に特化した密結合モードが追加されました。 > Amplify SDK を使用する場合は、目的関数の定式化に [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) を使用することで密結合モードを使用できます。 > 一方 [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) を使用した場合は従来の疎結合モードが使用されます。 > ただし、項数や問題規模に応じて、指定したモードが非効率と判断された場合は、他方のモードで実行されます。 ### パラメータフリー Amplify AE はユーザが求解に際して調整するパラメータを持ちません。ユーザが求解したい最適化問題を入力すると、ソルバー内部で自動的に最適なアニーリングの戦略を決定し、適切な求解を行います。例えば、シミュレーテッドアニーリング法における温度降下スケジュールや、ペナルティ関数の重みパラメータなどが自動調整されます。これにより、複雑なパラメータ調整の必要なく、ユーザは GPU アニーリングの性能を最大限に引き出すことができます。 ### マルチ GPU 対応 Amplify AE はマルチ GPU 環境に対応しており、複数の GPU を用いた並列処理が可能です。Amplify AE のマルチ GPU の利用用途には、複数の異なる問題の同時求解と、同一の問題に対する計算能力の向上があげられます。前者は、複数人での利用や複数の問題を同時に解く場合に有効です。後者は、同一の問題に対してより多くの計算資源を割り当て、GPU 間での通信を行うことで、より高精度な解を得ることが可能になります。言い換えると、より短時間で高い精度の解を得られます。 --- # 最新バージョンの紹介 このページでは、Amplify AE の最新バージョン (v1.0系) における主な改良点と新機能について説明します。最新版は従来の Amplify AE (v0.9系) と比較して、次の主要な点で大幅な性能向上を実現しています。 * GPU 最適化アルゴリズムの刷新 * 高次多項式(最大 4 次)への対応 * 制約条件の取り扱い強化(不等式制約、制約重みの自動調整) 現在、両方のバージョンが並行して提供されていますが、最新版への移行を強く推奨します。 ## 最新版への移行方法 Amplify SDK を使用している場合、従来版の Amplify AE から最新版への移行はクライアントクラスの置き換えのみで行えます。パラメータ設定の方法もほぼ同様ですが、一部名称が変更されています。 以下は置き換えの一例です。 **従来版を使用する場合** ```python from amplify import FixstarsClient client = FixstarsClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 実行時間を1秒に設定 client.parameters.timeout = 1000 ``` **最新版を使用する場合** ```python from amplify import AmplifyAEClient from datetime import timedelta client = AmplifyAEClient() # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 実行時間を1秒に設定 (注: パラメータ名が変更) client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) の使い方の詳細については、[クライアントページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md)を参照してください。 ## アップデートの背景 従来版の Amplify AE は、大規模問題に対応可能な GPU ベースのイジングマシンでしたが、QUBO ソルバー特有の課題を抱えていました。 * 不等式制約を扱うためには、補助変数の導入が必要であること * 制約ペナルティの重み設定において、チューニングの手間がかかること * 3 次以上の多項式を扱うためには、次数下げ処理が必要であること これらの課題は、求解の精度や速度の低下を招く要因となっていました。 最新版の Amplify AE は、これらの課題を根本から解決するためにアルゴリズムを刷新しています。最大 4 次までの多項式を直接扱えるようになり、さらに、制約条件に対する重みの設定が不要になりました。これにより、従来バージョンや他社ソルバーとは一線を画す、圧倒的なパフォーマンスを実現しています。 ## ベンチマークによる性能検証 最新の Amplify AE の実力を、一般的なベンチマーク問題および弊社が過去に対応した実問題で測定しました。比較対象として、他社(A社、B社)のソルバーの結果も掲載しています。 グラフの横軸は実行時間、縦軸は目的関数の値です。プロットが左下にあるほど、速く良い解が得られることを示します。 ### 2 次ナップサック問題 2 次ナップサック問題において、最新の Amplify AE は極めて良い求解性能を記録しました。問題セットには [ベンチマーク問題集](https://cedric.cnam.fr/~soutif/QKP/QKP.html) から `jeu_300_50_1` を使用しました。この問題セットは、300個のアイテムから50個を選択するナップサック問題です。 | ソルバー名 | 最適解の取得時間 | | --- | --- | | Amplify AE | **0.233 s** 🏆 | | A 社ソルバー | 4.08 s | | B 社ソルバー | 50.0 s | 最適解への到達速度は、A 社ソルバーの 18 倍、B 社ソルバーの 217 倍に達しました。 ### 実企業の人員シフト最適化問題 多数の制約(等式制約 365 個、不等式制約 720 個)が絡み合う複雑な人員シフト問題でも、Amplify AE はその実力を発揮しました。 *対話的なグラフです。HTML 版でのみ表示されます。* | ソルバー名 | 最良解の目的関数値 (実行60秒) | | --- | --- | | Amplify AE | **23.7** 🏆 | | A 社ソルバー | 24.5 | | B 社ソルバー | (実行可能解を得られず) | A 社ソルバーの 6 倍の速度で最適解に到達しました。B 社ソルバーは複雑な制約条件の組み合わせに対処できず、実行可能解が見つかりませんでした。 ## 制約条件の対応強化 以下は複数種類の制約条件が複雑に絡み合う実課題に基づく生産計画問題における求解結果の比較グラフです。 *対話的なグラフです。HTML 版でのみ表示されます。* この結果から、最新版は従来版と比較して 100 倍以上高速に実行可能解を発見し、さらに従来版よりも質の高い解に到達していることが分かります。実運用で直面する複雑な制約条件を持つ問題において、Amplify AE は大幅な性能向上を実現しています。 ### 制約重みの自動調整 最新版ではこの求解性能を従来より遥かに手軽にご利用いただけます。従来の最適化において、特に多くのユーザ様が躓かれていたのが制約の重み調整でした。最新版ではこの問題を抜本的に解決する機能を取り入れています。 移行はシンプルです。[`FixstarsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) クラスを [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) クラスに置き換えるだけで、制約重み調整が不要になります。 例えば一般的な QUBO ソルバーにおいて制約重みの考慮が必須な問題である巡回セールスマン問題(TSP)でも次のように重み不要で最大の求解性能を発揮して求解できます。 **従来版** ```python model = Model( route_length, (one_hot(q, axis=1) + one_hot(q, axis=0)) * distance.max(), ) ``` **最新版** ```python model = Model( route_length, (one_hot(q, axis=1) + one_hot(q, axis=0)), ) ``` 制約の重み調整は QUBO ソルバー特有の課題の一つで、制約の多い複雑な問題ほど適切な重みを見つけることは簡単ではありません。最新版の Amplify AE では、複数の制約条件式間の重み、目的関数と制約条件の間の重みのどちらについても自動で調整します。これにより、ユーザの定式化時の手間を削減し、常に最大の求解性能を発揮します。また、最適な重みが与えられるために手動チューニング時よりも高い求解精度を実現します。 ### 不等式制約に補助変数が不要 最適化を複雑化させる要因の一つとして不等式制約の取り扱いも挙げられます。最新版の Amplify AE ではアルゴリズムの刷新により、不等式制約を含む問題に対する性能が飛躍的に向上しました。こちらも定式化の変更は不要でAmplifyAEClient クラスに変更いただくだけでご利用いただけます。 不等式制約の取り扱いも QUBO ソルバーに特有の課題です。不等式制約の表現には補助変数を新たに発行する必要があるため、問題サイズが増大し求解が難しくなるという課題があります。従来は定式化の段階で一部の不等式制約について、不正確ながら問題が解きやすくなるペナルティ関数を選択していただくことで問題を緩和する(緩和法)などの工夫が必要な場合がありました。 最新版の Amplify AE では、 ソルバー内部でペナルティ関数を生成する機能を導入することで、不等式の正確な表現を維持しながら、問題サイズに影響を与えず取り扱えるようになりました。不等式制約についてもユーザの試行錯誤を削減し、より本質的な問題へ集中することを可能とします。 ## 高次多項式への対応 従来版の Amplify AE を含む QUBO ソルバーは、目的関数や制約条件が二次形式であることを前提として設計されてきました。しかし、実務における次の例のような課題では、変数間の相互作用が複雑化し、三次以上の高次多項式での定式化を余儀なくされるケースが多々あります。 実務における高次多項式問題の例 * 物流:輸送コストの最小化と平準化、複雑なネットワーク制約の考慮 * 生産計画:複数のマシンや複数の工程にまたがる、複雑な非線形制約を持つ最適化 * 通信ネットワーク:帯域割り当てやリソース利用における多変数間の複雑な相互作用 このような高次の問題に対しては、目的関数と制約条件をソルバーが扱える次数まで次数下げを行う必要があります。次数下げでは、多数の補助変数と制約を導入する必要があるため、問題が複雑化し、結果として実用的な計算時間で有効な解を得ることが困難になるという課題がありました。 最新版の Amplify AE では、目的関数・制約条件ともに最大四次式まで直接取り扱えるようになり、四次までの問題は次数下げの必要がなくなりました。 高次多項式対応による効果: * 性能の飛躍的向上:次数下げを不要とすることで、従来のソルバーでは求解が困難であった、あるいは解の質が悪化していた高次の問題に対して、圧倒的な性能を発揮します。 * 問題表現の忠実性:複雑な相互作用を持つ問題を、より自然な形で定式化し、問題サイズが不必要に増大するのを防ぎます。 一方、学術研究等で要望の強い、理想的な量子アニーリングマシンとして振る舞う、QUBO ソルバーモードもご用意しております。そのため、Amplify AE は実務・研究の両方で有効にご活用いただける高性能な組合せ最適化ソルバーとなっています。 ### 従来版との性能比較 目的関数が四次式となる LABS(Low Autocorrelation Binary Sequence:低自己相関二値列問題)問題と BVRP(Balanced Vehicle Routing Problem:負荷平準化配車計画問題)について、従来版の Amplify AE との比較を実施しました。 * LABS 問題:できる限りノイズが少ない(自己相関が低い)電気信号の並びを見つけ出すための最適化問題です。 * BVRP:複数台の車両の総経路長の最小化に加え、各車両の負荷を平準化するために各経路の分散(ばらつき)の最小化も目的とした最適化問題です。 以下はそれぞれの問題における求解結果の比較グラフです。グラフの横軸は実行時間、縦軸は目的関数の値です。プロットが左下にあるほど、速く良い解が得られることを示します。 *対話的なグラフです。HTML 版でのみ表示されます。* *対話的なグラフです。HTML 版でのみ表示されます。* * LABS 問題:従来版と比較して、より高速に実行可能解を発見し、さらに従来版よりも質の高い解に到達しています。 * BVRP:次数下げによる補助変数の増大が原因で実行可能解の発見に至らなかった従来版に対し、最新版は高速に実行可能解を見つけ、その後も継続的に解の質を改善しています。 以上の結果から、高次(四次)の問題に対して、最新版 Amplify AE は従来版と比較して大幅な性能向上を実現していることが分かります。 > [!NOTE] > > **参考** > > 慶応義塾大学田中研究室による [こちらの論文](https://arxiv.org/abs/2510.24237v1) では、最新版 Amplify AE を用いて、従来のように次数下げを行うよりも高次式を直接扱う手法の方が、構造の単純さ・計算の安定性・解の品質の点において優れていることが実証されています。技術的な詳細に関心をお持ちの方は、ぜひご一読ください。 ## マルチ GPU オプション 標準の利用プランでは 1 つの GPU を利用することができますが、複数の GPU を利用できる GPU 追加オプションをご用意しています。複数の GPU を活用することで、次の方法で利用できます。 ### 複数ジョブの並列実行 複数の最適化問題を解きたい場合、各 GPU で並列にジョブを実行することで効率的に求解することができます。 Amplify SDK を使用している場合、solve 関数を parallel_solve 関数に置き換えるだけで複数の問題をご契約している複数 GPU を使って並列に解くことができます。 ### マルチ GPU による求解 Amplify AE は複数の GPU が連携してアニーリングするアルゴリズムを取り入れており、これによって良い解をより高速・高精度に求めることが可能になっています。 Amplify SDK を使用している場合、クライアントのパラメータとして使用する GPU の数を指定することでマルチ GPU による求解が実行できます。 ### マルチ GPU の計算性能 最大カット問題を対象として、各プランのアニーリング速度 (時間あたりの解の探索回数) の比較を行いました。 次のグラフはご利用プランを GPU の種類によって ベーシック/スタンダードプラン、プレミアムプラン、Sプレミアムプランに分類し、異なる3つの問題サイズでのアニーリング速度比を示したものです。Sプレミアム (2 GPUs) と Sプレミアム (4 GPUs) はマルチ GPU 求解時の性能を表しています。 *対話的なグラフです。HTML 版でのみ表示されます。* 高性能な GPU を利用できる上位のプランになるほどアニーリング速度が速くなっています。また、マルチ GPU 求解によってさらに高速な解の探索が実現されています。 ご利用プランやマルチ GPU オプションによる性能差は問題サイズが大きくなるほど顕著になっています。 ## 今後の展望 さらなるアルゴリズムの改良や新機能の追加を通じて、より多様な最適化問題に対応できるよう努めます。実用的な最適化ソリューションとしての価値を高めていくためにも、ユーザの皆様からのフィードバックを積極的に取り入れていきますので、ご意見をお寄せください。 直近では、最新の NVIDIA Blackwell アーキテクチャの GPU に対応予定です。 --- # 求解のアルゴリズム Fixstars Amplify Annealing Engine (Amplify AE) は、シミュレーテッドアニーリング (焼きなまし法) 法をベースにした最適化アルゴリズムで実行されます。 このページでは、Amplify AE のアルゴリズムの概要と、ソルバー内部の処理ステップについて説明します。 ## GPU アニーリング法 シミュレーテッドアニーリング (焼きなまし) 法では、最適化問題を解くために、目的関数を最小化することを目指します。最初に変数セットの初期解を生成し、徐々に解を改善していきます。解を繰り返し改善していく中で、各ステップでの温度と呼ばれるパラメータの値に応じて状態遷移を行います。温度が高い場合には、現在の状態から離れた新しい状態 (目的関数の値が現在より大きくなる解) に遷移する確率が高く、温度が低い場合には、現在の状態に近い (目的関数の値が現在より小さい) 新しい状態に遷移する確率が高くなります。温度が高いうちは、探索範囲が広くより大きな変化を許容します。温度が低くなるにつれて探索範囲は狭まり、より細かい解の改善に焦点を当てます。このようにして温度を徐々に下げていくことで、最適解を見つけることを目指します。 このプロセスは次のように定式化されます。現在の温度を $T$、現在の状態を $S$、新しい状態を $S'$、目的関数 $f$ の差分を $\varDelta f = f\left(S'\right) - f\left(S\right)$ とした場合、状態遷移の確率 $P_{S \rightarrow S'}$ は次のように表されます (メトロポリス法の場合)。 $$ P_{S \rightarrow S'} = \min \left( 1, \exp \left( -\varDelta f / T \right) \right) $$ 新しく状態 $S'$ を生成し、上記の式を評価することで状態遷移を行うかどうかを確率的に決定します。遷移が許可される場合は現在の状態が $S'$ に更新されます。温度 $T$ を高温から低温に変化させながら更新を繰り返すことで、解の改善が期待されます。 このプロセスが逐次的に行われるために、一般的にシミュレーテッドアニーリング法は並列化が難しいとされています。並列化のアルゴリズムはいくつかの方針が提案されていますが、Amplify AE では、GPU の計算性能を活かすことに特化した独自の並列化アルゴリズム [[1]](#id3) を採用することで、探索プロセス全体を高速かつ効果的に実行します。具体的には、遷移先の状態の候補の生成や目的関数の評価について GPU の並列計算を活用し、複数の遷移先の候補を用いた効率的な探索を実現しています。 > [!NOTE] > > **注釈** > > 疑似乱数を用いて確率的に状態遷移を行うため、実行する度に同じ入力に対しても異なる解が得られることがあります。 > GPU による並列計算では計算順序を制御できないため、たとえ疑似乱数のシード値を固定しても計算結果が同一になる保証がありません。 > そのため、現在の Amplify AE ではシード値の設定はサポートされていません。 一方、シミュレーテッドアニーリング法では温度変化のスケジューリングが重要です。ここで温度の変化のスケジューリングとは、初期温度と最終温度の決定と、その初期温度から最終温度への変化の仕方のことを意味します。温度スケジュールのチューニングは高精度の解を得るために必須の要素です。この問題に対し、Amplify AE では温度スケジューリングを自動的に調整する機能を有しており、ユーザーは温度に関するパラメータを設定する必要なく、適切な求解を可能としています。通常の温度スケジュールでは最終温度までのステップ数を指定して探索を終了しますが、Amplify AE は探索過程の最小単位を入力された問題や求解の状況に応じて自動的に決定します。さらにこれを継続的に繰り返すことで、与えられた求解時間 (`time_limit_ms` リクエストパラメータ) が経過するまで探索を続けます。これにより、実行時間を長く指定するほど高精度な解を得る可能性が高まります。 ### 目的関数の最適化 上記のアルゴリズムに従い、入力された目的関数に対して次のようにして新しい状態 $S'$ と目的関数の値 $f\left(S'\right)$ を計算します。まずは制約条件が存在しない場合の目的関数の最適化について説明します。 Amplify AE はバイナリ変数の多項式を入力として受け付けるため、ある変数 $q$ に対してその変数の値を反転 ($0$ を $1$ あるいは $1$ を $0$ に) する操作 $q \leftarrow 1 - q$ を行うことで新しい状態 $S'$ を生成します。このとき、目的関数の差分 $\varDelta f$ は次のように表されます。 $$ \varDelta f_{\rm{obj}}^q = f\left(S'\,|\,q \leftarrow 1 - q \right) - f\left(S \,|\,q\right) $$ この値から状態遷移確率 $P_{S \rightarrow S'}$ を計算し、一様乱数を生成して状態遷移が許可されるかどうかを決定します。状態遷移が許可される場合は、現在の状態 $S$ が新しい状態 $S'$ に更新されます。 ### 制約条件の最適化 アニーリング法で制約条件を扱う場合、与えられた全ての制約条件が満たされる解について目的関数の最小化を実行する必要があります。制約条件を満たす解を得るためには、例えば制約条件を満たす状態遷移のみを許可する方法が考えられます。しかし、候補となる状態遷移が制約条件を満たすかどうかを確認するために、全ての制約条件を評価する必要があり、計算量が増大してしまいます。さらに、制約条件を満たす状態遷移のみを許可すると、探索空間が狭まり必ずしも最適解に到達できない可能性があります。 そこで、Amplify AE では、制約条件を満たす解を得るために、制約条件に相当するペナルティ関数を導入し、これを目的関数の追加項として扱います。基本的に、ペナルティ関数は制約条件を満たす解に対しては $0$ となり、制約条件を満たさない解に対しては $0$ より大きな値をとる性質を持ちます。これにより、目的関数の最小化と同時にペナルティ関数の値が $0$ となれば、制約条件を満たす解が得られることになります。 この方針は、量子アニーリングやイジングマシンハードウェアなどの QUBO ソルバーで制約条件を扱う際に広く用いられる方法です。探索の途中ではあえて制約条件を満たさない状態遷移を許可することで探索空間を広げることができます。 ある制約条件 $c$ のペナルティを $g_c$ とした場合、目的関数と同様にして、変数 $q$ を反転するときのペナルティ関数の差分 $\varDelta g_c$ を次のように定義します。 $$ \varDelta g_c^{q} = g_c\left(S'\,|\,q \leftarrow 1 - q \right) - g_c\left(S \,|\,q\right) $$ さらに、目的関数の差分を $\varDelta f$ を次のように読み替えます。 $$ \varDelta f = \varDelta f_{\rm{obj}}^q + w \sum_c \varDelta g_c^{q} $$ この $\varDelta f$ から状態遷移確率 $P_{S \rightarrow S'}$ を計算して状態を更新していきます。 ここで $w \left(> 0 \right)$ はペナルティ関数の重みを表します。終状態で制約条件を満たすためには、ペナルティ関数を適切に調整する必要がある点に注意を要します。目的関数の変化に対して制約条件の重みが小さいと、制約条件を満たさない解が選択される可能性が高くなります。一方で、重みが大きすぎると目的関数の最小化が難しくなる可能性があります。このバランスが高い精度で解を得るために非常に重要です。Amplify AE では、ペナルティ関数の重みを自動的に調整する機能を有しており、ユーザーはこのパラメータを設定することなく適切な求解を行うことができます。 Amplify AE によるペナルティ関数の評価は、ユーザの入力に応じて次の 2 通りの方法で行われます。 (i) デフォルトの場合 ユーザから制約条件式を受け取った場合、ペナルティ関数は制約の違反量に対して単調増加する式として Amplify AE が実行時に計算します。このとき、Amplify AE はペナルティ関数 $g_c$ を違反量 $d$ の関数として以下の性質を満たすように生成します。 $$ \begin{align*} g_c\left(d \right) & = \begin{cases} 0 & (d = 0; c \text{ is satisfied}) \\ \text{positive value} & (d > 0; c \text{ is not satisfied}) \end{cases} \\ g_c \left(d_1 \right) & = g_c \left(d_2 \right) \quad \text{for} \quad d_1 = d_2 \\ g_c \left(d_1 \right) & < g_c \left(d_2 \right) \quad \text{for} \quad d_1 < d_2 \end{align*} $$ ペナルティ関数は、ユーザが入力した制約条件に基づき、Amplify AE の求解中に自動生成されます。もしペナルティ関数をユーザが直接指定したい場合は、次の PUBO モードを利用します。 (ii) PUBO モードの場合 ユーザが制約条件の代わりにペナルティ関数を与えた場合、指定されたペナルティ関数を利用してペナルティ値を評価します。この動作状態を PUBO モードと呼びます。ここでペナルティ関数は以下を満たす必要があります。 $$ g_c\left(d \right) \ge 0 $$ PUBO モードでは、ユーザはペナルティ関数 $g_c$ とその重み $w_c$ を直接指定します。これらを用いて状態遷移の差分は以下のように計算されます。 $$ \varDelta f = \varDelta f_{\rm{obj}}^q + w \sum_c w_c \varDelta g_c^{q} $$ ペナルティ関数全体にかかる $w$ は、前述の Amplify AE が自動調整する重みです。PUBO モードでのみ、この機能の制御をリクエストデータの `penalty_weight_calibration` フィールドで設定できます。これを無効 (`false`) にした場合は $w = 1$ に固定化されます。 一方 $w_c$ はユーザがペナルティ関数ごとに個別に指定可能で、相対的な重み付けを担います。デフォルトは $w_c = 1$ です。制約条件を満たす解が得られない場合などには、ユーザがこの値を調整することで求解の精度を向上させることができます。 通常、違反量 $d$ が $0$ のときはペナルティ関数の値も $0$ となり、制約が満たされていると解釈されます。これに対して、オプションとして違反量に対して制約が満たされていると見なす閾値 $d_{\text{th}}$ を設定することもできます。これを用いると、$d \le d_{\text{th}}$ の場合、仮にペナルティ関数の値が $0$ でなくても、制約条件が満たされていると見なします。この値を設定する必要があるのは、例えば[緩和法](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-relaxation)を用いて制約条件のペナルティを設定する場合です。この値を用いて Amplify AE は取得した解が制約条件を満たすかを判定するのに利用します。Amplify SDK を用いて定式化した場合、ペナルティ関数の性質に応じて $d_{\text{th}}$ は適切な値が自動的に設定されます。 > [!NOTE] > > **参考** > > Amplify SDK を用いてモードの切り替えやペナルティ関数の設定を行う方法については [クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 --- [[1](#id2)] 特許取得済み --- # 高度な利用方法 レスポンスデータから取得できる情報を活用することで、Amplify AE の利用をより効果的に行えます。このセクションでは Amplify AE の高度な利用方法について説明します。 ## 実行時間情報の取得 Amplify AE はユーザからの求解のリクエストを受け取った後に以下のステップで実行し結果を返却します。 [![../_images/timing_light.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_light.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_light.drawio.svg) [![../_images/timing_dark.drawio.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_dark.drawio.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/timing_dark.drawio.svg) 1. リクエストデータの解析 * ユーザからの求解リクエストを解析し、JSON データから必要な情報を抽出します 2. リソースの割り当て * ユーザが使用可能な GPU リソースを予約し計算に必要な環境を準備します 3. GPU による求解 * シミュレーテッドアニーリング法に基づく最適化アルゴリズムを実行します 4. 結果の解析と返却 * 計算結果をホストメモリに転送し、最適解や目的関数・制約条件の評価結果を返却します 上の右図は、Amplify SDK が想定するソルバーの実行時間に関する模式図です。Amplify AE はこの図に即した動作を行います。 "Receive Request" から "Start Execution" までの時間は、上のステップにおける 1 と 2 の処理時間に相当します。"Start Execution" から "End Execution" までの時間は 3 に相当し、"End Execution" から "Send Response" までの時間は、4 に対応します。 リクエストデータに含まれる `time_limit_ms` パラメータは 3 の時間を指定するものですが、完全に一致させることは難しく、指定時間を少し超過することがあります。そのため、実際の処理時間については レスポンスデータの `execution_time_ms` フィールドに記録されます。また、ステップ 2 の待ち時間はレスポンスデータの `queue_time_ms` フィールドで取得できます。 レスポンスデータに含まれる時刻情報を以下にまとめます。 | | | | --- | --- | | `execution_time_ms` | GPU の求解時間 (ms 単位) | | `queue_time_ms` | リソース割当キュー (ステップ2) の待ち時間 (ms 単位) | | `submitted_at` | リクエストを受け取った時刻 ("Receive Request" の時刻) | | `started_at` | GPU 処理を開始した時刻 (ステップ3開始時刻) | > [!NOTE] > > **参考** > > Amplify SDK による時刻情報の取得については [クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 ステップ 4 の "Start Execution" から "End Execution" までの間、Amplify AE は最適化アルゴリズムを実行し、最良解が更新される度に得られた解とその実行時間を記録します。これにより、探索中の解の履歴がユーザに返却されます。それぞれの解の取得時刻は `solutions` フィールド内の配列要素における `time_stamp_ms` フィールドに記録されます。この時刻はステップ3開始時刻 (`started_at`) からの経過時間を表します。これらの情報を用いる事で、ユーザは探索の進行状況の履歴を把握できます。Amplify SDK を用いた実行時間に関する解析の例は [実行時間情報の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/timing.md) を参照してください。 ## 求解情報の取得 上記の求解における "Execution Time" の時間の間に、Amplify AE がどの程度の求解のイテレーションを実行したのかについて、レスポンスデータに詳細な情報が記録されます。 Amplify AE は求解フェーズにおいて、指定された数の GPU を用いてアニーリング法に基づき、現在の状態 (変数の値の組み合わせ) から次の状態を作成します。この操作を「フリップ」と呼びます。GPU は求解の状況に応じて決められた数のフリップを行い、その間に得られた最良解を CPU に返します。ここではこれを「サンプリング」と呼びます。もしサンプリングで得られた解が前回の最良解よりも良い場合は既知の最良解を更新します。この一連の操作を指定された時間に達するまで行い、ユーザに解の更新履歴として結果を返します。 上記の求解処理において、Amplify AE は次の情報をレスポンスデータに記録します。 | | | | --- | --- | | `num_gpus` | 求解に使用した GPU 数 | | `num_flips` | 実行結果を返却するまでに試行した全 GPU の合計フリップ数 | | `num_samplings` | 実行結果を返却するまでに得られた解の数 (サンプリング数) | | `version` | Amplify AE のバージョンと GPU の名前 | > [!NOTE] > > **参考** > > Amplify SDK による求解情報の取得については [クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 ## 重複解の取得 同じ目的関数の値を持つ解が複数存在する場合、デフォルトでは Amplify AE は最初に見つけた解のみを記録します。これは、既知の最良解を更新するプロセスが、より良い解が見つかった場合にのみ更新されるためです。 この動作を変更し発見したすべての重複解を取得したい場合、リクエストデータの `duplicate_solutions` パラメータを `true` に設定します。これにより、変数の組み合わせが異なるが目的関数の値が同じ解もすべて記録され、レスポンスデータの `solutions` フィールドに含まれる配列に返却されます。 > [!NOTE] > > **注釈** > > 必ずしも全ての重複解を取得できるわけではないことに注意してください。Amplify AE の探索アルゴリズムは確率的であり、同じ目的関数の値を持つ解が複数存在する場合でも、全ての解を見つけることが保証されているわけではありません。 > [!NOTE] > > **参考** > > Amplify SDK による重複解の取得については [クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/fixstars.md) を参照してください。 --- # Amplify AE の性能評価 Amplify AE の性能を評価するため、(1) 求解性能、(2) アニーリング速度という 2 つの観点でベンチマークを取得しています。 ## 求解性能ベンチマーク 公開されているベンチマーク問題、および実社会における最適化問題をベンチマークセットとして、実行時間ごとの目的関数の値を取得しました。 また、比較対象として他社のイジングマシン 2 種類でも同様にベンチマークを取得しました。 これらのソルバーについては、設定可能なパラメータを複数通り試し、最も良い結果を得たケースを載せています。 Amplify AE 内部のアルゴリズムや求解性能は設定した実行時間 (`time_limit_ms`) に依存しないため、1 回の実行のレスポンスに含まれる複数の解 (経過時間と目的関数の値) をプロットしています。 一方、他社ソルバーについては、1 回の実行につき最良の結果のみを取得しているため、実行時間が異なるデータは独立しています。 各データは 11 回試行した中央値を表示しています。 指定した実行時間で実行可能解が得られなかった場合、そのデータはプロットされていません。 ### 実行環境 * Amplify SDK v1.4.0 * Amplify AE v1.0.0 * NVIDIA Hopper 1基 * Constraint モード ### ベンチマーク問題 ベンチマークに使用した問題の概要は以下の通りです。2次以上の目的関数を持つベンチマーク問題と実在する企業における業務課題をいくつか取り上げています。 | 問題セット | 変数の個数 | 目的関数 | 等式制約 | 不等式制約 | | --- | --- | --- | --- | --- | | [QKP (jeu_300_50_1)](https://cedric.cnam.fr/~soutif/QKP/jeu_300_50_1.txt) | 300 | 2 次 | なし | 最大 1次 / 1個 | | [CVRP (E-n51-k5)](https://vrp.atd-lab.inf.puc-rio.br/media/com_vrp/instances/E/E-n51-k5.vrp) | 5,100 | 2 次 | 最大 1 次 / 160 個 | 最大 1 次 / 5 個 | | 生産計画問題 | 7,400 | 2 次 | 最大 1 次 / 933 個 | なし | | 人員シフト問題 | 730 | 2 次 | 最大 2 次 / 365 個 | 最大 1 次 / 720 個 | ### ベンチマーク結果 (求解性能) #### 2 次ナップサック問題 (QKP, jeu_300_50_1) ナップサック問題は、荷物の価値と重みが与えられて、重みが一定の値に収まるような荷物の選び方のうち価値の総和が最大になる選び方を求めます。これに対し QKP では荷物のペアで追加の価値が生じることを考慮するより難しい問題となっております。 *対話的なグラフです。HTML 版でのみ表示されます。* | ソルバー名 | 実行可能解の取得時間 [[1]](#no-zero) | 最適解の取得時間 | | --- | --- | --- | | Amplify AE | **0.00176 s** 🏆 | **0.233 s** 🏆 | | A 社ソルバー | 3.09 s | 4.08 s | | B 社ソルバー | 0.12 s | 50.0 s | #### 容量制約付き運搬経路問題 (CVRP, E-n51-k5) 容量制約付き運搬経路問題 (CVRP) は、車両の積載容量に制限のある $k$ 台の車を使って $n$ 個の配送先に荷物を届けるルートのうち、距離や輸送コストが最小となるルートを選ぶ問題です。 *対話的なグラフです。HTML 版でのみ表示されます。* | ソルバー名 | 実行可能解の取得時間 | 最良解の目的関数値 [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.0780 s** 🏆 | **589** 🏆 | | A 社ソルバー | 1.12 s | 653 | | B 社ソルバー | (実行可能解を得られず) | (実行可能解を得られず) | #### 生産計画問題 工場の生産スケジュールにおける生産コストを最小化する業務課題を Amplify AE で解きました。 *対話的なグラフです。HTML 版でのみ表示されます。* | ソルバー名 | 実行可能解の取得時間 [[2]](#sec) | 最適解の取得時間 [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.140 s** 🏆 | **0.142 s** 🏆 | | A 社ソルバー | 30.7 s | 34.5 s | | B 社ソルバー | 4.08 s | (最適解を得られず) | #### 人員シフト問題 様々な制約がある中で、最も効率の良い作業員シフトを組む業務課題を Amplify AE で解きました。 *対話的なグラフです。HTML 版でのみ表示されます。* | ソルバー名 | 実行可能解の取得時間 | 最良解の目的関数値 [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.026 s** 🏆 | **23.7** 🏆 | | A 社ソルバー | 21.0 s | 24.5 | | B 社ソルバー | (実行可能解を得られず) | (実行可能解を得られず) | ## アニーリング速度ベンチマーク GPUアニーリングでは、1秒あたりの [フリップ回数](https://amplify.fixstars.com/ja/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solveinfo) が多いほど探索できる組み合わせが増え、与えられた求解時間においてより良い解が見つかる可能性が高まります。 Amplifyクラウドサービスでは、上位プランほど高性能なGPUをご利用いただけます。そこで、1秒あたりの変数フリップ回数を「アニーリング速度」と定義し、各プランで提供される GPU の性能と利用台数ごとのアニーリング速度を測定しました。検証には、小・中・大の3種類の問題サイズからなるベンチマークセットを使用しています。 各プランで提供されるGPUの種類については、[価格ページ](https://amplify.fixstars.com/ja/pricing) をご参照ください。 | GPU 名 | 提供プラン | | --- | --- | | NVIDIA Volta | ベーシック / スタンダード | | NVIDIA Ampere | プレミアム | | NVIDIA Hopper | Sプレミアム / エンタープライズ | ### 実行環境 * Amplify SDK v1.4.0 * Amplify AE 1.0.0 Constraint モード * GPU 数 1 - 4 (2以上は NVIDIA Hopper のみ) ### ベンチマーク結果 (アニーリング速度) アニーリング速度について、Basic プランからの比と実数値をプロットしました。 問題規模が大きくなるほど、プランによる差異が顕著に表れます。 #### 最大カット問題 (全結合) **Basic 比** *対話的なグラフです。HTML 版でのみ表示されます。* **実数値** *対話的なグラフです。HTML 版でのみ表示されます。* #### 最大カット問題 (疎結合) **Basic 比** *対話的なグラフです。HTML 版でのみ表示されます。* **実数値** *対話的なグラフです。HTML 版でのみ表示されます。* #### 巡回セールスマン問題 **Basic 比** *対話的なグラフです。HTML 版でのみ表示されます。* **実数値** *対話的なグラフです。HTML 版でのみ表示されます。* --- [[1](#id5)] 自明な実行解 (全てゼロ) を除く [2] ([1](#id6),[2](#id8),[3](#id9),[4](#id11)) 実行時間を 60 秒とする --- # Changelog ## v1.3.0 (Aug. 21, 2026) * Improve performance for linear problems containing only integer-coefficient constraints. ## v1.2.0 (Jun. 09, 2026) * Improve performance for problems containing constraints with a wide range of coefficients. * Reduce overhead when using multiple GPUs. v1.2.1 (Jul. 10, 2026) * Return a better solution when no feasible solution has been found. * Fix: Prevent possible bug in the dense objective mode. ## v1.1.0 (Mar. 31, 2026) * Add support for dense format input for objective functions * Improve performance for quadratic problems involving numerous nonlinear terms in objective function ## v1.0.0 (Oct. 16, 2025) * Release the v1 API series. * Major update of API specification. v1.0.2 (Oct. 31, 2025) * Enhance performance for problems without an objective function. ## v0.9.0 (Sep. 01, 2025) * Final version of the v0 API series. * Support asynchronous API calls. ## v0.8.0 (Sep. 07, 2023) * Improve response time. ## v0.7.4 (Oct. 07, 2022) * Improve performance. * [Removed] Remove `num_unit_steps` parameter. This parameter is now automatically adjusted internally. ## v0.6.4 (Apr. 28, 2022) * Improve performance greatly. * Support NVIDIA A100 GPU through a newly added service contract plan, which speeds up large-scale problems and accepts fully connected 131,072 bit-problems at the largest (twice as currently running V100 GPU). * Support multi GPU computation. Add `num_gpus` parameter to indicate the number of GPUs for annealing. * Add runtime `version` information to execution parameter outputs. ## v0.5.7 (May 09, 2021) * Improve performance. * Improve precision of internal calculations. * Add support of penalty function inputs. * Automatically calibrate multipliers of penalty functions. * Return `feasibilities` parameter which shows whether each solution is feasible. * Extend execution parameter outputs * `timeout` to show the input timeout value. * `num_iterations` to indicate the number of iterations of optimization until timeout. * `penalty_calibration` to show whether automatic calibration of penalty functions is enabled. * `penalty_multipliers` to show (calibrated) multipliers of penalty functions. * Extend `polynomial` parameter to accept a constant value. ## v0.4.5 (Nov. 17, 2020) * Improves performance for problems with variables that do not contain interactions. ## v0.3.5 (Sep. 09, 2020) * Improve performance. * Accept upper and lower triangular matrix for `matrix` key of the request parameter. * Accept encoded request and response body compressed by deflate or gzip. * Set the value of `num_unit_steps` to `10` as default. ## v0.2.3 (Jul. 16, 2020) * Improve performance. * Increase maximum problem size. * Fully connected (matrix): 65,536 bits * Sparse (polynomial): 4,294,967,296 elements ## v0.1.0 (Dec. 25, 2019) * Initial release 🎄 --- # API Reference ```json { "openapi": "3.1.0", "info": { "title": "Amplify Annealing Engine API", "version": "1.3.0" }, "servers": [ { "url": "https://optigan.fixstars.com" } ], "paths": { "/v1/health": { "get": { "tags": [ "Annealing Engine v1 API" ], "summary": "Health Check", "description": "サービスが正常に動いているか確認します。", "operationId": "health_check_v1_health_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseHealth" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X GET \"https://optigan.fixstars.com/v1/health\" \\\n -H \"Authorization: Bearer \"" } ] } }, "/v0/health": { "get": { "tags": [ "Annealing Engine v0 API" ], "summary": "Health Check", "description": "サービスが正常に動いているか確認します。", "operationId": "health_check_v0_health_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseHealth" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X GET \"https://optigan.fixstars.com/v0/health\" \\\n -H \"Authorization: Bearer \"" } ] } }, "/health": { "get": { "tags": [ "Annealing Engine v0 API" ], "summary": "(Alias) Health Check", "description": "サービスが正常に動いているか確認します。", "operationId": "_Alias__health_check_health_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseHealth" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X GET \"https://optigan.fixstars.com/health\" \\\n -H \"Authorization: Bearer \"" } ] } }, "/v1/sync/solve": { "post": { "tags": [ "Annealing Engine v1 API" ], "summary": "V1 Solve (Synchronous)", "description": "ソルバーを同期的に実行します。", "operationId": "v1_solve__synchronous__v1_sync_solve_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RequestV1Solve" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV1SyncSolve" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "429": { "description": "Too Many Requests", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "500": { "description": "Internal Server Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X POST \"https://optigan.fixstars.com/v1/sync/solve\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d @request.json" } ] } }, "/v1/async/solve": { "post": { "tags": [ "Annealing Engine v1 API" ], "summary": "V1 Solve (Asynchronous)", "description": "ソルバーを非同期に実行します。", "operationId": "v1_solve__asynchronous__v1_async_solve_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RequestV1Solve" } } }, "required": true }, "responses": { "201": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV1AsyncSolve" } } } }, "429": { "description": "Too Many Requests", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X POST \"https://optigan.fixstars.com/v1/async/solve\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d @request.json" } ] } }, "/v0/sync/solve": { "post": { "tags": [ "Annealing Engine v0 API" ], "summary": "V0 Solve (Synchronous)", "description": "ソルバーを同期的に実行します。", "operationId": "v0_solve__synchronous__v0_sync_solve_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RequestV0Solve" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV0SyncSolve" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "429": { "description": "Too Many Requests", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "500": { "description": "Internal Server Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X POST \"https://optigan.fixstars.com/v0/sync/solve\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d @request.json" } ] } }, "/solve": { "post": { "tags": [ "Annealing Engine v0 API" ], "summary": "(Alias) V0 Solve (Synchronous)", "description": "ソルバーを同期的に実行します。", "operationId": "_Alias__v0_solve__synchronous__solve_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RequestV0Solve" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV0SyncSolve" } } } }, "400": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "429": { "description": "Too Many Requests", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } }, "500": { "description": "Internal Server Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X POST \"https://optigan.fixstars.com/solve\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d @request.json" } ] } }, "/v0/async/solve": { "post": { "tags": [ "Annealing Engine v0 API" ], "summary": "V0 Solve (Asynchronous)", "description": "ソルバーを非同期に実行します。", "operationId": "v0_solve__asynchronous__v0_async_solve_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RequestV0Solve" } } }, "required": true }, "responses": { "201": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV0AsyncSolve" } } } }, "429": { "description": "Too Many Requests", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseOnError" } } } } }, "parameters": [ { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X POST \"https://optigan.fixstars.com/v0/async/solve\" \\\n -H \"Authorization: Bearer \" \\\n -H \"Content-Type: application/json\" \\\n -d @request.json" } ] } }, "/v1/jobs/{job_id}": { "get": { "tags": [ "Annealing Engine v1 API" ], "summary": "Job Result", "description": "ジョブの結果を取得します。", "operationId": "job_result_v1_jobs__job_id__get", "parameters": [ { "name": "job_id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "ジョブ ID", "title": "Job Id" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV1JobsCompleted" } } } }, "202": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseJobsNotCompleted" } } }, "description": "Accepted" }, "404": { "description": "Not Found" } }, "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X GET \"https://optigan.fixstars.com/v1/jobs/{job_id}\" \\\n -H \"Authorization: Bearer \"" } ] } }, "/v0/jobs/{job_id}": { "get": { "tags": [ "Annealing Engine v0 API" ], "summary": "Job Result", "description": "ジョブの結果を取得します。", "operationId": "job_result_v0_jobs__job_id__get", "parameters": [ { "name": "job_id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "ジョブ ID", "title": "Job Id" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "認証ヘッダー。`Bearer ` 形式で使用してください。" } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseV0JobsCompleted" } } } }, "202": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponseJobsNotCompleted" } } }, "description": "Accepted" }, "404": { "description": "Not Found" } }, "x-codeSamples": [ { "lang": "curl", "label": "cURL", "source": "curl -X GET \"https://optigan.fixstars.com/v0/jobs/{job_id}\" \\\n -H \"Authorization: Bearer \"" } ] } } }, "components": { "schemas": { "ConditionV0": { "properties": { "left": { "$ref": "#/components/schemas/PolynomialV0", "description": "条件の多項式" }, "op": { "type": "string", "enum": [ "=", "==", "eq", "EQ", "<", "lt", "LT", ">", "gt", "GT", ">=", "ge", "GE" ], "title": "Op", "description": "比較演算子", "default": "=" }, "right": { "type": "number", "title": "Right", "description": "右辺の値", "default": 0 } }, "type": "object", "required": [ "left" ], "title": "ConditionV0" }, "ConstraintV0": { "properties": { "penalty": { "$ref": "#/components/schemas/PolynomialV0", "description": "ペナルティ多項式" }, "multiplier": { "type": "number", "title": "Multiplier", "description": "ペナルティ関数の重み", "default": 1 }, "condition": { "anyOf": [ { "$ref": "#/components/schemas/ConditionV0" }, { "type": "null" } ], "description": "ペナルティ関数の条件。None の場合、`penalty` が condition として扱われます" } }, "type": "object", "required": [ "penalty" ], "title": "ConstraintV0" }, "ConstraintV1": { "anyOf": [ { "required": [ "lower" ] }, { "required": [ "upper" ] } ], "properties": { "lower": { "type": "number", "title": "Lower", "description": "下限", "default": "-inf" }, "upper": { "type": "number", "title": "Upper", "description": "上限", "default": "+inf" }, "expression": { "$ref": "#/components/schemas/PolynomialV1", "description": "制約を課す多項式" } }, "type": "object", "required": [ "expression" ], "title": "constraint" }, "DenseObjectiveV1": { "properties": { "matrix": { "items": { "items": { "type": "number" }, "type": "array" }, "type": "array", "title": "Matrix", "description": "目的関数の密行列表現。 上三角行列として与えられ、形式は [[a_11, ..., a_1n], [a_22, ..., a_2n], ..., [a_nn]] である必要があります。", "default": [] }, "constant": { "type": "number", "title": "Constant", "description": "目的関数の定数項", "default": 0 } }, "type": "object", "title": "DenseObjectiveV1" }, "ExecutionParametersV0": { "properties": { "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "計算に使用された GPU 数" }, "timeout": { "type": "number", "minimum": 0, "title": "Timeout", "description": "指定されたタイムアウト (msec)" }, "num_iterations": { "type": "integer", "minimum": 1, "title": "Num Iterations", "description": "タイムアウトまでの探索回数" }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "description": "ペナルティ係数の自動調整機能が有効化されたか" }, "penalty_multipliers": { "items": { "type": "number" }, "type": "array", "title": "Penalty Multipliers", "description": "解の探索に用いられたペナルティ係数の配列" }, "version": { "type": "string", "title": "Version", "description": "Amplify AE の実行時バージョン情報" } }, "type": "object", "required": [ "num_gpus", "timeout", "num_iterations", "penalty_calibration", "penalty_multipliers", "version" ], "title": "ExecutionParametersV0" }, "ExecutionTimeV0": { "properties": { "annealing_time": { "type": "number", "minimum": 0, "title": "Annealing Time", "description": "アニーリング実行時間 (msec)" }, "queue_time": { "type": "number", "minimum": 0, "title": "Queue Time", "description": "キュー待ち時間 (msec)" }, "cpu_time": { "type": "number", "minimum": 0, "title": "Cpu Time", "description": "CPU 処理時間 (msec)" }, "time_stamps": { "items": { "type": "number" }, "type": "array", "title": "Time Stamps", "description": "アニーリング開始時刻を 0 として、解が得られた時刻 (msec)" } }, "type": "object", "required": [ "annealing_time", "queue_time", "cpu_time", "time_stamps" ], "title": "ExecutionTimeV0" }, "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail" } }, "type": "object", "title": "HTTPValidationError" }, "MatrixV0": { "items": { "items": { "type": "number" }, "type": "array" }, "type": "array", "title": "MatrixV0", "description": "QUBO 行列" }, "OutputsV0": { "properties": { "spins": { "type": "boolean", "title": "Spins", "description": "変数の値を出力するかどうか", "default": true }, "energies": { "type": "boolean", "title": "Energies", "description": "エネルギーの値を出力するかどうか", "default": true }, "feasibilities": { "type": "boolean", "title": "Feasibilities", "description": "実行可能性の値を出力するかどうか", "default": true }, "sort": { "type": "boolean", "title": "Sort", "description": "出力のソート", "default": true }, "duplicate": { "type": "boolean", "title": "Duplicate", "description": "重複を許可するかどうか", "default": false }, "num_outputs": { "type": "integer", "title": "Num Outputs", "description": "出力の数", "default": 1 } }, "type": "object", "title": "OutputsV0" }, "PenaltyV1": { "properties": { "threshold": { "type": "number", "minimum": 0, "title": "threshold", "description": "ペナルティ関数のしきい値", "default": 0 }, "weight": { "type": "number", "exclusiveMinimum": 0, "title": "weight", "description": "ペナルティ関数の重み", "default": 1 }, "expression": { "$ref": "#/components/schemas/PolynomialV1", "description": "ペナルティ関数の多項式表現" } }, "type": "object", "required": [ "expression" ], "title": "penalty" }, "PolynomialV0": { "items": { "anyOf": [ { "anyOf": [ { "type": "number", "description": "係数" }, { "prefixItems": [ { "type": "number", "description": "係数" } ], "type": "array", "maxItems": 1, "minItems": 1 } ], "title": "coefficient" }, { "prefixItems": [ { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "変数のインデックス" }, { "type": "number", "description": "係数" } ], "type": "array", "maxItems": 2, "minItems": 2, "title": "linear" }, { "prefixItems": [ { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "変数のインデックス" }, { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "変数のインデックス" }, { "type": "number", "description": "係数" } ], "type": "array", "maxItems": 3, "minItems": 3, "title": "quadratic" } ] }, "type": "array", "title": "PolynomialV0", "description": "QUBO 多項式" }, "PolynomialV1": { "items": { "prefixItems": [ { "type": "number", "description": "係数" } ], "items": { "type": "integer", "maximum": 4294967295, "minimum": 0, "maxLength": 4, "minLength": 1, "description": "変数インデックスのリスト" }, "type": "array", "maxItems": 5, "minItems": 1 }, "type": "array", "title": "PolynomialV1" }, "RequestV0Solve": { "oneOf": [ { "$ref": "#/components/schemas/RequestV0SolvePolynomial" }, { "$ref": "#/components/schemas/RequestV0SolveMatrix" }, { "$ref": "#/components/schemas/RequestV0SolveConstraints" } ], "title": "RequestV0Solve" }, "RequestV0SolveConstraints": { "properties": { "constant": { "type": "number", "title": "Constant", "description": "定数項", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "出力設定" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "制約条件" } }, "type": "object", "required": [ "constraints" ], "title": "constraints-only" }, "RequestV0SolveMatrix": { "properties": { "constant": { "type": "number", "title": "Constant", "description": "定数項", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "出力設定" }, "matrix": { "$ref": "#/components/schemas/MatrixV0" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "制約条件" } }, "type": "object", "required": [ "matrix" ], "title": "matrix" }, "RequestV0SolvePolynomial": { "properties": { "constant": { "type": "number", "title": "Constant", "description": "定数項", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "出力設定" }, "polynomial": { "$ref": "#/components/schemas/PolynomialV0" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "制約条件" } }, "type": "object", "required": [ "polynomial" ], "title": "polynomial" }, "RequestV1Solve": { "oneOf": [ { "$ref": "#/components/schemas/RequestV1SolveSparseConstraint" }, { "$ref": "#/components/schemas/RequestV1SolveDenseConstraint" }, { "$ref": "#/components/schemas/RequestV1SolveSparsePenalty" }, { "$ref": "#/components/schemas/RequestV1SolveDensePenalty" } ], "title": "RequestV1Solve", "description": "Base model for RequestV1Solve to ensure correct discriminator usage." }, "RequestV1SolveDenseConstraint": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "重複解をレスポンスに含めるかどうか", "default": false }, "dense_objective": { "$ref": "#/components/schemas/DenseObjectiveV1", "description": "目的関数の密行列表現" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV1" }, "type": "array", "title": "Constraints", "description": "制約条件のリスト" } }, "type": "object", "required": [ "dense_objective", "constraints" ], "title": "Constraint mode (dense)" }, "RequestV1SolveDensePenalty": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "重複解をレスポンスに含めるかどうか", "default": false }, "dense_objective": { "$ref": "#/components/schemas/DenseObjectiveV1", "description": "目的関数の密行列表現" }, "penalties": { "items": { "$ref": "#/components/schemas/PenaltyV1" }, "type": "array", "title": "Penalties", "description": "ペナルティ関数のリスト" }, "penalty_weight_calibration": { "type": "boolean", "title": "Penalty Weight Calibration", "description": "ペナルティ関数の重みを自動で調整するかどうか", "default": true } }, "type": "object", "required": [ "dense_objective", "penalties" ], "title": "PUBO mode (dense)" }, "RequestV1SolveSparseConstraint": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "重複解をレスポンスに含めるかどうか", "default": false }, "sparse_objective": { "$ref": "#/components/schemas/PolynomialV1", "description": "目的関数の多項式表現" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV1" }, "type": "array", "title": "Constraints", "description": "制約条件のリスト" } }, "type": "object", "required": [ "sparse_objective", "constraints" ], "title": "Constraint mode (sparse)" }, "RequestV1SolveSparsePenalty": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "実行時間の上限 (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "計算に使用する GPU 数。0 を指定すると、利用可能なすべての GPU を使用する", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "重複解をレスポンスに含めるかどうか", "default": false }, "sparse_objective": { "$ref": "#/components/schemas/PolynomialV1", "description": "目的関数の多項式表現" }, "penalties": { "items": { "$ref": "#/components/schemas/PenaltyV1" }, "type": "array", "title": "Penalties", "description": "ペナルティ関数のリスト" }, "penalty_weight_calibration": { "type": "boolean", "title": "Penalty Weight Calibration", "description": "ペナルティ関数の重みを自動で調整するかどうか", "default": true } }, "type": "object", "required": [ "sparse_objective", "penalties" ], "title": "PUBO mode (sparse)" }, "ResponseHealth": { "properties": { "status": { "type": "string", "title": "Status", "description": "サービスの状態" }, "version": { "type": "string", "title": "Version", "description": "サービスのバージョン" } }, "type": "object", "required": [ "status", "version" ], "title": "ResponseHealth" }, "ResponseJobsError": { "properties": { "status": { "type": "string", "const": "Error", "title": "Status", "description": "ジョブの状態" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" }, "error": { "type": "string", "title": "Error", "description": "エラーメッセージ" } }, "type": "object", "required": [ "status", "submitted_at", "error" ], "title": "ResponseJobsError" }, "ResponseJobsInProgress": { "properties": { "status": { "type": "string", "const": "InProgress", "title": "Status", "description": "ジョブの状態" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" }, "started_at": { "type": "string", "format": "date-time", "title": "Started At", "description": "ジョブが開始された日時" } }, "type": "object", "required": [ "status", "submitted_at", "started_at" ], "title": "ResponseJobsInProgress" }, "ResponseJobsNotCompleted": { "oneOf": [ { "$ref": "#/components/schemas/ResponseJobsSubmittedOrWaiting", "title": "submitted or waiting" }, { "$ref": "#/components/schemas/ResponseJobsInProgress", "title": "in progress" } ], "title": "ResponseJobsNotCompleted" }, "ResponseJobsSubmittedOrWaiting": { "properties": { "status": { "type": "string", "enum": [ "Submitted", "Waiting" ], "title": "Status", "description": "ジョブの状態" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" } }, "type": "object", "required": [ "status", "submitted_at" ], "title": "ResponseJobsSubmittedOrWaiting" }, "ResponseOnError": { "properties": { "error": { "type": "string", "title": "Error", "description": "エラーメッセージ" } }, "type": "object", "required": [ "error" ], "title": "ResponseOnError" }, "ResponseV0AsyncSolve": { "properties": { "status": { "type": "string", "const": "Submitted", "title": "Status", "description": "ジョブの状態" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" }, "location": { "type": "string", "pattern": "/v0/jobs/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "title": "Location", "description": "ジョブのステータスを確認するための URI" } }, "type": "object", "required": [ "status", "submitted_at", "location" ], "title": "ResponseV0AsyncSolve" }, "ResponseV0JobsCompleted": { "oneOf": [ { "$ref": "#/components/schemas/ResponseV0SyncSolve", "title": "completed" }, { "$ref": "#/components/schemas/ResponseJobsError", "title": "error" } ], "title": "ResponseV0JobsCompleted" }, "ResponseV0SyncSolve": { "properties": { "execution_time": { "$ref": "#/components/schemas/ExecutionTimeV0", "description": "実行時間情報 (msec)" }, "energies": { "items": { "type": "number" }, "type": "array", "title": "Energies", "description": "アニーリング結果のエネルギー値のリスト" }, "spins": { "items": { "items": { "type": "integer", "enum": [ 0, 1 ] }, "type": "array" }, "type": "array", "title": "Spins", "description": "アニーリング結果のスピン配置のリスト" }, "feasibilities": { "items": { "type": "boolean" }, "type": "array", "title": "Feasibilities", "description": "アニーリング結果のそれぞれの解が実行可能解がどうか" }, "execution_parameters": { "$ref": "#/components/schemas/ExecutionParametersV0", "description": "アニーリング実行時のパラメータの情報" }, "message": { "type": "string", "title": "Message", "description": "警告メッセージ" } }, "type": "object", "required": [ "execution_time", "energies", "spins", "feasibilities", "execution_parameters", "message" ], "title": "ResponseV0SyncSolve" }, "ResponseV1AsyncSolve": { "properties": { "status": { "type": "string", "const": "Submitted", "title": "Status", "description": "ジョブの状態" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" }, "location": { "type": "string", "pattern": "/v1/jobs/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "title": "Location", "description": "ジョブのステータスを確認するための URI" } }, "type": "object", "required": [ "status", "submitted_at", "location" ], "title": "ResponseV1AsyncSolve" }, "ResponseV1JobsCompleted": { "oneOf": [ { "$ref": "#/components/schemas/ResponseV1SyncSolve", "title": "completed" }, { "$ref": "#/components/schemas/ResponseJobsError", "title": "error" } ], "title": "ResponseV1JobsCompleted" }, "ResponseV1SyncSolve": { "properties": { "solutions": { "items": { "$ref": "#/components/schemas/Solution" }, "type": "array", "minItems": 1, "title": "Solutions", "description": "解のリスト" }, "execution_time_ms": { "type": "number", "minimum": 0, "title": "Execution Time Ms", "description": "実行時間 (msec)" }, "queue_time_ms": { "type": "number", "minimum": 0, "title": "Queue Time Ms", "description": "キュー時間 (msec)" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "ジョブが提出された日時" }, "started_at": { "type": "string", "format": "date-time", "title": "Started At", "description": "ジョブが開始された日時" }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "使用した GPU の数" }, "num_samplings": { "type": "integer", "minimum": 0, "title": "Num Samplings", "description": "サンプリング数" }, "num_flips": { "type": "integer", "minimum": 0, "title": "Num Flips", "description": "フリップ数" }, "warnings": { "items": { "type": "string" }, "type": "array", "title": "Warnings", "description": "警告のリスト" }, "version": { "type": "string", "pattern": "(^\\d+\\.\\d+\\.\\d+(\\-.*)?(\\+.*)?$)", "title": "Version", "description": "実行した Amplify AE のバージョン情報" } }, "type": "object", "required": [ "solutions", "execution_time_ms", "queue_time_ms", "submitted_at", "started_at", "num_gpus", "num_samplings", "num_flips", "warnings", "version" ], "title": "ResponseV1SyncSolve" }, "Solution": { "properties": { "time_stamp_ms": { "type": "number", "minimum": 0, "title": "Time Stamp Ms", "description": "解が得られた時刻 (msec)" }, "objective": { "type": "number", "title": "Objective", "description": "目的関数の値" }, "values": { "items": { "type": "integer", "enum": [ 0, 1 ] }, "type": "array", "title": "Values", "description": "変数の値" }, "status": { "type": "string", "enum": [ "Infeasible", "Feasible", "Optimal" ], "title": "Status", "description": "解の状態" } }, "type": "object", "required": [ "time_stamp_ms", "objective", "values", "status" ], "title": "Solution" }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [ { "type": "string" }, { "type": "integer" } ] }, "type": "array", "title": "Location" }, "msg": { "type": "string", "title": "Message" }, "type": { "type": "string", "title": "Error Type" }, "input": { "title": "Input" }, "ctx": { "type": "object", "title": "Context" } }, "type": "object", "required": [ "loc", "msg", "type" ], "title": "ValidationError" } } } } ``` --- # Amplify Quantum Amplify SDK では量子コンピュータを利用した組合せ最適化計算を研究・検証するための機能を提供しています。 **🔱️ 複数のデバイスとアルゴリズムに対応** IBM Quantum, Amazon Braket等で提供されている量子コンピュータを含む数多くのデバイス及び複数の量子アルゴリズムに対応しており、デバイス・アルゴリズム間の比較が簡単です。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#multiple-solvers) **🦖 パワフルなインターフェース** 量子コンピュータをAmplify SDK のパワフルなインターフェースから利用できます。 直感的な定式化から量子回路への変換、量子コンピュータを用いた求解まで一気通貫にサポートします。 [Learn more »](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md#easy-to-use) [Amplify SDK のより詳しい特徴はこちら](https://amplify.fixstars.com/ja/docs/amplify/v1/features.md) ## 量子コンピュータとは 量子コンピュータは、量子力学の原理に基づいて情報を処理する計算機です。古典コンピュータが $0$ または $1$ のいずれかの値を取る「ビット」を情報の基本単位とするのに対し、量子コンピュータでは $0$ と $1$ の重ね合わせを取り得る「量子ビット (qubit)」を基本単位とします。この重ね合わせの利用により、古典コンピュータでは困難な問題を効率的に扱える可能性があるとして注目されています。 こうした量子コンピュータの性質を活用した**量子アルゴリズム**によって、組合せ最適化計算ができることが知られています。このクラスのアルゴリズムは、量子コンピュータで量子回路の実行・測定を行い、その結果を古典コンピュータ側で最適化に用いるという役割分担を取り、現在の量子コンピュータ (NISQ デバイス) でも現実的に動作することを目指した手法として研究・開発が進められています。 ## 量子コンピュータによる最適化 Amplify SDK の拡張パッケージである Amplify Quantum を利用することで量子コンピュータを使った組合せ最適化計算が実行できます。 > [!WARNING] > > **注意** > > 量子アニーリングマシンを使った組合せ最適化計算については、[D-Wave Systems](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md)を参照して下さい。 Amplify Quantum では、[`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を呼び出すだけで、モデルから量子回路への変換・古典最適化ループ・バックエンドとの通信までを自動で実行します。 対応している複数の量子コンピュータと複数の量子アルゴリズムを自由に組み合わせて簡単に最適化計算を実行できます。 以下は [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md) を実行する場合の Amplify Quantum 内部の動作です。 数理最適化モデルから量子回路への変換と古典最適化ループを担当する**アルゴリズムクラス**と、量子コンピュータまたはシミュレータとの通信による量子回路実行を担当する**クライアントクラス**が協調してローカルのPython環境で最適化を実行します。 ```mermaid sequenceDiagram box rgba(90, 100, 120, 0.20) Amplify Quantum 内 participant Solve as solve() participant Algo as アルゴリズムクラス(QAOA) participant Client as クライアントクラス end participant Backend as 量子コンピュータ / シミュレータ Solve->>Algo: 数理最適化モデル Algo->>Algo: 量子回路 への変換 loop 収束するまで繰り返し Algo->>Algo: パラメータ θ の更新 (古典最適化) Algo->>Client: θ に対応する回路 Client->>Backend: 量子回路実行 (CloudAPI / ローカル) Backend-->>Client: サンプリング結果 Client-->>Algo: 測定結果 (イジング列, 出現回数) end Algo-->>Solve: 最適解 ``` ### 対応デバイス 以下の量子コンピュータおよびシミュレータを利用できます。クライアントを差し替えるだけで実行デバイスを切り替え可能です。 #### 量子コンピュータプロバイダ IBM Quantum 超伝導方式 AQT イオントラップ方式 IonQ イオントラップ方式 \* IQM 超伝導方式 Rigetti 超伝導方式 QUDORA イオントラップ方式 \*\* #### 量子回路シミュレータ ユーザーのローカルマシンで動作するシミュレータと、クラウドサービスとして提供されているシミュレータの両方に対応しています。 Qulacs Simulator ローカル Qiskit Aer Simulator ローカル Amazon Braket Simulator ローカル / クラウド #### その他 OQTOPUS Cloud \*\*\* 量子コンピューティング プラットフォーム 各クライアントの認証・パラメータ設定の詳細は [対応デバイス一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/index.md) を参照してください。 \* : 量子コンピュータ実機だけでなく、クラウドシミュレータも利用できます。 \*\* : クラウドエミュレータのみ利用できます。 \*\*\* : 産総研 ABCI-Q で提供される富士通株式会社製の量子コンピュータ「システムF」を含みます。 ### 対応アルゴリズム 以下の量子最適化アルゴリズムを利用できます。利用するクライアントクラスの初期化時にアルゴリズムを指定します。 アルゴリズムごとに対応している問題の次数や制約条件が変わります。 QAOA 任意次数のイジング多項式 (制約なし) 制約付き QAOA 任意次数のイジング多項式 + N-HOT 制約 Recursive QAOA 任意次数のイジング多項式 (制約なし) 各アルゴリズムの詳細や実行パラメータ設定については [対応アルゴリズム一覧](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/index.md) を参照してください。 --- # クイックスタート ## インストール 量子コンピュータを活用する機能は Amplify SDK のアドオンとして提供されています。利用するには次のコマンドで追加のパッケージを含めてインストールして下さい。 ```bash $ python3 -m pip install -U 'amplify[quantum]' ``` 正しくインストールされると、次のようにして量子コンピュータ利用の機能が利用できます。 ```python >>> from amplify import QAOA ``` 次の環境において動作を確認しています。 **Python バージョン** * 3.10 * 3.11 * 3.12 * 3.13 **サポート OS** * Windows 10/11 * Linux * Ubuntu 22.04/24.04/26.04, Rocky Linux 9.6/10.0 * x86_64 * macOS * ARM64 (Monterey 以降) Pythonのバージョン, OSによっては依存パッケージのインストールに失敗する可能性があります。 > [!WARNING] > > **注意** > > [Amplify SDK の動作確認済み環境](https://amplify.fixstars.com/ja/docs/amplify/v1/quickstart.md#how-to-install)とは異なり、以下の環境では動作しない可能性があります。 > > **Python バージョン** > > * 3.14 > > **サポート OS** > > * Linux > > * ARM64 > * macOS > > * x86_64 (Monterey 以降) ## 量子コンピュータでの求解 > [!WARNING] > > **注意** > > 量子アニーリングマシンを使った求解については[D-Wave Systems](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md)を参照して下さい。 クラウドサービスとして提供されている各種量子コンピュータ及びローカルシミュレータを利用して、組合せ最適化問題を解くことができます。ここでは、量子回路を実行するデバイスとして、ローカルシミュレータである[Qiskit Aer Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aer.md)と量子最適化アルゴリズムである[QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md)を使います。 ### 1. 組合せ最適化モデルの作成 サンプル問題として次を考えます。Amplify SDKによる定式化の説明は[Amplify SDK クイックスタート](https://amplify.fixstars.com/ja/docs/amplify/v1/quickstart.md#run-sample-code)を参照してください。 **Sample QUBO Problem** **目的関数** $$ \text{minimize:} \quad f = q_0 q_1 + q_0 - q_1 + 1 $$ **決定変数** $$ q_0, q_1 \in \{0, 1\} $$ **制約条件** $$ \text{None} $$ ```pycon >>> from amplify import Model, VariableGenerator >>> g = VariableGenerator() # 決定変数のジェネレータを作成 >>> q = g.array("Binary", 2) # 決定変数を定義 >>> f = q[0] * q[1] + q[0] - q[1] + 1 # 目的関数を定義 >>> model = Model(f) # モデルを作成 ``` ### 2. ソルバークライアントの作成 今回は回路の実行に Qiskit Aer Simulator を使用して QAOA による最適化を行うため、Qiskit Aer Simulatorのクライアントクラス ([`AerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient))と QAOA のアルゴリズムクラス ([`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)) を利用してソルバークライアントを作成します。 ```pycon >>> from amplify import QAOA, AerClient >>> client = AerClient(QAOA) # QAOA と Qiskit Aer Simulator の組み合わせを選択 ``` 加えて、QAOAの回路の深さを 2 、最適化ステップ毎の測定回数を 1000 にそれぞれ設定します。 ```pycon >>> client.parameters.reps = 2 # QAOAのAnsatz回路の深さを 2 に設定 >>> client.parameters.shots = 1000 # QAOAの各最適化ステップにおける測定回数を 1000 に設定 ``` 他のクライアント同様に [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を用いてソルバーを実行し、QAOAによる最適化を行えます。 ```pycon >>> from amplify import solve >>> result = solve(model, client) # QAOA を実行 ``` ### 3.結果の確認 実行結果は [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスのインスタンスとして返されます。このインスタンスにはソルバーを実行した結果や行われたモデルの変換情報などが含まれます。[`best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) プロパティを呼び出すことで得られた解のうち最も良い解を取得できます。結果の取得のより詳細については[7. 組合せ最適化問題の求解 - 結果の取得](https://amplify.fixstars.com/ja/docs/amplify/v1/solve.md#solver-result)を参照してください。 ```pycon >>> result.best.objective # 目的関数の値 0.0 >>> result.best.values # 変数の値 Values({Poly(q_0): 0, Poly(q_1): 1}) ``` **量子回路の取得**: 古典最適化の各ステップで実行された量子回路は [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) 経由で取得できます。 ```python >>> # サンプリングに利用した量子回路を表示 >>> print(result.client_result.history[0].sampling_meta.circuit) ... ``` クライアントによって回路オブジェクトの型は異なります。AerClientでは [`qiskit.circuit.QuantumCircuit`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit)になります。詳細は[各クライアントのページ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md)を参照して下さい。 **最終測定の結果の取得**: 最適化されたパラメータ $\boldsymbol{\theta}^{\textup{opt}}$ で実施された最終測定の結果は [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) で取得できます。各要素は「イジング列 ($\{-1, 1\}$ 値) と出現回数のタプル」であり、出現回数が多いイジング列ほど最適解の有力な候補です。 ```python >>> # 最適パラメータでの測定結果を出現回数の降順で表示 >>> for ising_seq, freq in sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True): >>> print(f"イジング列: {ising_seq}, 出現回数: {freq}") ``` イジング列を元の決定変数配列に変換する方法や分布の解釈については、[最良パラメータでの測定結果](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-best-count) を参照して下さい。 ## 次のステップ 量子コンピュータへの接続方法の詳細は[量子コンピュータ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md)を参照して下さい。 各アルゴリズムでの求解、詳細な結果の取得については[QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md), [Recursive QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md)を参照して下さい。 --- # 対応デバイス一覧 Amplify SDK で対応している量子コンピュータ及びそのシミュレータの一覧を示します。どのクライアントも共通のインターフェースで利用でき、[対応アルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/index.md) を初期化時に指定するだけで実行する最適化手法を切り替え可能です。 クライアントの使い方や認証手続きについては[量子コンピュータ](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md)、もしくは各クライアントのページを参照して下さい。 * **ローカルシミュレータ** (登録不要): ユーザーのマシンで量子回路を評価します。 * [Qulacs Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qulacs.md) — [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) * [Qiskit Aer Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aer.md) — [`AerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) * [Amazon Braket Simulator](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aws.md) — [`BraketSimulatorClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) (ローカル/クラウド両対応) * **クラウド QPU**: 各ベンダーの量子コンピュータを利用します。各ベンダーへのアカウント契約・API 認証が必要です。 * [IBM Quantum](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ibm.md) — [`IBMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) * [AQT](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/aqt.md) — [`AQTClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) * [IonQ](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/ionq.md) — [`IonQClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) * [IQM](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/iqm.md) — [`IQMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) * [Rigetti](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/rigetti.md) — [`RigettiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) * [QUDORA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/qudora.md) — [`QUDORAClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) * [OQTOPUS Cloud](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/samplers/oqtopus.md) — [`OqtopusClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) > [!TIP] > > **ヒント** > > 量子アニーリングマシンについては[D-Wave Systems](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/dwave.md)を参照して下さい。 --- # IBM Quantum [IBM Quantum](https://quantum.cloud.ibm.com/)のQPUを回路の評価に利用します。 [`IBMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient)として利用できます。 > [!NOTE] > > **注釈** > > 利用には自身の IBM Cloud アカウントで取得した IBM Quantum API キーが必要です。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.IBMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・超伝導量子ビット | | API 方式 | REST API ([IBM Quantum](https://quantum.cloud.ibm.com/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.token) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | IBM Cloud APIキー。[QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) の認証に使用します。 | | [`url`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.url) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) の接続先 URL | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | IBM Quantum の回路を実行するデバイス名。デフォルト: [least_busy()](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#least_busy) により自動選択 | | [`channel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.channel) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) のチャンネル。`"ibm_quantum_platform"`, `"ibm_cloud"`, `"local"` 等 | | [`proxy`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.proxy) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) との接続に用いるプロキシサーバー | | [`verify`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.verify) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`None`](https://docs.python.org/3/library/constants.html#None) | サーバーの TLS 証明書を検証するかどうか | | [`qiskit_pass_manager`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.qiskit_pass_manager) | [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) | [`EllipsisType`](https://docs.python.org/3/library/types.html#types.EllipsisType) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路のトランスパイルに使用する Qiskit の [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager)。 デフォルト (`...`) では [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager) によって自動生成されます。 [`None`](https://docs.python.org/3/library/constants.html#None) を指定するとトランスパイルをスキップします。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`QiskitJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.job_id # ジョブ ID meta.circuit # 実行した Qiskit 回路オブジェクト meta.transpiled_circuit # トランスパイル後の回路 (トランスパイルされなかった場合は None) meta.metadata # ジョブの結果から得られる生のメタデータ meta.metrics # ジョブの結果から得られる実行時間などのメトリクスデータ ``` **設定例**: ```python from amplify import QAOA, IBMClient # クライアントの作成 client = IBMClient(QAOA) # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 実行するデバイスを指定 client.device = "ibm_fez" # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # Qiskit Aer Simulator [Qiskit Aer Simulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html)を回路の評価に利用します。 [`AerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient)として利用できます。 > [!TIP] > > **Tip** > > 事前準備不要で利用できます。 > > 自身の IBM Cloud アカウントで取得した IBM Quantum API キーを設定すれば IBM Quantum 実機を模倣したノイズモデルも利用できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.AerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・シミュレータ | | API 方式 | ローカルシミュレーション ([Qiskit Aer](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: 以下のアトリビュートとメソッドを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Aer Simulator の動作するデバイス。`"CPU"`, `"GPU"`, `"Thrust"` のいずれか。デフォルト: `"CPU"`。 詳細は [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) を参照してください。 | | [`method`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.method) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | シミュレーション手法。`"automatic"`, `"statevector"`, `"density_matrix"` 等。デフォルト: `"automatic"`。 詳細は [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) を参照してください。 | | [`qiskit_pass_manager`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.qiskit_pass_manager) | [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) | [`EllipsisType`](https://docs.python.org/3/library/types.html#types.EllipsisType) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路のトランスパイルに使用する Qiskit の [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager)。 デフォルト (`...`) では [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager) によって自動生成されます。 [`None`](https://docs.python.org/3/library/constants.html#None) を指定するとトランスパイルをスキップします。 | | [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.token) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | IBM Quantum APIキー。設定することでIBM Quantum のノイズモデルをダウンロードして利用できます。 | | [`url`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.url) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) の接続先 URL | | [`proxy`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.proxy) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) との接続に用いるプロキシサーバー | | [`verify`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.verify) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | [`None`](https://docs.python.org/3/library/constants.html#None) | サーバーの TLS 証明書を検証するかどうか | | [`noise_model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.noise_model) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | AerSimulatorで模倣する IBM Quantum のデバイス名。 [`None`](https://docs.python.org/3/library/constants.html#None) であればノイズ無しのシミュレータとして動作します。 設定可能な名前は [FakeProviderForBackendV2](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/fake-provider-fake-provider-for-backend-v2) からバックエンドを取得可能な名前です。 有効な `token` が設定されている場合は追加で [QiskitRuntimeService.backend()](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#backend) から取得可能な名前も利用可能です。 | | [`channel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.channel) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) のチャンネル。`"ibm_quantum_platform"`, `"ibm_cloud"`, `"local"` 等 | | メソッド | 引数 | 返却型 | 詳細 | | --- | --- | --- | --- | | [`get_options()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.get_options) | | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict)[[`str`](https://docs.python.org/3/library/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | `set_options` で明示的に設定された Aer Simulator のオプションを取得します。 | | [`set_options()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.set_options) | 任意のキーワード引数 | | Aer Simulator の実行オプションを設定します。 設定可能なオプションは [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) のドキュメントを参照してください。 例: `seed_simulator`, `noise_model`, `precision`, `fusion_enable` 等 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`QiskitJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.job_id # ジョブ ID meta.circuit # 実行した Qiskit 回路オブジェクト meta.transpiled_circuit # トランスパイル後の回路 (トランスパイルされなかった場合は None) meta.metadata # ジョブの結果から得られる生のメタデータ meta.metrics # ジョブの結果から得られる実行時間などのメトリクスデータ ``` **設定例**: ```python from amplify import QAOA, AerClient # クライアントの作成 client = AerClient(QAOA) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 # ノイズモデルを利用する場合 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.noise_model = "fake_fez" # シミュレーションデバイスの設定 client.device = "CPU" client.method = "automatic" ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() '0.17.2' ``` Aer Simulator のオプションを確認・設定: ```python >>> client.get_options() {'device': 'CPU', 'method': 'automatic'} >>> client.set_options(seed_simulator=42) >>> client.get_options() {'seed_simulator': 42, 'device': 'CPU', 'method': 'automatic'} ``` --- # Qulacs Simulator [Qulacs](http://docs.qulacs.org/) を回路の評価に利用するローカルシミュレータです。 [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient)として利用できます。 > [!TIP] > > **Tip** > > 事前準備不要で利用できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・シミュレータ | | API 方式 | ローカルシミュレーション ([Qulacs](http://docs.qulacs.org/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: 固有のアトリビュート・メソッドはありません。 **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`QulacsJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した Qulacs 回路オブジェクト ``` **設定例**: ```python from amplify import QAOA, QulacsClient # クライアントの作成 client = QulacsClient(QAOA) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # Amazon Braket Simulator [Amazon Braket](https://aws.amazon.com/braket/) のシミュレータを回路の評価に利用します。ローカルシミュレータとクラウドシミュレータの両方をサポートします。 [`BraketSimulatorClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient)として利用できます。 > [!TIP] > > **Tip** > > 事前準備不要で利用できます。 > > 自身の AWS アカウントでの認証を行うことで、クラウドシミュレータ (`SV1`, `DM1`) も利用できます。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.BraketSimulatorClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・シミュレータ | | API 方式 | ローカルシミュレーション / REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用するシミュレータ名またはクラウドシミュレータのデバイス ARN。デフォルト: `"braket_sv"` ローカルシミュレータ: * [braket_sv](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-sv) (状態ベクトル) * [braket_dm](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-dm) (密度行列) クラウドシミュレータ: * [SV1](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-sv1) (状態ベクトル) * [DM1](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-dm1) (密度行列) | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient.provider) | [`braket.aws.aws_session.AwsSession`](https://amazon-braket-sdk-python.readthedocs.io/en/stable/_apidoc/braket.aws.aws_session.html#braket.aws.aws_session.AwsSession) | [`None`](https://docs.python.org/3/library/constants.html#None) | デバイスに接続するためのプロバイダを指定します。現在は [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) のみがサポートされています。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト meta.metadata # Amazon Braket タスクメタデータ (task_id, created_at, ended_at) ``` **設定例**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, BraketSimulatorClient # ローカルシミュレータを使う場合 client = BraketSimulatorClient(QAOA) client.device = "braket_sv" # クラウドシミュレータを使う場合 client = BraketSimulatorClient(QAOA, device="SV1") boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # AQT [AQT (Alpine Quantum Technologies)](https://www.aqt.eu/) のイオントラップ型量子コンピュータを [Amazon Braket](https://aws.amazon.com/braket/) 経由で回路の評価に利用します。 > [!NOTE] > > **注釈** > > 利用には自身の AWS アカウントでの認証が必要です。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.AQTClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・イオントラップ | | API 方式 | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する [AQT デバイス](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html)名またはデバイス ARN。デフォルト: `"IbexQ1"` | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient.provider) | [`braket.aws.aws_session.AwsSession`](https://amazon-braket-sdk-python.readthedocs.io/en/stable/_apidoc/braket.aws.aws_session.html#braket.aws.aws_session.AwsSession) | [`None`](https://docs.python.org/3/library/constants.html#None) | デバイスに接続するためのプロバイダを指定します。現在は [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) のみがサポートされています。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト meta.metadata # Amazon Braket タスクメタデータ (task_id, created_at, ended_at) ``` **設定例**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, AQTClient # クライアントの作成 client = AQTClient(QAOA) # デバイスを指定 client.device = "Ibex-Q1" # AWS 認証の設定 (AWS プロファイルから AwsSession を構築) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # IonQ [IonQ](https://ionq.com/) のイオントラップ型量子コンピュータを回路の評価に利用します。 [`IonQClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) として利用できます。 > [!NOTE] > > **注釈** > > IonQ の利用方法として以下の 2 つの方法があります。 > > 1. API トークンを使用する方法: [Fixstars Amplify アカウント](https://amplify.fixstars.com/user/token)または自身の IonQ のアカウントで API トークンを取得してください。 > 2. [Amazon Braket](https://aws.amazon.com/braket/) 経由で使用する方法: 自身の AWS アカウントの認証情報を用意してください。また、認証と通信に Python 3.11 以降が必要な場合があります。 > [!TIP] > > **ヒント** > > Amplify Quantum v1.2 で [`IonQClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) の API トークン認証機能をサポートしました。 > ご利用中のパッケージのバージョンが古い場合は、以下のコマンドを実行して最新版にアップデートしてください。 > > ```bash > $ pip install -U 'amplify[quantum]' > ``` **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.IonQClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・イオントラップ | | API 方式 | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートとメソッドを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.token) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 認証に利用する API トークン | | [`url`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.url) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 接続先 URL | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する [IonQ デバイス](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html)名またはデバイス ARN。デフォルト: `"Forte1"` | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.provider) | [`braket.aws.aws_session.AwsSession`](https://amazon-braket-sdk-python.readthedocs.io/en/stable/_apidoc/braket.aws.aws_session.html#braket.aws.aws_session.AwsSession) | [`None`](https://docs.python.org/3/library/constants.html#None) | デバイスに接続するためのプロバイダを指定します。現在は [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) のみがサポートされています。 | | メソッド | 戻り値のデータ型 | 詳細 | | --- | --- | --- | | [`get_options()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.get_options) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict)[[`str`](https://docs.python.org/3/library/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | `set_options` で明示的に設定された実行オプションを取得します。 | | [`set_options()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.set_options) | [`None`](https://docs.python.org/3/library/constants.html#None) | 実行オプションを設定します。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト ``` **設定例**: ```python from amplify import QAOA, IonQClient # クライアントの作成 client = IonQClient(QAOA) # シミュレータを指定 (シミュレータは API トークン経由でのみ利用可能です) client.device = "simulator" # client.set_options(noise_model="forte-1") # シミュレータのノイズモデルの指定 # QPU を指定 (QPU は有償トークンまたは Amazon Braket 経由で利用可能です) # client.device = "qpu.forte-1" # Forte-1 の QPU を使用する場合 # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` Amazon Braket を使用する場合は、API トークンを設定する部分を以下のように変更してください。 ```python import boto32 from braket.aws import AwsSession session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=session) ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # IQM [IQM](https://www.meetiqm.com/) の超伝導型量子コンピュータを [Amazon Braket](https://aws.amazon.com/braket/) 経由で回路の評価に利用します。 [`IQMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient)として利用できます。 > [!NOTE] > > **注釈** > > 利用には自身の AWS アカウントでの認証が必要です。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.IQMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・超伝導量子ビット | | API 方式 | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する [IQM デバイス](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html)名またはデバイス ARN。デフォルト: `"Garnet"` | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient.provider) | [`braket.aws.aws_session.AwsSession`](https://amazon-braket-sdk-python.readthedocs.io/en/stable/_apidoc/braket.aws.aws_session.html#braket.aws.aws_session.AwsSession) | [`None`](https://docs.python.org/3/library/constants.html#None) | デバイスに接続するためのプロバイダを指定します。現在は [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) のみがサポートされています。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト meta.metadata # Amazon Braket タスクメタデータ (task_id, created_at, ended_at) ``` **設定例**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, IQMClient # クライアントの作成 client = IQMClient(QAOA) # デバイスを指定 client.device = "Garnet" # AWS 認証の設定 (AWS プロファイルから AwsSession を構築) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # Rigetti [Rigetti](https://www.rigetti.com/) の超伝導型量子コンピュータを [Amazon Braket](https://aws.amazon.com/braket/) 経由で回路の評価に利用します。 [`RigettiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient)として利用できます。 > [!NOTE] > > **注釈** > > 利用には自身の AWS アカウントでの認証が必要です。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.RigettiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・超伝導量子ビット | | API 方式 | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | 使用する [Rigetti デバイス](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html)名またはデバイス ARN。デフォルト: `"Cepheus1108Q"` | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient.provider) | [`braket.aws.aws_session.AwsSession`](https://amazon-braket-sdk-python.readthedocs.io/en/stable/_apidoc/braket.aws.aws_session.html#braket.aws.aws_session.AwsSession) | [`None`](https://docs.python.org/3/library/constants.html#None) | デバイスに接続するためのプロバイダを指定します。現在は [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) のみがサポートされています。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。[`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta)が利用されます。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト meta.metadata # Amazon Braket タスクメタデータ (task_id, created_at, ended_at) ``` **設定例**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, RigettiClient # クライアントの作成 client = RigettiClient(QAOA) # デバイスを指定 client.device = "Cepheus-1-108Q" # AWS 認証の設定 (AWS プロファイルから AwsSession を構築) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # QUDORA [QUDORA](https://qudora.com/) のイオントラップ型量子コンピュータ及びそのクラウドシミュレータを回路の評価に利用します。 [`QUDORAClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) として利用できます。 > [!TIP] > > **ヒント** > > [`QUDORAClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) は Amplify Quantum v1.1 で追加されました。 > ご利用中のパッケージのバージョンが古い場合は、以下のコマンドを実行して最新版にアップデートしてください。 > > ```bash > $ pip install -U 'amplify[quantum]' > ``` > [!NOTE] > > **注釈** > > 利用には API トークンが必要です。 > > Fixstars Amplify の[ユーザ登録](https://amplify.fixstars.com/register)を行い無償のお試し API トークンを入手するか、自身の QUDORA Cloud のアカウントで API トークンを入手してください。 **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.QUDORAClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型・イオントラップ | | API 方式 | REST API (JSON) | | API リファレンス | [📖 API Reference](https://api.qudora.com/docs) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: 以下のアトリビュートとメソッドを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.token) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 認証に利用する API トークン | | [`url`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.url) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 接続先 URL | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路を実行する QUDORA のデバイス名。デフォルト: [`"Qamelion"`](https://qudora.com/news/qudora-launches-qamelion-quantum-emulator-with-adaptive-noise-modeling/) | | [`qiskit_pass_manager`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.qiskit_pass_manager) | [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) | [`EllipsisType`](https://docs.python.org/3/library/types.html#types.EllipsisType) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路のトランスパイルに使用する Qiskit の [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager)。 デフォルト (`...`) では [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager) によって自動生成されます。 [`None`](https://docs.python.org/3/library/constants.html#None) を指定するとトランスパイルをスキップします。 | | メソッド | 戻り値のデータ型 | 詳細 | | --- | --- | --- | | [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.solve) | アルゴリズムに依存 | ソルバーの API を直接実行します。通常は [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数を使用してください。 | | [`version()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.version) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | バックエンドのバージョン情報を取得します。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した回路オブジェクト ``` **設定例**: ```python from amplify import QAOA, QUDORAClient # クライアントの作成 client = QUDORAClient(QAOA) # デバイスを指定 client.device = "Qamelion" # Qamelion エミュレータを使用する場合 (デフォルト) # API トークンを設定 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョンを取得: ```python >>> client.version() ``` --- # OQTOPUS Cloud [OQTOPUS Cloud](https://oqtopus-cloud.readthedocs.io) 経由で利用可能なクラウド量子コンピュータ及びシミュレータを回路の評価に利用します。 [`OqtopusClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) として利用できます。 > [!NOTE] > > **注釈** > > `quri-parts-oqtopus==1.0.3` で通信できる OQTOPUS Cloud にのみ対応しています。 > > 利用には OQTOPUS Cloud の API トークンと接続先 URL が必要です。 > [!TIP] > > **ヒント** > > [`OqtopusClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) は Amplify Quantum v1.3 で追加されました。 > ご利用中のパッケージのバージョンが古い場合は、以下のコマンドを実行して最新版にアップデートしてください。 > > ```bash > $ pip install -U 'amplify[quantum]' > ``` **ソルバー仕様**: | | | | --- | --- | | クライアントクラス | [`amplify.OqtopusClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) | | [実行パラメータ](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.parameters) | アルゴリズムに依存 | | [実行結果](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | [実行時間](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | アルゴリズムに依存 | | 量子コンピュータ方式 | ゲート型 | | API 方式 | REST API ([OQTOPUS Cloud](https://oqtopus-cloud.readthedocs.io)) | 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 **クライアントクラス**: [クライアントクラスの共通インターフェース](https://amplify.fixstars.com/ja/docs/amplify/v1/solvers.md#client-common-interface) に加えて以下のアトリビュートを持ちます。 | アトリビュート | データ型 | 詳細 | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.token) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS の API トークン。 | | [`url`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.url) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS サービスの接続先 URL。 | | [`proxy`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.proxy) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 接続時に利用するプロキシサーバー URL。 | | [`provider`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.provider) | `quri_parts_oqtopus.backend.OqtopusConfig` | [`None`](https://docs.python.org/3/library/constants.html#None) | `token` / `url` / `proxy` 属性の代わりに `quri_parts_oqtopus.backend.OqtopusConfig` を利用して認証情報を設定します。`provider` 属性の設定が最も優先されます。 | | [`device`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路を実行する OQTOPUS のデバイス名。 [`None`](https://docs.python.org/3/library/constants.html#None) の場合、回路の量子ビット数を満たす利用可能なデバイスの中から自動選択されます。 | | [`qiskit_pass_manager`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.qiskit_pass_manager) | [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) | [`EllipsisType`](https://docs.python.org/3/library/types.html#types.EllipsisType) | [`None`](https://docs.python.org/3/library/constants.html#None) | 回路のトランスパイルに使用する Qiskit の [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager)。 デフォルト (`...`) では [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager) によって自動生成されます。 [`None`](https://docs.python.org/3/library/constants.html#None) を指定するとトランスパイルをスキップします。 | | [`name`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.name) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に投入するジョブに付与する名前。 | | [`description`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.description) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に投入するジョブに付与する説明文。 | | [`transpiler_info`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.transpiler_info) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に転送されるトランスパイラ情報。 | | [`simulator_info`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.simulator_info) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に転送されるシミュレータ情報。 | | [`mitigation_info`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.mitigation_info) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に転送される誤り抑制 (error mitigation) の設定。 | | [`job_type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.job_type) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | [`None`](https://docs.python.org/3/library/constants.html#None) | OQTOPUS に転送されるジョブタイプ。 | **バックエンド固有のメタ情報**: [QAOAのsampling_meta](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta)などで取得できるサンプリング時の詳細情報です。 ```python meta = client_result.history[0].sampling_meta meta.circuit # 実行した Qiskit 回路オブジェクト (トランスパイル前) meta.transpiled_circuit # トランスパイル後の回路 (トランスパイルされなかった場合は None) ``` **設定例**: ```python from amplify import QAOA, OqtopusClient # クライアントの作成 client = OqtopusClient(QAOA) # 接続先 URL と API トークンを設定 client.url = "" client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # QAOAのパラメータを設定 client.parameters.reps = 1 client.parameters.shots = 100 ``` `quri_parts_oqtopus.backend.OqtopusConfig` を直接渡すこともできます。この場合 `provider` の値のみから認証を行います。 ```python from quri_parts_oqtopus.backend import OqtopusConfig client = OqtopusClient(QAOA) client.provider = OqtopusConfig.from_file() ``` **実行例**: ```python from amplify import Model, VariableGenerator, solve # 決定変数と目的関数を定義 g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # モデルを作成 model = Model(f) # ソルバーを実行 result = solve(model, client) ``` バックエンドのバージョン ([quri-parts-oqtopus](https://pypi.org/project/quri-parts-oqtopus/) のバージョン) を取得: ```python >>> client.version() ``` --- # 対応アルゴリズム一覧 Amplify SDK で対応している量子コンピュータを利用するアルゴリズムの一覧を示します。量子コンピュータを扱うクライアントは、初期化時にここで挙げるアルゴリズムクラスを指定して使用します。 * [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md): [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) クラス。深さ $p$ のパラメトリック量子回路 (Ansatz) の最適化と測定を繰り返し、最良パラメータでの測定結果から解を得ます。`QAOAType` の設定により、標準的な Ansatz と N-HOT 制約を考慮した Ansatz を切り替えられます。 * [Recursive QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md): [`RQAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) クラス。浅い QAOA を繰り返し、各ステップで変数を 1 つずつ消去して問題サイズを削減します。変数数が十分小さくなった時点で総当たりにより厳密解を求めます。 各ページでは、パラメータの設定、求解結果の詳細な情報の取得、活用方法について説明します。量子最適化アルゴリズムそのものの数理的な枠組みは [アルゴリズムの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/index.md) を参照してください。 > [!NOTE] > > **注釈** > > 他のアルゴリズムも今後追加予定です。 --- # QAOA / 制約付き QAOA QAOA (Quantum Approximate Optimization Algorithm) は量子コンピュータによる量子回路の実行と古典最適化を交互に繰り返す量子古典ハイブリッドアルゴリズムです。イジング変数で $N$ 次多項式の目的関数の最適化問題を求解できます。 量子コンピュータを利用するクライアントでアルゴリズムに [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) を指定することで利用します。 このページでは QAOA のパラメータの設定、求解結果の詳細な情報の取得、活用方法について説明します。 アルゴリズムの詳細は[QAOA アルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md)及び[制約付き QAOA アルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)を参照して下さい。 以下は [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) を用いて QAOA を実行し、求解の実行結果を取得する例です。 ```python from amplify import QAOA, QulacsClient, VariableGenerator, Model, equal_to, solve # 決定変数の配列を生成 gen = VariableGenerator() q = gen.array("Binary", 5) # 目的関数と制約条件を作成 objective = q[0] * q[1] - q[2] constraint = equal_to(q[0] + q[1] + q[2], 1) # モデルの定義 model = Model(objective, constraint) client = QulacsClient(QAOA) result = solve(model, client) ``` ## 実行結果の評価 量子コンピュータソルバーにおいては、 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行結果である [`amplify.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスで取得できる、 [`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) 及び [`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) はソルバーとの通信・実行時間ではなく、量子コンピュータ実機/シミュレータとの通信時間・回路の実行時間に対応します。 QAOA では量子状態を `shots` 回測定してイジング列をサンプリングすることを繰り返します。 そのため、 [`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) 及び [`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) は対応する時間の全てのサンプリングにおける合計になります。 ```python result = solve(model, client) result.response_time # QPU との通信時間の合計 result.execution_time # QPU での実行時間の合計 ``` QAOAにおいて最適なパラメータで最も頻繁に観測されたイジング列が最適解の有力な候補です。 しかしながら観測回数の最も多いイジング列が最適とは限らないため、最適化過程の全ての測定においてサンプリングされたイジング列すべてを記録します。 その中から目的関数の値が最も小さくなるイジング列が [`amplify.Result.best`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) で取得できます。 ### QAOA 固有の結果 [`amplify.Result.client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) の型はアルゴリズムの型に依存し、アルゴリズム毎に異なる型で実行過程の情報を含む詳細な求解結果を返します。`QAOA`では[`amplify.QAOA.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result)が対応します。 #### QAOA Result 属性一覧 | 属性 | 型 | 説明 | | --- | --- | --- | | [`durations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.durations) | [`QAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) | 実行時間の内訳 | | [`num_execution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.num_execution) | `int` | コスト関数の総評価回数 (古典最適化のイテレーション数) | | [`optimized_cost`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_cost) | `float` | 最適化で得られた最良のコスト関数値 $C(\boldsymbol{\theta}^{\textup{opt}})$ | | [`optimized_parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_parameters) | `tuple[float, ...]` | 最適化で得られた最良のパラメータ $\boldsymbol{\theta}^{\textup{opt}}$ | | [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) | `list[tuple[list[int], int]]` | 最良パラメータでの測定結果 (イジング列, 出現回数) のリスト | | [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) | `Sequence[`[`QAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem)`]` | パラメータ最適化の各ステップの履歴 | #### [`QAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) (実行時間の内訳) [`durations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.durations) は QAOA の各フェーズにかかった時間の内訳を提供します。 ```python d = result.client_result.durations result.total_time # amplify.solveにかかった時間 d.total_time # QAOA 全体の経過時間 d.total_response_time # バックエンド との通信時間の合計 d.total_execution_time # バックエンド での実行時間の合計 d.classical_processing_time # 古典最適化にかかった時間 (= total_time - total_response_time) ``` 以下の図は、QAOA 実行中の各メトリクスの関係を示しています。古典最適化のイテレーション毎に量子コンピュータでのサンプリングを実行して解を抽出します。 [![../../_images/sampling_timing.ja.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/sampling_timing.ja.svg)](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/sampling_timing.ja.svg) * [`total_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_time): パラメータ最適化と最終測定を含む全体の経過時間 * [`total_response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_response_time): 全ステップにおける 量子コンピュータ実機/シミュレータとの通信にかかった時間の合計。キューの待ち時間などを含みます * [`total_execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_execution_time): 量子コンピュータ実機/シミュレータが実際に回路を実行していた時間の合計 * [`classical_processing_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.classical_processing_time): 古典最適化アルゴリズム (scipy.optimize.minimize 等) が走っていた時間の合計。`total_time - total_response_time` で算出されます #### [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) (QAOA 最適化の履歴) [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) はパラメータ最適化の各ステップ ([`QAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem)) のリストです。 古典最適化でコスト関数を評価するたびに 1 エントリが追加されます。コスト関数の評価のたびに量子回路が実行されます。 ```python for step in result.client_result.history: print(step.timestamp) # QAOAの開始時刻からのこのステップの完了までの経過時間 print(step.parameters) # ステップのパラメータ値 θ print(step.objective) # コスト関数値 C(θ) print(step.counts) # 測定結果 (イジング列, 出現回数) print(step.sampling_durations) # サンプリングにかかった時間 print(step.sampling_meta) # バックエンド固有のメタ情報 ``` #### [`sampling_meta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem.sampling_meta) (バックエンド固有のメタ情報) [`sampling_meta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem.sampling_meta) の内容はバックエンドによって異なります。 **Qiskit ベース (AerClient / IBMClient) の場合**: ```python meta = result.client_result.history[0].sampling_meta meta.job_id # ジョブ ID meta.circuit # 実行した Qiskit 回路オブジェクト ``` 詳細は各[量子コンピュータクライアントの詳細](https://amplify.fixstars.com/ja/docs/amplify/v1/clients/quantum_algorithm.md)を参照して下さい #### [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) (最良パラメータでの測定結果) [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) は最良パラメータ $\boldsymbol{\theta}^{\textup{opt}}$ での測定結果です。各要素は `(イジング列, 出現回数)` のタプルです。出現回数が多いイジング列ほど最適解の有力な候補です。 ```python for ising_seq, freq in sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True): print(f"イジング列: {ising_seq}, 出現回数: {freq}") ``` ##### optimized_counts のイジング列を変数に変換する [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) のイジング列は、内部的な量子ビットの測定値をイジング値 ($\{-1, 1\}$) で表したものです。[`amplify.Result.intermediate`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) の [`amplify.Result.ModelConversion.mapping`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) を使って元の変数配列に変換できます。 ```python result = solve(model, client) sorted_counts = sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True) for sol, freq in sorted_counts[:5]: values = q.substitute( { k: p.substitute( {v: sol[v.id] for v in result.intermediate.model.get_variables()} ) for k, p in result.intermediate.mapping.items() } ) print(f"解: {values}, 出現回数: {freq}") ``` ##### optimized_counts の分布と最適化の質 [`optimized_counts`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) の分布は、QAOA のパラメータ最適化がどの程度うまく機能したかの指標になります。 * **測定結果が少数のイジング列に集中している場合**: 量子状態が特定の解に収束しており、最適化が成功しています。最頻のイジング列が最適解の有力な候補です。 * **測定結果が多数のイジング列に分散している場合**: 量子状態が広い状態空間に広がっており、最適化が十分に進んでいません。[Ansatz回路の深さ](#qaoa-reps) を増やす、[古典最適化](#qaoa-minimize) の調整、あるいは [QAOA の種別](#qaoa-qaoatype) の変更を検討してください。 ```python bc = result.client_result.optimized_counts total = sum(count for _, count in bc) top_freq = max(count for _, count in bc) print(f"ユニークなイジング列の数: {len(bc)} / {total} shots") print(f"最頻イジング列の出現回数: {top_freq} ({100 * top_freq / total:.1f}%)") ``` ## パラメータの設定 指定したアルゴリズムのパラメータは `client.parameters` で設定します。 全てのパラメータにデフォルトの設定が与えられているため、変更なしで動作します。 | パラメータ | 型 | デフォルト | 説明 | | --- | --- | --- | --- | | [`reps`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.reps) | `int` | `10` | [Ansatz 回路の深さ](#qaoa-reps) (層数 $p$)。大きいほど表現力が増しますが、回路が深くなります | | [`shots`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.shots) | `int` | `1024` | [測定回数](#qaoa-shots)。大きいほど統計精度が上がりますが、実行時間が増えます | | [`alpha`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.alpha) | `float` | `1.0` | [コスト関数の調整](#qaoa-alpha)。小さくするほどエネルギーの小さい解を重視します。 | | [`qaoa_type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.qaoa_type) | [`QAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) | [`AUTO`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.AUTO) | [QAOA の種別](#qaoa-qaoatype)。回路と扱える次数が変わります | | [`minimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) | [`MinimizeProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol) | [`ScipyMinimize()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) | [古典最適化手法](#qaoa-minimize)。デフォルトではscipyのCOBYLAを利用します | QAOA の性能は、Ansatz 回路の構成や古典最適化の設定に大きく影響されます。ここでは、各パラメータの役割と調整のポイントを説明します。 ### Ansatz 回路の深さ (reps) `reps` は Ansatz 回路の層数 $p$ を指定します。 * 大きいほど量子状態の表現力が増し、理論上はより良い解に近づけます。 * ただし、回路が深くなると最適化するパラメータ数は `reps` に比例して増加するため、古典最適化の収束にも影響します。 * また、実機ではノイズの影響を受けやすくなります。 * デフォルト: `10` **設定例**: ```python client.parameters.reps = 5 ``` ### 測定回数 (shots) `shots` はパラメータ最適化の各ステップおよび最終的な解抽出で行う測定回数です。 * 大きいほどコスト関数の推定精度が上がり、安定した結果が得られます。 * ただし、1 回の最適化ステップあたりの実行時間, またはQPUでの実行コストを増加させます。 * デフォルト: `1024` **設定例**: ```python client.parameters.shots = 2048 ``` ### コスト関数の調整 (alpha) QAOA では通常、サンプリングされた量子状態から目的関数の期待値を計算し、これを古典最小化対象のコストとします。 デフォルトの $\alpha = 1.0$ では通常通り期待値をコストとして利用しますが、$0 < \alpha < 1.0$ を設定することで Conditional Value-at-Risk (CVaR) をコストとして利用できます。 [[1]](#id6) CVaR では、測定で得られたエネルギー値を低い順にならべ、そのうち $\text{ceil}(\alpha \times \text{shots})$ 個の平均をコストとします。 したがって $\alpha = 1.0$ では全測定結果の平均となるためCVaRは期待値と一致します。 $\alpha$ を小さくするほど低エネルギー側のサンプルを重視するため、良い解のサンプリング確率を高める方向に最適化を誘導できます。 一方、$\alpha$ に伴いコスト推定に利用するサンプル数が少なくなるため、推定精度を保つには `shots` 数を増やす必要があります。 ### QAOA の種別 (qaoa_type) `qaoa_type` は使用する QAOA Ansatz の種類を指定します。 | QAOAType | 目的関数の受理次数 | 説明 | | --- | --- | --- | | `AUTO` (デフォルト) | Ising: 任意次数 | 自動選択。制約の有無に応じて ORIGINAL または NHOT を使い分けます | | `ORIGINAL` | Ising: 任意次数 | 標準的な QAOA Ansatz を使用します | | `NHOT` | Ising: 任意次数 | N-HOT 制約(イジング変数から成る変数列に対して、ちょうど $n$ 個の変数だけが $-1$ になる制約)を考慮した Ansatz を使用します | | `AUTO_QUADRATIC` / `ORIGINAL_QUADRATIC` / `NHOT_QUADRATIC` | Ising: 2次 | 対応する各 QAOA を2 次以下の次数でのみ扱います | > [!NOTE] > > **注釈** > > `_QUADRATIC` が付くタイプでは、Amplify SDK が高次の目的関数を 2 次以下に自動で次数下げします。次数下げにより補助変数が追加され、量子ビット数が増える場合があります。 アルゴリズムの詳細は [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md) および [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) を参照してください。 **設定例**: ```python from amplify import QAOAType client.parameters.qaoa_type = QAOAType.AUTO # デフォルト ``` ### 古典最適化手法 (minimize) `minimize` はパラメータ最適化に使用する古典最適化手法を指定します。デフォルトでは [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) が使用されます。 #### ScipyMinimize [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) は `scipy.optimize.minimize` をラップした最適化手法です。 `scipy.optimize.minimize` のパラメータをオブジェクトのプロパティから渡せます。 各パラメータの詳細は[SciPyのドキュメント](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html)を参照してください。 | パラメータ | 型 | デフォルト | 説明 | | --- | --- | --- | --- | | [`method`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.method) | `str` | `"COBYLA"` | 古典最適化のアルゴリズム名 | | [`tol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.tol) | `float | None` | `None` | 収束判定の許容誤差。`None` で scipy のデフォルト | | [`x0`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.x0) | `list[float] | None` | `None` | パラメータの初期値。`None` でランダム初期化 | | [`options`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.options) | `dict | None` | `None` | scipy に渡す追加オプション (`maxiter`, `disp` など) | > [!TIP] > > **Tip** > > `method` の選択は問題や状況に依存しますが、勾配を使わない `"COBYLA"` は量子コンピュータ上の最適化でよく使われます。 **設定例**: ```python from amplify import ScipyMinimize client.parameters.minimize.method = "COBYLA" # 最適化アルゴリズム client.parameters.minimize.tol = None # 収束判定の許容誤差 client.parameters.minimize.x0 = None # パラメータの初期値 (None でランダム) client.parameters.minimize.options = {"maxiter": 100, "disp": True} ``` #### NoOpMinimize (最適化をスキップ) [`NoOpMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) は古典最適化を行わず、指定されたパラメータでそのまま測定を行います。すでに最適化済みのパラメータで再測定したい場合に使用します。最適化済みのパラメータを再利用して `shots` を増やした再測定を行うことで、統計精度を向上できます。 **設定例**: ```python from amplify import NoOpMinimize # 1回目: 通常の QAOA (パラメータ最適化 + 測定) result = solve(model, client) best_params = result.client_result.optimized_parameters # 2回目: 最適化済みパラメータで再測定 (shots を増やして精度向上) client.parameters.shots = 4096 client.parameters.minimize = NoOpMinimize(best_params) result2 = solve(model, client) ``` この場合、`result2.client_result.num_execution` は `1` になり、測定が一度だけ行われていることが確認できます。 --- [[1](#id5)] P. Kl. Barkoutsos, G. Nannicini, A. Robert, I. Tavernelli, and S. Woerner, Improving Variational Quantum Optimization using CVaR, [Quantum 4, 256 (2020)](https://doi.org/10.22331/q-2020-04-20-256). --- # Recursive QAOA QAOA をサブルーチンとして繰り返し実行し、段階的に問題サイズを縮小しながら最適解を特定する量子古典ハイブリッドアルゴリズムです。各ステップで浅い回路による QAOA の測定結果から削減する変数を決定し、問題が十分小さくなった段階で総当たりにより厳密解を求めます。通常の QAOA で課題となる回路の深さの制約を緩和し、より大規模な問題への適用を目指します。 イジング変数で $N$ 次多項式の目的関数の最適化問題を求解できます。 量子コンピュータを利用するクライアントでアルゴリズムに [`RQAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) を指定することで利用します。 このページでは RQAOA のパラメータの設定、求解結果の詳細な情報の取得、活用方法について説明します。 アルゴリズムの詳細は[RQAOAのアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md)を参照して下さい。 以下は [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) を用いて RQAOA を実行し、求解の実行結果を取得する例です。 ```python from amplify import RQAOA, QulacsClient, VariableGenerator, Model, solve # 決定変数の配列を生成 gen = VariableGenerator() q = gen.array("Binary", 5) # 目的関数を作成 objective = q[0] * q[1] - q[2] # モデルの定義 model = Model(objective) client = QulacsClient(RQAOA) result = solve(model, client) ``` > [!NOTE] > > **注釈** > > RQAOA は制約付きの問題には対応していません。制約がある場合には、ペナルティ項を導入して制約なし問題へと自動変換します。 ## 実行結果の評価 量子コンピュータソルバーにおいては、 [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) 関数の実行結果である [`amplify.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) クラスで取得できる、 [`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) 及び [`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) はソルバーとの通信・実行時間ではなく、量子コンピュータ実機/シミュレータとの通信時間・回路の実行時間に対応します。 RQAOAではサブルーチンとしてQAOAを複数回呼び出して最適化を行います。 そのため、[`amplify.Result.response_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time)及び[`amplify.Result.execution_time`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time)は対応する時間の全てのQAOAにわたる合計になります。 ```python result = solve(model, client) result.response_time # QPU との通信時間の合計 result.execution_time # QPU での実行時間の合計 ``` RQAOAにおいて最適解は縮小された問題から総当たりによってただ一つに求められます。 このとき、縮小された問題における最適解を元に復元することで縮小前の問題の解もただ一つ得られます。 そのため、[`amplify.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) にはこの解一つのみが含まれます。 ### RQAOA固有の結果 [`amplify.Result.client_result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) の型はアルゴリズムの型に依存し、アルゴリズム毎に異なる型で実行過程を含む詳細な求解結果を返します。`RQAOA`では[`amplify.RQAOA.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result)が対応します。 #### RQAOA Result 属性一覧 | 属性 | 型 | 説明 | | --- | --- | --- | | [`durations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.durations) | [`RQAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) | 実行時間の内訳 | | [`num_execution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.num_execution) | `int` | 各ステップのQAOAによるコスト関数の総評価回数 (古典最適化のイテレーション数) | | [`optimized_objective`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.optimized_objective) | `float` | RQAOAで得られた最良の目的関数値 | | [`optimized_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.optimized_solution) | `tuple[int, ...]` | RQAOAで得られた最良の解 | | [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) | `Sequence[`[`RQAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem)`]` | 各ステップのQAOAによる変数削減の履歴 | ##### [`RQAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) (実行時間の内訳) `durations` は RQAOA の各フェーズにかかった時間の内訳を提供します。 ```python d = result.client_result.durations result.total_time # amplify.solveにかかった時間 d.total_time # RQAOA 全体の経過時間 d.total_response_time # バックエンド との通信時間の合計 d.total_execution_time # バックエンド での実行時間の合計 d.classical_processing_time # 古典最適化にかかった時間 (= total_time - total_response_time) ``` #### [`history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) (RQAOA 最適化の履歴) [`amplify.RQAOA.Result.history`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) は変数削減のための各QAOAステップ ([`RQAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem)) のリストです。 ```python for step in result.client_result.history: print(step.timestamp) # RQAOAの開始時刻からこのステップの完了までの経過時間 print(step.model) # 変数削減後のこのステップでの目的関数 print(step.qaoa_result) # QAOAResult print(step.elimination_info) # このステップの結果から選ばれた変数削減情報 ``` ## パラメータの設定 | パラメータ | 型 | デフォルト | 説明 | | --- | --- | --- | --- | | [`reps`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.reps) | `int` | `10` | [Ansatz 回路の深さ](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-reps) (層数 $p$)。大きいほど表現力が増しますが、回路が深くなります | | [`shots`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.shots) | `int` | `1024` | [測定回数](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-shots)。大きいほど統計精度が上がりますが、実行時間が増えます | | [`alpha`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.alpha) | `float` | `1.0` | [コスト関数の調整](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-alpha)。小さくするほどエネルギーの小さい解を重視します。 | | [`qaoa_type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.qaoa_type) | [`RQAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) | [`ORIGINAL`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType.ORIGINAL) | [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype)。[`ORIGINAL_QUADRATIC`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType.ORIGINAL_QUADRATIC)または[`ORIGINAL`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType.ORIGINAL)から選択できます | | [`minimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.minimize) | [`MinimizeProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol) | [`ScipyMinimize()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) | [古典最適化手法](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-minimize)。デフォルトではscipyのCOBYLAを利用します | | [`min_size`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.min_size) | `int` | `2` | 変数数がこの値になるまで変数削減を試みます | | [`max_degree`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.max_degree) | `int|None` | `None` | 変数削減を行う対象の項の最大次数を制限します。Noneなら制限しません | | [`min_corr`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.min_corr) | `float` | `0` | 項の期待値の絶対値がこの値を上回る項から変数削減を行います | ### 変数削減目標サイズ (min_size) `min_size` は RQAOA で問題に含まれる変数の個数をいくつにまで削減することを目指すかを指定します。詳細は[RQAOAのアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md)を参照して下さい。 後述の`max_degree`、`min_corr`の値によっては変数を削減できない場合があり、その場合は変数の削減を中断し総当たりよる最適解の探索に移ります。 * 一度の変数削減で一つの変数を削減します。元の変数の個数との差がQAOAの実行回数になります。 * 最適解の特定に総当たりを行うため、`min_size`が大きいほど最適解の特定にかかる時間が増加します。 * デフォルト: `2` **設定例**: ```python client.parameters.min_size = 2 ``` ### 変数削減対象項 (max_degree) `max_degree` は RQAOA で変数削減の対象とする変数を選ぶ元の項の次数の制限です。詳細は[RQAOAのアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md)を参照して下さい。 * `3` 以上では変数削減に伴い問題の次数が増加する場合があることに注意が必要です。 * 目的関数に含まれる項が max_degree を下回るものしかない場合は変数削減を中断し、最適解の探索に移ります。 * デフォルト: `None` **設定例**: ```python client.parameters.max_degree = 2 ``` ### 変数削減項期待値閾値 (min_corr) `min_corr` は RQAOA で変数削減の対象とする項が満たすべき最小の期待値の制限です。詳細は[RQAOAのアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md)を参照して下さい。 * 目的関数に含まれる項の期待値の絶対値が全て min_corr を下回る場合は変数削減を中断し、最適解の探索に移ります。 * デフォルト: `0` **設定例**: ```python client.parameters.min_corr = 0 ``` --- # アルゴリズムの詳細 Amplify SDK で対応している量子最適化アルゴリズムについてその理論的な枠組みを紹介します。 各アルゴリズムのページではより詳細なアルゴリズム、及び理論について説明します。 * [QAOA のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md): 量子コンピュータと古典最適化を組み合わせて組合せ最適化問題 (PUBO) を解く代表的な変分量子アルゴリズムです。問題に対応するハミルトニアンを構成し、パラメトリック量子回路 (Ansatz) を用いてその基底状態を近似的に探索します。 * [制約付き QAOA のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md): N-HOT 制約 (ちょうど $n$ 個の変数のみが $-1$ となる等式制約) を考慮した Ansatz を用いる QAOA です。制約条件で制限された量子状態の部分空間内で最適化を行うことで、ペナルティ法に比べて効率的に制約付き問題を解けることが期待されます。 * [Recursive QAOA のアルゴリズム](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/RQAOA_algo.md): 深さの浅い QAOA を繰り返し実行し、段階的に問題の変数を削減してから最適解を特定する手法です。回路の深さを抑えながら大規模な問題への適用を目指します。 --- # QAOAのアルゴリズム 本ページでは、QAOA (Quantum Approximate Optimization Algorithm) [[1]](#id13) の数理的な枠組みを説明します。 ## QAOA が解く最適化問題 QAOA は、量子コンピュータと古典最適化を用いて組合せ最適化問題を解くアルゴリズムです。 QAOAでは Polynomial Unconstrained Binary Optimization (PUBO) と呼ばれるクラスの問題を扱います。 その名の通り、PUBO はバイナリ (binary) 変数 $x = (x_1, x_2, \ldots, x_n) \quad (x_i \in \{0,1\},\ i=1,2,\ldots,n)$ の多項式 (polynomial) で表される目的関数を、制約条件無し (unconstrained) で最小化する (optimization) 問題です。 形式的には、$f$ を $x$ の多項式として $$ \mathrm{minimize}_{x \in \{0,1\}^n} \quad f(x) $$ と書けます。 量子コンピュータでは、バイナリ変数 $x \in \{0,1\}^n$ よりも、イジング変数 $z = (z_1, z_2, \ldots, z_n), \quad z_i \in \{-1,1\}$ を用いる方が扱いやすいのが一般的です。そのため、最適化したいバイナリ関数 $f(x)$ が与えられたとき、変数変換 $z_i = 2x_i - 1$ を行い、$\tilde f(z) = f(x)$ となる等価なイジング関数 $\tilde f$ を定義します。以下では、このイジング関数 $\tilde f(z)$ の最小化を考えます。 > [!IMPORTANT] > > **重要** > > Amplify SDK では、バイナリ変数 $x \in \{0,1\}$ とイジング変数 $z \in \{-1,1\}$ は、次の関係を満たすものとします: > > > $$ > z = 2x - 1, \qquad x = \frac{1 + z}{2} > $$ > イジング変数 $z$ の定義と、$f(x)$ が $x$ の多項式であることから、$\tilde f(z)$ も $z$ の多項式となります。 以下、多項式 $\tilde f(z)$ を構成する各単項式を $\tilde f_{\alpha}(z)$ と表し、 $$ \tilde f(z) = \sum_{\alpha}\tilde f_{\alpha}(z) $$ と書きます。 ## 量子状態について QAOA の説明に入る前に、量子コンピュータにおいて情報がどのように表現されるかを簡単に確認します。 私たちが通常用いる古典コンピュータでは、情報は $0$ と $1$ からなる「ビット」の列として表されます。量子コンピュータの世界では、この「ビット」に対応するものを **量子ビット (qubit)** と呼び、これは大きさが 1 に規格化された複素数上の 2 次元ベクトル、すなわち **量子状態** として表現されます。 古典のビットが $0$ か $1$ のどちらかの値しか取らないのに対し、量子ビットはより多様な量子状態を取り得ます。数学的には、量子状態 $\ket{\psi}$ は、$|\alpha|^2 + |\beta|^2 = 1$ を満たす複素数 $\alpha, \beta$ を用いて、列ベクトル $(\alpha,\beta)^T$ で表されます。量子情報の分野では、しばしば $\ket{0} = (1,0)^{T},\quad \ket{1} = (0,1)^{T}$ と定義された正規直交基底 $\{\ket{0}, \ket{1}\}$ を用いて $$ \ket{\psi} = \alpha \ket{0} + \beta \ket{1} $$ と表現します。この正規直交基底を**計算基底**と呼びます。以下では量子状態などの行列表示は計算基底で行うものとします。 一般に、$n$ 量子ビットの量子状態は $2^n$ 次元の複素ベクトルで表されます。基本的な考え方は 1 量子ビットの場合と同様です。 ## ハミルトニアンについて QAOA では与えられた目的関数を量子ビットに作用するエルミート演算子に変換し、その値を量子コンピュータで評価します。この目的関数に対応する演算子を**ハミルトニアン**と呼びます。 数学的にはエルミート演算子とは、共役転置(転置と複素共役を取ったもの)が自身に一致する線形演算子を指します。 例として、1量子ビット(2次元複素ベクトル空間)のケースについて行列表示を考えてみましょう。複素数 $a,b,c,d$ を用いて表される線形演算子 $$ A = \begin{pmatrix} a & b \\ c & d \end{pmatrix} $$ がエルミート演算子であるというのは、共役転置 $$ A^\dagger = \begin{pmatrix} a^* & c^* \\ b^* & d^* \end{pmatrix} $$ に対して、$A^\dagger = A$ が成り立つことを意味します。この関係から、一般に1量子ビットに作用するエルミート演算子 $A$ は、実数 $x,y$ と複素数 $z$ を用いて $$ A = \begin{pmatrix} x & z \\ z^* & y \end{pmatrix} $$ と表現されます。 1量子ビットに作用するエルミート演算子の重要な例として、Pauli 演算子があります。行列表示では、 $$ I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \,\, X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \,\, Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}, \,\, Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} $$ と表されます。それぞれ、$I$ を恒等演算子、$X$ を Pauli $X$ 演算子、$Y$ を Pauli $Y$ 演算子、$Z$ を Pauli $Z$ 演算子と呼びます。 [ハミルトニアンの作成](#hamiltonian-construction)で詳述するように、QAOA では目的関数が持つイジング変数を、Pauli $Z$ 演算子で置き換えることでハミルトニアンを構成します。 Pauli $Z$ 演算子の定義から、計算基底 $\{\ket{0}, \ket{1}\}$ は、Pauli $Z$ 演算子の固有ベクトルになっています。特に、 $$ Z\ket{0} &= \ket{0} \\ Z\ket{1} &= -\ket{1} $$ となります。つまり、量子ビットが $\ket{0}$ の時 $Z = 1$、量子ビットが $\ket{1}$ の時 $Z = -1$ となり、計算基底の下で Pauli $Z$ 演算子がイジング変数のようなふるまいをすることが分かります。この意味で、Pauli $Z$ 演算子で構成されたハミルトニアンは、元のイジング変数で定義された目的関数と対応しています。 またこの関係から、量子状態 $\ket{0}$ がイジング値 $1$ に、量子状態 $\ket{1}$ がイジング値 $-1$ に対応することも見て取れます。 ## 量子測定について 量子コンピュータ上の量子ビットで表される状態に、**量子測定**を行うことで古典ビットの情報を引き出すことができます。ここでは、最も基礎的な量子測定である、**計算基底による量子測定**を取り上げます。なお、QAOA で必要とされる量子測定はすべて計算基底による量子測定であるため、以下では特に言及がない限りこれを「量子測定」と呼ぶこととします。 1量子ビット上の量子状態 $$ \ket{\psi} = \alpha\ket{0} + \beta\ket{1} $$ に対する量子測定とは、**確率 $|\alpha|^2$ で値 "0" を、確率 $|\beta|^2$ で値 "1" を得る操作**として理解されます。 この時重要なのが、**量子測定を行うと状態 $\ket{\psi}$ が破壊されてしまう**という点です。厳密には、測定によって得られた値が "0" の時、状態が $\ket{0}$ に、得られた値が "1" の時、状態が $\ket{1}$ に変化します。 量子コンピュータのハードウェアによっては、物理的な制約から量子測定実行後の状態が得られないものもあることから、本ドキュメントでは量子測定後、状態は破壊され二度と使えなくなってしまうものとして話を進めます。 ## エルミート演算子の期待値評価について エルミート演算子 $H$ で表される物理量の、状態 $\ket{\psi}$ での期待値は、 $$ \braket{\psi|H|\psi} $$ で表されます。ここで $\bra{\psi}$ は、量子状態(複素列ベクトル)$\ket{\psi}$ の随伴ベクトル(共役転置を取ったもの)と定義されます。例えば、1量子ビットのケースで、$\ket{\psi} = (a,b)^T$ なら $\bra{\psi} = (a^*, b^*)$ となり、$n$ 量子ビットの場合も同様に共役転置で定義されます。 QAOA では、Pauli $Z$ 演算子の期待値の評価が必要になります。ここでは、量子測定を用いて Pauli $Z$ 演算子の期待値を評価する方法について解説します。 与えられた量子状態が $$ \ket{\psi} = \alpha\ket{0} + \beta\ket{1} $$ の時、$\ket{\psi}$ における Pauli $Z$ 演算子の期待値は、計算基底での行列表示を用いて $$ \braket{\psi|Z|\psi} = (\alpha^*, \beta^*) \begin{pmatrix} 1 & 0\\ 0 & -1 \end{pmatrix} \begin{pmatrix} \alpha\\ \beta \end{pmatrix} = |\alpha|^2 - |\beta|^2 $$ と計算できます。 ここで、状態 $\ket{\psi}$ が未知($\alpha$ と $\beta$ の値が未知)の際には、期待値を直接厳密に計算することはできません。しかし、未知の量子状態 $\ket{\psi}$ のコピーを十分大きな数用意して量子測定を繰り返し行うことにより、期待値を近似的に評価することができます。 量子状態 $\ket{\psi}$ を $N$ 個用意し、それぞれについて量子測定を行うことを考えます。その結果、"0" が $N_{\alpha}$ 個、 "1" が $N_{\beta}$ 個得られたとします。($N = N_{\alpha} + N_{\beta}$ です。) この時、十分大きい $N$ については、 $$ |\alpha|^2 \approx \frac{N_{\alpha}}{N} \ ,\ |\beta|^2 \approx \frac{N_{\beta}}{N} $$ と近似できます。これを用いると、Pauli $Z$ 演算子の期待値を $$ \braket{\psi|Z|\psi} = |\alpha|^2 - |\beta|^2 \approx \frac{N_{\alpha} - N_{\beta}}{N} $$ と評価できることが分かります。 ここでは1量子ビットのケースを考えましたが、一般の $n$ 量子ビットについても同様に Pauli $Z$ 演算子の期待値が評価できます。 > [!IMPORTANT] > > **重要** > > [量子測定についての解説](#quantum-measurement)で触れたとおり、量子測定を行うと状態 $\ket{\psi}$ は破壊されてしまいます。そのため、$\ket{\psi}$ の量子測定を $N$ 回行う際には、$\ket{\psi}$ のコピーを $N$ 個用意する必要があります。この値を**ショット数**あるいは**サンプル数**と呼びます。 > > ショット数を大きくとれば計算の精度が良くなることが期待される一方、計算に時間がかかってしまうというトレードオフがあります。そのため QAOA ではショット数を適切に設定することが肝要となります。 ## QAOA の手続き QAOA は次のような手続きで最適化問題を解きます。 1. 与えられたイジング関数 $\tilde f$ から、目的関数に対応するハミルトニアン $H$ を構成する。このとき、$H$ の最小固有値が $\tilde f$ の最小値に対応する。 2. $H$ の最小固有値(に対応する固有状態)を探索するために、実数パラメータ $\boldsymbol{\theta} = (\theta_1,\theta_2,\ldots,\theta_k)$ で特徴づけられたパラメトリック量子回路(Ansatz 回路)を構成する。パラメータ $\boldsymbol{\theta}$ に対応する量子状態を $\ket{\psi(\boldsymbol{\theta})}$ と書き、Ansatz 状態と呼ぶ。 3. コスト関数を $C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})}$ と定義する。 4. 量子コンピュータ上での $C(\boldsymbol{\theta})$ の評価と、古典最適化アルゴリズムによるパラメータ $\boldsymbol{\theta}$ の更新を、ある収束条件を満たすまで繰り返す。 以下、各ステップについて順に説明します。 ### 1. ハミルトニアンの作成 QAOA の目的関数として、イジング関数 $$ \tilde f(z) = \sum_{\alpha} \tilde{f}_{\alpha}(z) $$ が与えられているとします。 目的は、$\tilde f(z)$ を最小化するイジング変数列 $z = (z_1,\ldots,z_n) \in \{-1,1\}^n$ を見つけることです。 量子コンピュータで最適化を行うには、このイジング関数を量子ビットに作用するエルミート演算子(**ハミルトニアン**)へと変換します。具体的には、目的関数に対応するハミルトニアン $H = \sum_{\alpha} H_{\alpha}$ を**各単項式 $\tilde f_\alpha(z)$ に登場するイジング変数 $z_i$ を、対応する Pauli $Z$ 演算子 $Z_i$ に置き換える**ことで定義します。 具体例を以下に示します。 * $\tilde f_{\alpha}(z) = 2z_1z_2$ のとき $$ H_{\alpha} = 2 Z_1 Z_2 $$ * $\tilde f_{\alpha}(z) = -3 z_3$ のとき $$ H_{\alpha} = -3 Z_3 $$ * $\tilde f_{\alpha}(z) = 5$ のような定数項は、恒等演算子 $I$ の係数に対応し $$ H_{\alpha} = 5 I $$ となります。このような定数項は、スペクトル全体を一定だけシフトするだけで基底状態は変えないため、多くの場合は無視して構いません(ただしエネルギーの絶対値が必要な場面では保持します)。 ここで $Z_i$ は「$i$ 番目の量子ビットに作用する Pauli $Z$ 演算子」を意味します。本ドキュメントではテンソル積 $\otimes$ は省略し、$Z_1 \otimes Z_2$ を $Z_1 Z_2$ のように書きます。 以上より、$n$ 変数のイジング関数 $\tilde f$ を QAOA で最適化したい場合、$n$ 量子ビット上で定義されたハミルトニアン $H$ が必要になります。したがって、少なくとも $n$ 量子ビットを持つ量子コンピュータが必要になります。 ### 2. Ansatz 状態の準備 与えられた問題を解くため、パラメータ付きの量子状態(Ansatz 状態)を定義します。Ansatz 状態とは、**パラメータで特徴づけられた量子回路を初期状態に作用させて得られる状態** のことです。QAOA では、特定の構造を持つ QAOA Ansatz を用います。QAOA Ansatz を作成する回路は次のようになります。 ![../../_images/qaoa_circuit.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/qaoa_circuit.svg) #### 初期状態 QAOA では、多くの場合、初期状態として $+$ 状態と呼ばれる状態を用います。1 量子ビットの $+$ 状態は $$ \ket{+} = \frac{\ket{0} + \ket{1}}{\sqrt{2}} $$ と定義されます。 > [!TIP] > > **ヒント** > > $+$ 状態は、$0$ 状態 $\ket{0}$ に Hadamard ゲート > > > $$ > \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1 & 1 \\ > 1 & -1 > \end{pmatrix} > $$ > > > を作用させることで得られます。 $n$ 個すべての量子ビットが $+$ 状態にある $\ket{+}^{\otimes n}$ を QAOA の初期状態として用います。 #### QAOA Ansatz の定義 QAOA Ansatz は、実数パラメータ列 $$ \boldsymbol{\theta} = (\boldsymbol{\beta},\boldsymbol{\gamma}) = (\beta_1,\ldots,\beta_p,\gamma_1,\ldots,\gamma_p) $$ で特徴づけられる量子状態です。ここで $p$ は QAOA の「深さ」(層数)です。 本ドキュメントでは、パラメータ全体をまとめて $\boldsymbol{\theta}$ と書きます。QAOA Ansatz を生成する量子回路 $U(\boldsymbol{\theta})$ を次のように定義します。 $$ U(\boldsymbol{\theta}) = \prod_{j=1}^{p} \left[ \exp\left(-i \beta_j \sum_{k} X_k\right) \exp\left(-i \gamma_j H\right) \right] $$ ここで $H$ は先ほど定義したコストハミルトニアン、 $X_k$ は $k$ 番目の量子ビットに作用する Pauli $X$ 演算子を表します。因子の積 $\prod_{j=1}^{p}$ は、**右側の $j=1$ の層から左側の $j=p$ の層へ向かって順に作用する** と解釈します。本ドキュメントでは、$\gamma_j$ をコストハミルトニアン $H$ に対応するパラメータ、 $\beta_j$ を $X$ によるミキシングに対応するパラメータとして用いています。直感的には、 * $\exp(-i \gamma_j H)$ が Pauli $Z$ 方向(コスト関数)に沿って状態を発展させ、 * $\exp\left(-i \beta_j \sum_k X_k\right)$ が Pauli $X$ 方向に沿って状態を混合させる ことで、多様な量子状態を表現します。 以上より、パラメータ $\boldsymbol{\theta}$ に対応する QAOA Ansatz 状態を $$ \ket{\psi(\boldsymbol{\theta})} = U(\boldsymbol{\theta}) \ket{+}^{\otimes n} $$ と定義します。 ### 3. コスト関数の定義 コスト関数 $C(\boldsymbol{\theta})$ は、ハミルトニアン $H$ の、Ansatz 状態 $\ket{\psi(\boldsymbol{\theta})}$ における期待値として定義されます。数学的には $$ C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})} $$ です。 [先述の通り](#hermitian-evaluation)計算基底の行列表示では、量子状態 $\ket{\psi}$ は複素列ベクトルとして表され、$\bra{\psi}$ はその随伴ベクトルです。 ハミルトニアン $H$ の最小固有値を $\lambda_{\min}$、その固有ベクトルを $\ket{\psi_{\min}}$ とすると、$C(\boldsymbol{\theta})$ は $\ket{\psi(\boldsymbol{\theta})}$ が $\ket{\psi_{\min}}$ に一致するときに最小値 $\lambda_{\min}$ を取ります。 QAOA では、「$\ket{\psi(\boldsymbol{\theta})}$ のうち、$C(\boldsymbol{\theta})$ を最小にするものは $H$ の基底状態(の良い近似)になっているはずだ」という前提のもと、古典的な最適化により $C(\boldsymbol{\theta})$ を最小化するパラメータ $\boldsymbol{\theta}$ を探索します。 ### 4. 古典最適化によるパラメータ更新サイクル QAOA の本体とも言えるステップです。ここでは、 * 量子コンピュータによるコスト関数 $C(\boldsymbol{\theta})$ の値の評価 * 古典コンピュータによるパラメータ $\boldsymbol{\theta}$ の更新 を繰り返し、$C(\boldsymbol{\theta})$ を最小化する $\boldsymbol{\theta}^{\textup{opt}}$ を見つけることを目指します。 #### コスト関数 $C(\boldsymbol{\theta})$ の値の評価 コスト関数 $C(\boldsymbol{\theta})$ の値を評価するのは量子コンピュータの仕事です。 目的関数から作られたハミルトニアン $H$ は、その[構成方法](#hamiltonian-construction)より $$ H = \sum_{\alpha} H_{\alpha} = \sum_{\alpha} c_{\alpha} Z_{\alpha} $$ と表すことができます。 ここで、$c_{\alpha}$ は 単項式 $\tilde{f}_{\alpha}(z)$ の係数部分、$Z_{\alpha}$ は変数部分に対応する Pauli $Z$ 演算子です。この表式を用いると、コスト関数 $C(\boldsymbol{\theta})$ は $$ C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})} = \sum_{\alpha} c_{\alpha} \bra{\psi(\boldsymbol{\theta})} Z_{\alpha} \ket{\psi(\boldsymbol{\theta})} $$ と表されます。各 $\bra{\psi(\boldsymbol{\theta})} Z_{\alpha} \ket{\psi(\boldsymbol{\theta})}$ の値は、[期待値評価についての解説](#hermitian-evaluation)の通り、$\ket{\psi(\boldsymbol{\theta})}$ の量子測定の結果を用いて評価することができます。それぞれの $\bra{\psi(\boldsymbol{\theta})} Z_{\alpha} \ket{\psi(\boldsymbol{\theta})}$ の値を上式に代入することで、コスト関数 $C(\boldsymbol{\theta})$ の値が評価できます。 #### パラメータ $\boldsymbol{\theta}$ の更新 量子コンピュータが評価したコスト関数の値をもとに、パラメータ $\boldsymbol{\theta}$ を更新して最適パラメータを見つけ出すのは古典コンピュータ側の役割です。 パラメータ更新サイクルをまとめると、 1. あるパラメータ $\boldsymbol{\theta}$ を用いて QAOA 回路 $U(\boldsymbol{\theta})$ を実行し、 2. 状態 $\ket{\psi(\boldsymbol{\theta})}$ に対するハミルトニアン $H$ の期待値 $C(\boldsymbol{\theta})$ を測定により推定し、 3. 古典最適化アルゴリズム(勾配法、勾配無し最適化、ベイズ最適化など)を用いて 次の $\boldsymbol{\theta}$ を決める というステップを、ある収束条件を満たすまで繰り返します。 ## QAOA まとめ 最後に、QAOA の典型的なステップを改めてまとめます。 ```mermaid flowchart TD S1["Step 1: ハミルトニアンの定義"] S2["Step 2: Ansatz 回路の構成"] S3["Step 3: コスト関数の定義"] S4["Step 4: パラメータの最適化"] S5["Step 5: 解の抽出"] S1 --> S2 --> S3 --> S4 S4 -->|"未収束"| S4 S4 -->|"収束"| S5 ``` **Step1: ハミルトニアンの定義** 最適化したい古典コスト関数を $f(z) = \sum_{\alpha} c_{\alpha} f_{\alpha}(z)$ と書く。ここで、$z = (z_1,\ldots,z_n)$ は $z_i \in \{-1,1\}$ のイジング変数列、$c_{\alpha}$ は実数係数、$f_{\alpha}$ は単項式である。各単項式 $f_{\alpha}(z)$ に現れるイジング変数 $z_i$ を対応する Pauli $Z$ 演算子 $Z_i$ に置き換え、必要に応じて恒等演算子 $I$ を用いることで、量子ビット空間上のハミルトニアン $H = \sum_{\alpha} H_{\alpha}$ を構成する。QAOA の目的は、この $H$ の最小固有値/固有ベクトルを近似的に求めることで、$f(z)$ の最小値を達成するイジング変数列 $z$ を得ることである。 **Step2: Ansatz 状態の準備** 上で構成したハミルトニアン $H$ の最小固有値を探索するため、実数パラメータ列 $\boldsymbol{\theta} = (\boldsymbol{\gamma},\boldsymbol{\beta})$ で特徴づけられた QAOA Ansatz 回路 $U(\boldsymbol{\theta})$ を構成する。初期状態 $\ket{+}^{\otimes n}$ に対し、 $\ket{\psi(\boldsymbol{\theta})} = U(\boldsymbol{\theta}) \ket{+}^{\otimes n}$ と定義し、この $\ket{\psi(\boldsymbol{\theta})}$ を Ansatz 状態と呼ぶ。 **Step3: コスト関数の定義** コスト関数を $C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})}$ と定義する。$C(\boldsymbol{\theta})$ は、パラメータ $\boldsymbol{\theta}$ に対応する Ansatz 状態 $\ket{\psi(\boldsymbol{\theta})}$ におけるハミルトニアン $H$ の期待値である。 **Step4: パラメータのアップデート** 量子コンピュータ上で $C(\boldsymbol{\theta})$ を評価し、その結果を用いて古典最適化アルゴリズムによりパラメータ $\boldsymbol{\theta}$ を更新する。この「(量子側での)評価」と「(古典側での)更新」を、所定の収束条件を満たすまで繰り返す。 **Step5: 解の抽出** 収束時のパラメータを $\boldsymbol{\theta}^{\textup{opt}}$ と書く。このとき、$C(\boldsymbol{\theta}^{\textup{opt}})$ および $\ket{\psi(\boldsymbol{\theta}^{\textup{opt}})}$ は、ハミルトニアン $H$ の最小固有値/固有ベクトルの良い近似になっていると期待される。状態 $\ket{\psi(\boldsymbol{\theta}^{\textup{opt}})}$ での測定結果から得られたイジング変数列 $z$ ごとに目的関数 $\tilde{f}(z)$ を計算し、 $\tilde{f}(z)$ が最小となるものを候補解として選ぶ。測定結果の中で最も多く得られたイジング変数列 $z^{\textup{opt}}$ は $\tilde{f}(z)$ の最小値(またはその近傍の値)を与える解になっていると期待される。 --- [[1](#id1)] E. Farhi, J. Goldstone, and S. Gutmann, A Quantum Approximate Optimization Algorithm. [arXiv:1411.4028 (2014).](https://arxiv.org/abs/1411.4028) --- # 制約付き QAOA のアルゴリズム 最適化問題の中には、変数にある種の制約を課した下での最適値を求める、というものがあります。 例えば、イジング変数 $z$ を用いた目的関数 ${f}(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ を、「 $z_0$, $z_1$, $z_2$ のうち、ちょうど1個の変数だけが $-1$ になる 」という制約の下で最小化したいとします。 もし変数に何も制約がなければ、この関数 ${f}(z)$ は $(z_0, z_1, z_2) = (-1, -1, 1)$ で最小値 ${f}(z) = -5$ を取ります。 しかし、この解は「 $z_0$, $z_1$, $z_2$のうち、ちょうど1個の変数だけが $-1$ になる 」という制約を満たしません。このような制約の下では $(z_0, z_1, z_2) = (1, -1, 1)$ で最小値 $f(z) = -3$ を取ります。 変数への制約は様々なものが考えられますが、上記の例で課したような制約は広く用いられます。 ちなみに、変数が $\{0,1\}$ から成るバイナリ変数の場合には、ちょうど N 個の変数だけが $1$ になる制約はしばしば N-HOT 制約と呼ばれます。 N-HOT 制約について詳しくは、[Wikipedia: One-hot](https://ja.wikipedia.org/wiki/One-hot) を参照してください。 > [!NOTE] > > **注釈** > > ここでは、イジング変数から成る変数列に対して、ちょうど $n$ 個の変数だけが $-1$ になる制約についても N-HOT と呼びます。 > > ただし、Amplify SDK における [`one_hot()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot)関数は`poly == 1`として実装されています。 > そのためイジング変数で one_hot 制約を定義するには[`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to)関数で等式制約として表現する必要があります。 以下では「制約条件」といったとき、この条件を考えます。 Amplify では QAOA を実行する際に、自動で上記の N-HOT 制約が課された最適化問題を検出して、与えられた制約条件に応じた変数のグルーピングを行うことで探索空間を削減し、より効率よく解を求めることができます。自動検出を無効にすることもできます。詳細は[QAOAの種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype)を参照してください。 ## N-HOT QAOA ここでは、与えられた制約条件に対して変数のグルーピングを行うことでどのように最適解が得られるのかを説明します。 制約条件を扱えないソルバーで制約条件付きの最適化問題を解く際には、制約条件を満たす解を最適解とする (緩和) 多項式 ${g}$ とペナルティ係数 $\lambda$ を与え、 ${f}' = {f} + \lambda {g}$ を解くことで制約条件の下での最適解を得ます。 例えば、上記の例のような、目的関数 ${f}(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ を、「 $z_0 + z_1 + z_2 = 1$ 」という 等式制約の下で解きたいときは、${g}(z) = (z_0+z_1+z_2 - 1)^2$ として、適切な $\lambda$ を選ぶことで、所望の解を得ることができます。 詳しくは [ペナルティ法](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-definition) を参照してください。 一方、 N-HOT QAOA では制約条件を考慮した Ansatz を考えることで、与えられた最適化問題を「制約条件によって制限されたパラメーター空間内でハミルトニアンの最小の固有値と固有ベクトルを求める」問題に帰着させ、より効率的と期待される方法で問題を解きます。 解きたい最適化問題において、$k$個の独立した(制約する変数が互いにかぶらない)等式制約が与えられているとします。この制約条件の下で変数 $z$ は $z = (z^{(1)},z^{(2)},\ldots,z^{(k)},{z})$ のように $k+1$ 個のグループに分けられます。ここで、$z^{(1)}, \ldots, z^{(k)}$ は独立な等式制約に対応するグループで、${z}$ は制約のない変数のグループです。 Ansatz は、 グループが $k$ 個あるとき、 $\ket{\psi(\boldsymbol{\theta})}=\ket{\psi_{\mathrm{group}, 1}(\boldsymbol{\theta}^{(1)})}\otimes\ket{\psi_{\mathrm{group}, 2}(\boldsymbol{\theta}^{(2)})}\otimes\cdots\ket{\psi_{\mathrm{group}, k}(\boldsymbol{\theta}^{(k)})}\otimes\ket{\psi_{\mathrm{ungroup}}(\boldsymbol{{\theta}})}$ のように各グループについて独立に量子回路が作用するように定義します。 このうち、 $\ket{\psi_{\mathrm{ungroup}}(\boldsymbol{{\theta}})}$ では、独立な Pauli $X$ 回転ゲート $R_X(\theta)=\mathrm{e}^{i\frac{\theta}{2} X}$ を作用させます。 回路の概略を示すと下図のようになります。 ![grouping_ansatz](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/grouping_ansatz.drawio.svg) ### グループの Ansatz 回路 各グループ $i = 1,2,\ldots,k$ について Ansatz 回路 $U(\boldsymbol{\theta}^{(i)})$ は次のように構成されています。 ![grouping_ansatz_component](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/grouping_ansatz_component.drawio.ja.svg) 回路図中で 2 量子ビットゲート $A(\theta)$ は下図のように CNOT ゲートと Pauli $Y$ 回転ゲート $R_Y(\theta) = \mathrm{e}^{-i\frac{\theta}{2} Y}$ で実現されます。 ![gateA](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/gateA.drawio.svg) このゲート $A(\theta)$ を行列表示すると $$ A(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \sin\theta & \cos\theta & 0 \\ 0 & \cos\theta & -\sin\theta & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ となります [[1]](#id6) [[2]](#id7)。$A(\theta)$ を計算基底に作用させたときの結果を見てみると、 $$ \begin{align}\begin{aligned} A(\theta)\ket{00} &= \ket{00},\\A(\theta)\ket{01} &= \sin\theta\ket{01} +\cos\theta\ket{10},\\A(\theta)\ket{10} &= \cos\theta\ket{01} -\sin\theta\ket{10},\\A(\theta)\ket{11} &= \ket{11} \end{aligned}\end{align} $$ となっており、入力が計算基底の時、出力された状態は、入力状態の持つ"1"の数を保存することが分かります。 ### グループの初期状態 各グループ $i = 1,2,\ldots,k$ について、初期状態 $\ket{\psi_{\mathrm{init}, i}}$ は「制約条件で課された $-1$ の個数だけ"1"を持つ量子状態」に定めます。 > [!NOTE] > > **注釈** > > [QAOA 理論](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md)でも触れたとおり、1量子ビットの計算基底 $\{\ket{0}, \ket{1}\}$ は Pauli $Z$ 演算子の固有ベクトルであり、その固有値がイジング変数に対応します。具体的には、 > > > $$ > \braket{0|Z|0} &= 1 \\ > \braket{1|Z|1} &= -1 > $$ > > > から $\ket{0}$ が $1$ に、$\ket{1}$ が $-1$ に対応します。 > > 以下で解説する「制約条件で課された $-1$ の個数だけ"1"を持つ量子状態」というのは、量子ビットのラベル"1"がイジング値 $-1$ に対応することに留意して、イジング変数に対する制約条件を量子ビットに埋め込むことで得られる量子状態であると解釈されます。 ここで少し数学的な説明をします。グループ $i$ に属する量子ビットの数を $n_i$、制約条件で課された $-1$ の数を $l_i$ とします。ここで、ビット列 $x^n \in \{0,1\}^n$ のハミング重み(列内の"1"の個数)を $w(x^n)$ と定め、計算基底の部分集合 $\{\ket{x^{n_i}}: w(x^{n_i}) = l_i\}$ を考えます。これは、"1"の数が $l_i$ 個である計算基底状態の集合です。 「制約条件で課された $-1$ の個数だけ"1"を持つ量子状態」とは、この部分集合の要素の任意の重ね合わせ、つまり $$ \sum_{x^{n_i}:w(x^{n_i}) = l_i} |c_{x^{n_i}}|^2 = 1 $$ なる複素数 $c_{x^{n_i}}$ を用いて表された状態 $$ \sum_{x^{n_i}:w(x^{n_i}) = l_i} c_{x^{n_i}}\ket{x^{n_i}} $$ を指します。 Amplify では初期状態を $$ \ket{\psi_{\mathrm{init}, i}} = \ket{\underbrace{1\dots1}_{l_i \text{個}}\underbrace{0\dots0}_{(n_i -l_i) \text{個}}} $$ と定めています。 ### なぜ制約条件を満たすのか Ansatz 回路 $U(\boldsymbol{\theta}^{(i)})$ と初期状態 $\ket{\psi_{\mathrm{init}, i}}$ の構成を考えると、$\ket{\psi_{\mathrm{init}, i}}$ に $U(\boldsymbol{\theta}^{(i)})$ を作用されて得られる状態も、 $$ U(\boldsymbol{\theta}^{(i)})\ket{\psi_{\mathrm{init}, i}} = \sum_{x^{n_i}:w(x^{n_i}) = l_i} c_{x^{n_i}}\ket{x^{n_i}} $$ のように表されます。 例で確認します。以下では、$i$ 番目の量子ビットと $j$ 番目の量子ビットに作用するゲート $A$ を、$A_{(i,j)}$ と書くことにします。初期状態 $\ket{\psi_{\mathrm{init}}} = \ket{100}$ にゲート $A(\theta_1)_{(1,2)}$ を作用させることを考えます。 結果として $$ A(\theta_1)_{(1,2)}\ket{\psi_{\mathrm{init}}} = \cos\theta_1\ket{010} - \sin\theta_1\ket{100} $$ が得られます。この状態にさらに、ゲート $A(\theta_2)_{(2,3)}$ を作用させると、 $$ A(\theta_2)_{(2,3)}A(\theta_1)_{(1,2)}\ket{\psi_{\mathrm{init}}} = \cos\theta_1\cos\theta_2\ket{001} - \cos\theta_1\sin\theta_2\ket{010} - \sin\theta_1\ket{100} $$ が出力されます。以下この操作を何度繰り返しても、出力される状態は"1"を1個持つ状態、すなわち「制約条件で課された $-1$ の個数だけ"1"を持つ量子状態」になります。 以上のように状態 $U(\boldsymbol{\theta}^{(i)})\ket{\psi_{\mathrm{init}, i}}$ は初期状態が持つ"1"の個数を保存した状態になります。 この Ansatz 状態を用いることで、制約条件を保ちながら最適解を求めることが可能になるのです。 ### 例 ここでは簡単な例を用いて、制約付き QAOA の回路構成を確認します。 問題として、$f(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ と定義して $$ \min_{z: z_0 + z_1 = 0} {f}(z) $$ を考えます。簡単のため、Ansatz 回路の深さ(reps)は $1$ とします。 この問題では変数 $z_0$ と $z_1$ が制約条件 $z_0 + z_1 = 0$ が課されたグループに属しており、$z_2$ に制約条件はありません。 この制約条件は、$z_0$ と $z_1$ のどちらか片方だけが $-1$ となることを課すものです。 先述した手順に従うと、Amplify では $z_0$ と $z_1$ に関する初期状態が $\ket{10}$、$z_2$ に関する初期状態が $\ket{0}$ と定まり、制約付き QAOA の回路図は次のようになります。 ![grouping_ansatz_example](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/grouping_ansatz_example.drawio.svg) 確かに $z_0$ と $z_1$ にかかわる部分の回路では、入力状態の持つ"1"の数と、出力状態の持つ"1"の数が同一であることが分かります。 以上みてきた通り、本ページで導入した Ansatz 状態 $\ket{\psi(\boldsymbol{\theta})}$ は $k$ 個の独立な制約条件を満たす状態に制限され、制約を緩和して解を探索する通常の方法と比べて、より効率的に解を求めることができると期待されます。 --- [[1](#id1)] B.T. Gard, L. Zhu, G.S. Barron *et al*. Efficient symmetry-preserving state preparation circuits for the variational quantum eigensolver algorithm. [npj Quantum Inf **6**, 10 (2020).](https://doi.org/10.1038/s41534-019-0240-1) [[2](#id2)] Y. Ibe, Y.O. Nakagawa, N. Earnest *et al*. Calculating transition amplitudes by variational quantum deflation. [Phys. Rev. Research **4**, 013173 (2022).](https://doi.org/10.1103/PhysRevResearch.4.013173) --- # Recursive QAOA のアルゴリズム Recursive QAOA [[1]](#id8)(以下、RQAOA)は、深さの浅い Ansatz 回路による QAOA を繰り返し実行し、段階的に問題サイズを縮小しながら最適解を特定する手法です。通常の QAOA で問題となる回路の深さの制約を緩和し、大規模な問題への適用を目指します。通常の QAOA の理論についての解説は [QAOA 理論](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md) を参照してください。 > [!NOTE] > > **注釈** > > RQAOA は制約付きの問題には対応していません。制約がある場合には、ペナルティ項を導入して制約なし問題へ Amplify SDK が自動で変換します。詳細は[制約条件とペナルティ関数](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md)を参照してください。 ## RQAOA の手続き RQAOA は次のような手続きで実行されます。 * Step 1: 深さの浅い QAOA を利用した変数削減サイクル * 手順1: 浅い回路を用いて QAOA を実行する * 手順2: QAOA の結果を用いて消去する変数を決定する * 手順3: 変数を削減して新しい問題を構成する * Step 2: 変数を十分な数削減した問題の最適解の発見 * Step 3: 変数を削減した問題の解から元の問題の最適解の導出 ![../../_images/rqaoa_flowchart.drawio.ja.svg](https://amplify.fixstars.com/ja/docs/amplify/v1/_images/rqaoa_flowchart.drawio.ja.svg) ## RQAOA の詳細 以下ではより詳しく各ステップで行われる手続きについて見ていきます。 各項目の説明に際して、簡単な例としてイジング関数 $$ f(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ を最小化する問題を考えていきます。 ### Step 1. 変数削減サイクル RQAOA の中核をなすステップです。変数削減サイクルでは以下の手順を問題のサイズ(変数の数)が十分小さくなるまで繰り返し実行します。 1. イジング変数で構成された目的関数 ${f}(z)$ に対して、深さの浅い($p = 1$ などの)Ansatz 状態 $\ket{\psi(\boldsymbol{\theta})}$ を用いた QAOA を実行し、その終状態 $\ket{\psi}$ を計算基底で測定する。 2. 測定結果をもとに、目的関数 ${f}(z)$ の各項の期待値を求め、期待値の絶対値が最も大きい項に注目する。ここで、その期待値の正負に応じて、$\sigma = 1$ または $\sigma = -1$ と定義する。 3. 注目した項に対して、 ${\rm 項}_{\mathrm{max}}= \sigma$ という関係を導入する。この関係をもとに変数を消去して新しい目的関数 ${f}_{\mathrm{new}}(z)$ を定義する。 より詳細にそれぞれの手順を解説します。 #### 1. 浅い回路での QAOA 実行 RQAOA の繰り返し手順の最初では、与えられた最適化問題を浅い回路による QAOA を用いて近似的に解き、その終状態 $\ket{\psi}$ の測定結果を取得します。 測定結果はこの先の手順でどの変数を削除するのかにのみ用いられるため、**厳密な最適解を返す必要はありません**。これが浅い Ansatz 回路の使用を許容できる理由になっています。 #### 2. 消去する変数の決定 手順1で得られた測定結果から、目的関数の各項の中で「最も値が確からしい」項を決定します。そのために各項の期待値を計算します。 例 $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ を見てみましょう。この場合には、目的関数をハミルトニアンに変換したうえで、各項の変数部分に対応する Pauli $Z$ 演算子の期待値 $\braket{\psi|Z_0Z_1|\psi}$、$\braket{\psi|Z_1Z_2|\psi}$、$\braket{\psi| Z_0 |\psi}$、$\braket{\psi| Z_2 |\psi}$ をそれぞれ計算します。変換の詳細は[QAOA理論](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/QAOA_algo.md)を参照してください。 最も期待値の絶対値が大きかった Pauli 演算子を $Z_{\mathrm{max}}$ とします。 そして、$Z_{\mathrm{max}}$ に対応する項を ${\rm 項}_{\mathrm{max}}$ として、その値を ${\rm 項}_{\mathrm{max}} = \sigma \in \{-1,1\}$ で定めます。 もし $\langle \psi|Z_{\mathrm{max}}|\psi\rangle$ が正なら $\sigma = 1$ と、反対に $\langle \psi|Z_{\mathrm{max}}|\psi\rangle$ が負なら $\sigma = -1$ と定めます。定義より $-1 \leq \langle \psi|Z_{\mathrm{max}}|\psi\rangle \leq 1$ です。 多項式 $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ で、例えば $$ \begin{align}\begin{aligned} \begin{aligned} \braket{\psi|Z_0Z_1|\psi} &= -0.4\\\braket{\psi|Z_1Z_2|\psi} &= -0.6\\\braket{\psi|Z_0|\psi} &= -0.3\\\braket{\psi|Z_2|\psi} &= -0.2 \end{aligned} \end{aligned}\end{align} $$ という期待値計算の結果が得られたとしましょう。 この時、$Z_{\mathrm{max}} = Z_1Z_2$ であり、${\rm 項}_{\mathrm{max}} = z_1z_2$ となります。 $\braket{\psi|Z_1Z_2|\psi} = -0.6<0$ であることから、$\sigma = -1$ と定め、${\rm 項}_{\mathrm{max}} = \sigma$、つまり $z_1z_2 = -1$ という関係式が得られます。 この操作は次のような意味を持ちます。$Z_{\mathrm{max}}$ の期待値の絶対値が最も大きいというのは、その対応する変数 ${\rm 項}_{\mathrm{max}}$ の値が $+1$ あるいは $-1$ に最も近かったということです。この意味で、**もし目的関数の各項の値をどれか一つだけ決め打つのなら、${\rm 項}_{\mathrm{max}}$ が一番もっともらしい選択である**ということになります。そこで、$Z_{\mathrm{max}}$ の期待値の正負によってその項の値を ${\rm 項}_{\mathrm{max}} = 1$ または ${\rm 項}_{\mathrm{max}} = -1$ と決め打ち、問題のサイズを小さくしていくのです。 #### 3. 変数削減 手順2で導入した ${\rm 項}_{\mathrm{max}} = \sigma$ という関係を利用して変数削減を行います。 ##### ${\rm 項}_{\mathrm{max}}$ が一次の場合 この場合、ある非負整数 $i$ を用いて ${\rm 項}_{\mathrm{max}}$ = $z_i$ と表され、「$z_i$ の値が一番確からしく $\sigma$ になる」ということになります。そこで、元のハミルトニアン $H$ において $z_i = \sigma$ と置き換えて新しい目的関数 ${f}_{\mathrm{new}}$ を得ます。 ##### ${\rm 項}_{\mathrm{max}}$ が二次以上の場合 例 $$ {f}(z)= 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ を再び考えます。 手順2で設定したように、$z_1z_2 = -1$ と定まったとします。 これはすなわち、$z_1$ と $z_2$ の間に $z_1 = -z_2$ という関係が成り立つことを示唆しています。そのため、元の目的関数 ${f}(z)$ に、$z_1 = -z_2$ を代入することによって $$ {f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3 $$ が得られます。イジング変数 $z \in \{-1,1\}$ に対して、$z^2 = 1$ であることに注意してください。結果的に、変数が一つ減った新しい目的関数が得られていることが分かります。 この例では二次の問題を扱っていますが、より高次の項に注目して変数を削減する場合も同様の手順で行います。一般の場合について詳しくは[参考文献](https://arxiv.org/abs/1910.08980)の Appendix C を参照してください。 手順1-3の結果、新しい目的関数 ${f}_{\mathrm{new}}(z)$ の変数の数が十分小さい場合にはサイクルを抜け出します。そうでない場合には、${f}_{\mathrm{new}}(z)$ を用いて再度手順1から変数を削減します。 ### Step 2. 変数削減後の最適化問題の求解 変数削減サイクルを繰り返して問題のサイズが十分小さくなったら、総当たりなどで最適解を求めます。 ここでも例を考えてみましょう。 Step 1 で見た通り、 $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ において、$z_1z_2 = -1$ の関係式に基づいて $$ {f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3 $$ という新しい目的関数が得られたとします。総当たりの結果、${f}_{\mathrm{new}}(z)$ を最小化する値として、 $$ (z_0, z_2) = (-1,-1) $$ という解を得ます。 ### Step 3. 元の問題の最適解の導出 RQAOA の最後のステップでは、Step 2 で得られた変数削減後の問題の解から、元の最適化問題 ${f}(z)$ の最適解を構成します。この最適解の導出は、Step 1 の手順3で得られた変数削減のための関係式 ${\mathrm{項}}_{\mathrm{max}} = \sigma$ を逆向きにたどっていくことで行われます。 Step 2 では、変数削減後の問題 ${f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3$ の最適解 $(z_0, z_2) = (-1,-1)$ を得ました。このステップでは、変数削減の際に用いた $$ z_1 = -z_2 $$ に従って $z_1$ の値を導出します。今回のケースでは、 $$ z_1 = 1 $$ と求まります。こうして、元の最適化問題 ${f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2$ の最適解として、 $$ z = (z_0,z_1,z_2) = (-1,1,-1) $$ が得られます。 ## まとめ このように、RQAOA は QAOA を繰り返し利用して段階的に最適化問題のサイズを削減することで最適解を計算する手法です。 アルゴリズム内で QAOA は最適解を計算するのではなく、あくまで削減対象の変数を決定することに用いるため、最適解を計算する時よりも浅い回路を使用できることが期待されます。 通常の QAOA では、大規模な問題を解く際に深さの大きい回路が必要になり計算時間が増大してしまうことや、回路の大きさやハードウェアノイズなどが原因で QAOA におけるパラメータの更新がうまくいかなくなってしまう現象が指摘されていました(後者の現象は "Barren Plateau" と呼ばれて研究されています [[2]](#id9))。 RQAOA では、量子コンピュータを浅い回路での QAOA のみに用いることから、こうした問題を回避しながら最適化問題の解がより精度良く効率的に得られることが期待されます。 --- [[1](#id1)] S. Bravyi, A. Kliesch, R. Koenig, and E. Tang, Obstacles to Variational Quantum Optimization from Symmetry Protection. [Physical Review Letters **125**, 260505 (2020)](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.125.260505). [[2](#id7)] J.R. McClean, S. Boixo, V.N. Smelyanskiy, *et al*. Barren plateaus in quantum neural network training landscapes. [Nat Commun **9**, 4812 (2018)](https://doi.org/10.1038/s41467-018-07090-4); S. Wang, E. Fontana, M. Cerezo *et al*. Noise-induced barren plateaus in variational quantum algorithms. [Nat Commun **12**, 6961 (2021)](https://doi.org/10.1038/s41467-021-27045-6). --- # Amplify-BBOpt Amplify SDK の機能を活用して **ブラックボックス最適化 (BBO)** を実行するための拡張ライブラリです。 > [!TIP] > > **Tip** > > ブラックボックス最適化 とは、目的関数の数式表現が未知、あるいは複雑すぎる問題に対して最適なパラメータを見つける最適化手法です。 実験やシミュレーションをはじめとした、 Amplify SDK では表現できないような関数の最適化において Amplify-BBOpt が効果を発揮します。 具体的には、以下のようなユースケースで活用されています。 **📐 構造設計・トポロジー最適化** 空調性能を最大化する建物形状・機器配置の最適化、構造物の変位を最小化するための部材配置・荷重条件の調整など **⚗️ 材料・化学** ある性能指標を最大化するための合成材料の組成の最適化、化学プラントにおける生産量の最大化など **🌊 CAE・シミュレーション** 物質濃度をより均一にするための攪拌条件の探索、流体デバイスの形状パラメータの最適化など **🔬 実験** ある実験結果を実現するための条件の探索など Amplify SDK の [ソルバークライアント](https://amplify.fixstars.com/ja/docs/amplify/v1/clients.md)、API トークン、制約ヘルパー関数をそのまま使えるため、普段の Amplify SDK の開発体験を活かしてブラックボックス最適化に取り組むことができます。 ```python from amplify import AmplifyAEClient, less_equal from amplify_bbopt import KMTrainer, Optimizer, RealVariable, blackbox # 最適化したい関数の定義 @blackbox def func( x: float = RealVariable(bounds=(0, 2.5)), y: float = RealVariable(bounds=(1.0, 5.0)), ) -> float: ... # ソルバークライアントの設定 client = AmplifyAEClient() client.token = "YOUR_TOKEN" # 制約条件の設定 constraints = less_equal(func.variables.x + func.variables.y, 5) # 最適化の実行 optimizer = Optimizer( blackbox=func, trainer=KMTrainer(), client=client, constraints=constraints ) optimizer.add_random_training_data(num_data=5) optimizer.optimize(num_iterations=10) ``` インストール方法や使い方については、以下のリンク先をご参照ください。 [**Amplify-BBOpt Documentation に移動**](https://amplify.fixstars.com/ja/docs/amplify-bbopt/v1) --- # Changelog ## v1.6.0 (May. 21, 2026) * Support quantum computers via the Amplify Quantum extension. * Support Ubuntu 26.04. * Support D-Wave Advantage2_system1. * Fix: Correct response data not being written to file with [`write_response_data`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.write_response_data) enabled in specific cases. v1.6.1 (Jun. 09, 2026) * Add `dwave`, `quantum`, and `full` installation options, replacing the `extra` option with `full`. * Fix: [`embed()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) now works without raising a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) in all environments. v1.6.2 (Jul. 10, 2026) * Improve performance of [`to_unconstrained_poly()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_unconstrained_poly). * Fix: Work around a potential dependency resolution error when installing Amplify Quantum. * Fix: [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) now works correctly with multiple client arguments. * Fix: [`__getitem__()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.__getitem__) now works correctly when a slice results in zero length. v1.6.3 (Aug. 21, 2026) * Support Amplify Quantum v1.3. * Improve performance of [`get_variables()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.get_variables). * General security hardening and robustness improvements. * Fix: [`to_unconstrained_poly()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_unconstrained_poly) now works correctly with inequality constraints. ## v1.5.0 (Apr. 05, 2026) * Overhaul the docstrings. * Support `dense_objective` endpoint of Amplify AE v1.1. * Support Gurobi Optimizer 12.0.3 on [`GurobiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient). * Change default degree reduction algorithm to [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) from [`IshikawaKZFD`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD). ## v1.4.0 (Sep. 19, 2025) * Support Amplify Annealing Engine v1.0 on [`AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient). * Support D-Wave Advantage2_system1.6. * Deprecate D-Wave Advantage2_prototype2.6. * Rename `AmplifyClient` to [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient). * Support [D-Wave solver identification updates](https://docs.dwavequantum.com/projects/leap_sapi/en/latest/release_notes.html#solver-identification-update-deprecated-sapi-field) and update the dependent dwave-system package to v1.33.0. * Update type hints for [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) and [`sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.sum). * Support DNP Annealing Software v1.0.4 on `DASClient`. * Fix: Substitute method for high-order polynomials now correctly reduces the degree to 2. * Fix: [`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) now correctly handles integer NumPy arrays. * Fix: [`FujitsuDA4Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) now correctly handles inequality constraints without constants. v1.4.1 (Oct 16, 2025) * Support Python 3.14, and Python 3.9 is no longer supported. * Fix: Resolved error of [`transpose`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) operation on an unassigned [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class instance. v1.4.2 (Feb. 14, 2026) * Support Gurobi Optimizer 12.0.3 on [`GurobiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient). * Support D-Wave Advantage2_system1.11. * Fix: Update type hints for [`sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum). ## v1.3.0 (Nov. 01, 2024) * Improve support for type annotations. * Improve accuracy of [upper and lower bounds estimates](https://amplify.fixstars.com/ja/docs/amplify/v1/penalty.md#penalty-function-auto-generation) in constraint construction. * Change advanced parameters of [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve), [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve), [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to), [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), [`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) and [`clamp()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) functions to keyword-only arguments for usability. * Support [Hitachi CMOS annealing](https://annealing-cloud.com/) on [`HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient). * Support DNP Annealing Software v1.0.3 on `DASClient`. * Support D-Wave Advantage2_prototype2.5. * Support conversion from [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). * Support input/output of models with [LP](https://www.gurobi.com/documentation/current/refman/lp_format.html) and [QPLIB](https://doi.org/10.1007/s12532-018-0147-4) format files. * [`Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) can be used as a mapping key for [`substitute()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.substitute), [`substitute()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.substitute) and [`is_satisfied()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.is_satisfied). * Support conversion from real variables to binary variables. * Add `compress_qpu_problem_data` attribute to [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient), [`LeapHybridSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) and [`LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient). * Add support for Python 3.13, and Python 3.8 is no longer supported. v1.3.1 (Nov. 18, 2024) * Fix: Prevent segmentation fault when accessing variables through [`get_variables()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.get_variables) or [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.variables) property on empty models. * Fix: Correct `total_elapsed_time` in [`SolverTiming`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.SolverTiming) to reference the proper timing value. * Fix: Update type hints for [`domain_wall()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) and [`array`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array). ## v1.2.0 (July 23, 2024) * Support TOSHIBA SQBM+ v2.0.3 on [`ToshibaSQBM2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client). * Support DNP Annealing Software v1.0.2 on `DASClient`. v1.2.1 (Aug. 06, 2024) * Change supported macOS to Monterey or later. ## v1.1.0 (May 13, 2024) * Support NEC Vector Annealing Service 2.0 on [`NECVA2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client). * Improve the efficiency of the [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) quadratization method and significantly reduce the number of auxiliary variables. * Add support for Linux ARM64. v1.1.1 (May 28, 2024) * Fix type hints for `Result` class. ## v1.0.0 (Jan. 27, 2024) * Release version 1.0. v1.0.2 (Feb. 20, 2024) * Add documents in English. * Fix redundant deprecation warnings. * Add `client.ocean` namespace for legacy compatibility. v1.0.3 (Mar. 01, 2024) * Support D-Wave Advantage_system6.4. * Support D-Wave Advantage2_prototype2.2. v1.0.4 (Mar. 15, 2024) * Fix a problem where SQBM request data is not sent correctly on Windows. v1.0.5 (Mar. 19, 2024) * Support D-Wave Advantage2_prototype2.3. --- # API Reference * [Algebra](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/algebra.md) * [Algebraic classes and numerics](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/algebra.md#algebraic-classes-and-numerics) * [Constraint](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/constraint.md) * [Constraint classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/constraint.md#constraint-classes-and-functions) * [Model](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/model.md) * [Model classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/model.md#model-classes-and-functions) * [Graph Embedding](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/graph.md) * [Graph classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/graph.md#graph-classes-and-functions) * [Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/client.md) * [Client classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/client.md#client-classes-and-functions) * [Solve](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/solve.md) * [Solve classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/solve.md#solve-classes-and-functions) * [Misc.](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/misc.md) * [Function](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/misc.md#function) * [Attribute](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/misc.md#attribute) * [Quantum](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/index.md) * [Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/client.md) * [Algorithm](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md) * [Minimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/minimize.md) * [Sampler](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/sampler.md) * [Circuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/circuit.md) * [Misc.](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/misc.md) * [Deprecated](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/deprecated.md) * [Deprecated classes and functions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/deprecated.md#deprecated-classes-and-functions) --- # Algebra ## Algebraic classes and numerics ### Class | | | | --- | --- | | [`amplify.Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | The polynomial class used for representing objective functions and constraints. | | [`amplify.PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) | A NumPy-like multidimensional array of polynomials. | | [`amplify.Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) | This class represents a quadratic objective in coefficient-matrix form, expressed as $x^\top Q x + p^\top x + c$. | | [`amplify.Variable`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) | Class for variable information. | | [`amplify.VariableGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) | Provides functionality to generate a decision variable or an array of decision variables. | ### Function | | | | --- | --- | | [`amplify.sum`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) | Sum elements of a polynomial array, sequence, or iterator. | | [`amplify.einsum`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) | Einstein summation for polynomial arrays and NumPy arrays. | | [`amplify.dot`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.dot.md#amplify.dot) | Compute dot product for polynomial arrays and NumPy arrays. | | [`amplify.matmul`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.matmul.md#amplify.matmul) | Matrix multiplication for polynomial arrays and NumPy arrays. | ### Attribute | | | | --- | --- | | [`amplify.newaxis`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.newaxis.md#amplify.newaxis) | | ### Enum | | | | --- | --- | | [`amplify.VariableType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) | Enum of decision variable types: Binary, Ising, Integer, and Real. | ### Misc | | | | --- | --- | | [`amplify.Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) | Base class for PolyArray dimension types. | | [`amplify.Dim0`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim0.md#amplify.Dim0) | A 0D PolyArray. | | [`amplify.Dim1`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1) | A 1D PolyArray. | | [`amplify.Dim2`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim2.md#amplify.Dim2) | A 2D PolyArray. | | [`amplify.Dim3`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim3.md#amplify.Dim3) | A 3D PolyArray. | | [`amplify.Dim4`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim4.md#amplify.Dim4) | A 4D PolyArray. | --- # Poly **`class Poly`** The polynomial class used for representing objective functions and constraints. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Poly.__init__) | __init__ | | [`as_dict`](#amplify.Poly.as_dict) | Return the dictionary representation of the polynomial. | | [`as_variable`](#amplify.Poly.as_variable) | Return the variable representation of the polynomial. | | [`asdict`](#amplify.Poly.asdict) | alias of [`as_dict()`](#amplify.Poly.as_dict) | | [`decode`](#amplify.Poly.decode) | Equivalent to [`evaluate()`](#amplify.Poly.evaluate). | | [`degree`](#amplify.Poly.degree) | Return the degree of the polynomial. | | [`evaluate`](#amplify.Poly.evaluate) | Evaluate the polynomial by substituting variables using the given values. | | [`is_linear`](#amplify.Poly.is_linear) | Return `True` if the polynomial is linear. | | [`is_number`](#amplify.Poly.is_number) | Return `True` if the polynomial is a constant polynomial. | | [`is_quadratic`](#amplify.Poly.is_quadratic) | Return `True` if the polynomial is quadratic. | | [`is_variable`](#amplify.Poly.is_variable) | Return `True` if the polynomial represents a single variable. | | [`substitute`](#amplify.Poly.substitute) | Assign numbers or other polynomials to variables in the polynomial. | **Attributes** | | | | --- | --- | | [`id`](#amplify.Poly.id) | Variable ID. | | [`lower_bound`](#amplify.Poly.lower_bound) | Lower bound of the variable. | | [`name`](#amplify.Poly.name) | Variable name. | | [`type`](#amplify.Poly.type) | Variable type. | | [`upper_bound`](#amplify.Poly.upper_bound) | Upper bound of the variable. | | [`variables`](#amplify.Poly.variables) | List of all variables in the polynomial. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Poly.Iterator) **`__next__(self) → tuple[tuple[Poly, ...], float]`** **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](#amplify.Poly), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`__add__(self, arg: Poly | float, /) → Poly`** **`__add__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** __add__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__and__(self, arg: Poly | bool, /) → Poly`** **`__and__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical AND of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 & q_1` is equivalent to `q_0 * q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__bool__(self) → bool`** Cast a polynomial to a boolean value. Only valid for constant polynomials that take values 0 or 1. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__float__(self) → float`** Cast a polynomial to a float value. Only valid for constant polynomials. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__imul__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__index__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self) → None`** **`__init__(self, arg: float, /) → None`** **`__init__(self, arg: Variable, /) → None`** __init__ > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (float) > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Variable) **`__int__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → Poly`** Logical NOT of a polynomial. This is meaningful only for polynomials that take values 0 or 1. `~q_0` is equivalent to `1 - q_0`. **戻り値の型:** [*Poly*](#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__ipow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__isub__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__iter__(self) → Iterator`** Iterate over the terms in the polynomial. Each term is represented as a tuple of a tuple of variables and a coefficient. For example, the polynomial `3 * x_0 * x_1 - 2 * x_0 + 5` is iterated as `((Poly(x_0), Poly(x_1)), 3.0)`, `((Poly(x_0),), -2.0)`, and `((), 5.0)`. **戻り値の型:** [*Iterator*](#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) → Poly`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__len__(self) → int`** Return the number of terms in the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__mul__(self, arg: Poly | float, /) → Poly`** **`__mul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __mul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) → Poly`** **戻り値の型:** [*Poly*](#amplify.Poly) **`__or__(self, arg: Poly | bool, /) → Poly`** **`__or__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical OR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 | q_1` is equivalent to `-q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__pos__(self) → Poly`** **戻り値の型:** [*Poly*](#amplify.Poly) **`__pow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](#amplify.Poly) **`__radd__(self, arg: float, /) → Poly`** **`__radd__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__rand__(self, arg: bool, /) → Poly`** **`__rand__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) → Poly`** **`__rmul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: bool, /) → Poly`** **`__ror__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: float, /) → Poly`** **`__rsub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: bool, /) → Poly`** **`__rxor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float, /) → Poly`** **`__sub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __sub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__truediv__(self, arg: float, /) → Poly`** **`__truediv__(self, arg: ndarray[], /) → PolyArray[Dim]`** __truediv__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → Poly`** **`__xor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical XOR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 ^ q_1` is equivalent to `-2 * q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`as_dict(self) → dict[tuple[int, ...], float]`** Return the dictionary representation of the polynomial. The polynomial is represented as a dictionary where keys are tuples of variable indices and values are coefficients. For example, the polynomial `3 * x_0 - 2 * x_0 * x_1 + 5` will be represented as `{(): 5, (0,): 3, (0, 1): -2}`. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`as_variable(self) → Variable`** Return the variable representation of the polynomial. Only valid for polynomials that represent a single variable. **戻り値の型:** [*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) → dict[tuple[int, ...], float]`** alias of [`as_dict()`](#amplify.Poly.as_dict) **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`decode(self, values: Values) → float`** **`decode(self, values: Values, default: float) → float`** **`decode(self, values: Values, default: None) → Poly`** Equivalent to [`evaluate()`](#amplify.Poly.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. Please see the migration guide for details: > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values) > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values) > * default (float) > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values) > * default (None) > > **Returns:** > > amplify.Poly: **`degree(self) → int`** Return the degree of the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** **`evaluate(self, values: Values, default: None) → Poly`** Evaluate the polynomial by substituting variables using the given values. This method is usually used to obtain optimization results in array form. If the keyword argument `default` is not specified, variables that are not specified in `values` will be substituted by a reasonable default value. If the keyword argument `default` is specified with a float value, variables that are not specified in `values` will be substituted by that value. If the keyword argument `default` is specified with `None`, variables that are not specified in `values` will remain as symbolic variables without substitution. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values that can be obtained from optimization results, e.g. `result.best.values`. > * default (float): The default value for variables not specified in `values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > * default (None): Set to `None` to keep variables not specified in `values` symbolic. > > **Returns:** > > amplify.Poly: **`is_linear(self) → bool`** Return `True` if the polynomial is linear. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) → bool`** Return `True` if the polynomial is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) → bool`** Return `True` if the polynomial is quadratic. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) → bool`** Return `True` if the polynomial represents a single variable. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → Poly`** Assign numbers or other polynomials to variables in the polynomial. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](#amplify.Poly)*,* [*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Key-value pairs of variables and replacement values. Each value can be a number or another polynomial. **戻り値の型:** [*Poly*](#amplify.Poly) **`property id`** Variable ID. Only valid for polynomials that represent a single variable. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property lower_bound`** Lower bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **戻り値の型:** [*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) **`property upper_bound`** Upper bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # PolyArray **`class PolyArray`** A NumPy-like multidimensional array of polynomials. Supports indexing, slicing, broadcast-compatible arithmetic, and utility methods for building optimization expressions. **Methods** | | | | --- | --- | | [`__init__`](#amplify.PolyArray.__init__) | | | [`copy`](#amplify.PolyArray.copy) | Return a copy of the array. | | [`decode`](#amplify.PolyArray.decode) | Deprecated alias of [`evaluate()`](#amplify.PolyArray.evaluate). | | [`diagonal`](#amplify.PolyArray.diagonal) | Return a diagonal extracted from the array. | | [`evaluate`](#amplify.PolyArray.evaluate) | Evaluate each element by substituting variable values. | | [`fill`](#amplify.PolyArray.fill) | Fill all elements with a single polynomial or scalar value. | | [`flatten`](#amplify.PolyArray.flatten) | Return a flattened 1D copy of the array. | | [`nonzero`](#amplify.PolyArray.nonzero) | Return the indices of non-zero elements. | | [`ravel`](#amplify.PolyArray.ravel) | Return a flattened 1D view when possible. | | [`repeat`](#amplify.PolyArray.repeat) | Repeat elements of the array. | | [`reshape`](#amplify.PolyArray.reshape) | Return a reshaped view of the array. | | [`roll`](#amplify.PolyArray.roll) | Roll array elements along an axis. | | [`substitute`](#amplify.PolyArray.substitute) | Substitute variables in all elements of the array. | | [`sum`](#amplify.PolyArray.sum) | Sum array elements over the specified axis or axes. | | [`swapaxes`](#amplify.PolyArray.swapaxes) | Return a view with two axes swapped. | | [`take`](#amplify.PolyArray.take) | Take elements from the array along an axis. | | [`to_list`](#amplify.PolyArray.to_list) | Convert the polynomial array to nested Python lists. | | [`to_numpy`](#amplify.PolyArray.to_numpy) | Convert the polynomial array to a NumPy `float64` ndarray. | | [`tolist`](#amplify.PolyArray.tolist) | Alias of [`to_list()`](#amplify.PolyArray.to_list). | | [`tonumpy`](#amplify.PolyArray.tonumpy) | Alias of [`to_numpy()`](#amplify.PolyArray.to_numpy). | | [`transpose`](#amplify.PolyArray.transpose) | Permute axes and return a transposed view. | | [`view`](#amplify.PolyArray.view) | Return a view of the same underlying data. | **Attributes** | | | | --- | --- | | [`T`](#amplify.PolyArray.T) | A transposed view of the array. | | [`flat`](#amplify.PolyArray.flat) | A 1D view of the array. | | [`ndim`](#amplify.PolyArray.ndim) | The number of dimensions of the array. | | [`shape`](#amplify.PolyArray.shape) | The shape of the array. | | [`size`](#amplify.PolyArray.size) | The total number of elements in the array. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → typing_extensions.Self`** **戻り値の型:** typing_extensions.Self **`__next__(self: Iterator[Dim1]) → Poly`** **`__next__(self: Iterator[Dim2]) → PolyArray[Dim1]`** **`__next__(self: Iterator[Dim3]) → PolyArray[Dim2]`** **`__next__(self: Iterator[Dim4]) → PolyArray[Dim3]`** **`__next__(self) → Poly | PolyArray[Dim]`** __next__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim1]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim2]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim3]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim4]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 5.** > > **Returns:** > > Poly | PolyArray[Dim]: **`__nb_signature__ = 'class Iterator(typing.Generic[__Dim])'`** **`__add__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__add__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__add__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__and__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__and__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__and__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__and__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __and__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__bool__(self) → bool`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__copy__(self) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](#amplify.PolyArray.copy). **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__deepcopy__(self, arg: dict, /) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](#amplify.PolyArray.copy). **パラメータ:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__eq__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__eq__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__float__(self) → float`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__getitem__(self: PolyArray[Dim0], arg: tuple[()]) → Poly`** **`__getitem__(self: PolyArray[Dim0], arg: EllipsisType) → PolyArray[Dim0]`** **`__getitem__(self: PolyArray[Dim1], arg: tuple[int] | int) → Poly`** **`__getitem__(self: PolyArray[Dim1], arg: EllipsisType | tuple[()] | slice | tuple[slice]) → PolyArray[Dim1]`** **`__getitem__(self: PolyArray[Dim2], arg: tuple[int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim2], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim2], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice], ) → PolyArray[Dim2]`** **`__getitem__(self: PolyArray[Dim3], arg: tuple[int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim3], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim3], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim3], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__(self: PolyArray[Dim4], arg: tuple[int, int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim4], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__( self: PolyArray[Dim4], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice], ) → PolyArray[Dim4]`** **`__getitem__(self: PolyArray[Dim], arg: tuple | slice | EllipsisType | int | None) → PolyArray[Dim]`** Return a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]): self > * arg (tuple[()]): An index specified as an integer, slice, ellipsis, or newaxis. > > **Returns:** > > amplify.Poly: Selected element or slice, depending on the index. > > **Raises:** > > IndexError: If any index is out of bounds. > TypeError: If index type is invalid. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (types.EllipsisType) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (tuple[int] | int) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (tuple[int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 14.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 15.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 16.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim4]: > [!NOTE] > > **Overload 17.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (tuple | slice | types.EllipsisType | int | None) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **サンプル** > > ```python > from amplify import VariableGenerator, newaxis > > q = VariableGenerator().array("Binary", (3, 4)) > print(q[1, 2]) # Output: Poly(q_{1,2}) > print(q[0]) # Output: PolyArray([q_{0,0}, q_{0,1}, q_{0,2}, q_{0,3}]) > print(q[:, 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[..., 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[1, newaxis]) # Output: PolyArray([[q_{1,0}, q_{1,1}, q_{1,2}, q_{1,3}]]) > ``` **`__iadd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__iadd__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__iadd__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__iadd__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__iadd__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__iadd__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__iadd__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__iadd__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __iadd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__iand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__iand__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__iand__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __iand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__imul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__imul__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__imul__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__imul__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__imul__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__imul__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__imul__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__imul__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __imul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__index__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) → None`** **パラメータ:** **object** (*ndarray*) **`__int__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__ior__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ior__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ior__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ior__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ior__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ipow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__isub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__isub__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__isub__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__isub__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__isub__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__isub__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__isub__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__isub__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __isub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iter__(self) → Iterator[_Dim]`** Iterate over the first axis of the polynomial array. If the array has one or fewer dimensions, each yielded item is a polynomial. If the array has two or more dimensions, each yielded item is a subarray with one fewer dimension. **戻り値の型:** [*Iterator*](#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__ixor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ixor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ixor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ixor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ixor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__len__(self) → int`** Return the number of elements along the first axis. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__matmul__(self, arg: amplify.PolyArray | ndarray[], /) → Poly | PolyArray[_Dim]`** Perform matrix multiplication on two polynomial arrays. For arrays with three or more dimensions, the last two dimensions are treated as matrices and the remaining dimensions as batch dimensions. Broadcasting is applied to the batch dimensions. **パラメータ:** **arg** ([*PolyArray*](#amplify.PolyArray) *| ndarray*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](#amplify.PolyArray)[_Dim] **`__mul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__mul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__mul__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__mul__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ne__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__ne__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__neg__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__or__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__or__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__or__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__or__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __or__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__pos__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__radd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__radd__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) → Poly | PolyArray[__Dim]`** **パラメータ:** **arg** (*NDArray |* [*PolyArray*](#amplify.PolyArray)*[__Dim]*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](#amplify.PolyArray)[__Dim] **`__rmul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rmul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ror__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rsub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rxor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__setitem__( self, arg: tuple | slice | types.EllipsisType | int | None, value: amplify.Poly | float | int | list | ndarray[] | amplify.PolyArray, ) → None`** Assign a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. **パラメータ:** * **arg** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple) *|* [*slice*](https://docs.python.org/3/library/functions.html#slice) *|* [*EllipsisType*](https://docs.python.org/3/library/types.html#types.EllipsisType) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- An index specified as an integer, slice, ellipsis, or newaxis. * **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) -- Value to assign, compatible with the indexed shape. **例外:** * [**IndexError**](https://docs.python.org/3/library/exceptions.html#IndexError) -- If any index is out of bounds. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) -- If index type is invalid or value shape is incompatible. **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__sub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__sub__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__sub__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__truediv__(self, arg: float | int, /) → PolyArray[_Dim]`** **`__truediv__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__xor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__xor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__xor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __xor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`copy(self) → PolyArray[_Dim]`** Return a copy of the array. Each polynomial in the array is copied as well. **戻り値:** Copy of the array. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`decode(self, values: Values) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: None) → PolyArray[_Dim]`** Deprecated alias of [`evaluate()`](#amplify.PolyArray.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`diagonal(self: PolyArray[Dim], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim]`** **`diagonal(self: PolyArray[Dim2], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim1]`** **`diagonal(self: PolyArray[Dim3], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim2]`** **`diagonal(self: PolyArray[Dim4], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim3]`** Return a diagonal extracted from the array. Take the diagonal along `axis1` and `axis2` with optional `offset`. Unlike NumPy, return a copy. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim1]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim2]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim3]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. **`evaluate(self, values: Values) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: None) → PolyArray[_Dim]`** Evaluate each element by substituting variable values. Pass optimization result values to get a NumPy array with the same shape. The behavior for unassigned variables can be controlled by `default`. When `default=None`, keep variables not present in `values` symbolic and return a [`PolyArray`](#amplify.PolyArray). > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`fill(self, value: Poly | float | int) → None`** Fill all elements with a single polynomial or scalar value. **パラメータ:** **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)) -- The value to assign to all elements. **`flatten(self) → PolyArray[Dim1]`** Return a flattened 1D copy of the array. **戻り値:** Flattened copy. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) → tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **戻り値:** Tuple of index arrays, one for each dimension. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)[dtype=uint64], ...] **`ravel(self) → PolyArray[Dim1]`** Return a flattened 1D view when possible. **戻り値:** Flattened view when possible. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`repeat(self, repeats: int | list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`repeat(self, repeats: int | list[int], axis: int) → PolyArray[_Dim]`** Repeat elements of the array. When `axis` is `None`, repetitions are applied to the flattened array, and a 1D array is returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (typing.Literal[None]): Axis along which to repeat. If `None`, the array is repeated as a flattened array. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (int): Axis along which to repeat. If `None`, the array is repeated as a flattened array. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. **`reshape(self, shape: int | tuple[int]) → PolyArray[Dim1]`** **`reshape(self, shape: tuple[int, int]) → PolyArray[Dim2]`** **`reshape(self, shape: tuple[int, int, int]) → PolyArray[Dim3]`** **`reshape(self, shape: tuple[int, int, int, int]) → PolyArray[Dim4]`** **`reshape(self, arg0: int, arg1: int) → PolyArray[Dim2]`** **`reshape(self, arg0: int, arg1: int, arg2: int) → PolyArray[Dim3]`** **`reshape(self, arg0: int, arg1: int, arg2: int, arg3: int) → PolyArray[Dim4]`** **`reshape(self, shape: tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]) → PolyArray[Dim]`** **`reshape(self, *shape: int) → PolyArray[Dim]`** Return a reshaped view of the array. The new shape must be compatible with the current size. At most one `-1` is allowed to infer an unknown dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * shape (int | tuple[int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim1]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * shape (tuple[int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * shape (tuple[int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * shape (tuple[int, int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > * arg3 (int): Fourth dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * shape (tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * \*shape (int): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. **`roll(self, shift: int, axis: int | None = None) → PolyArray[_Dim]`** Roll array elements along an axis. If `axis` is `None`, the array is rolled in flattened order. Unlike NumPy, `roll` is provided as a method, and cannot roll multiple axes simultaneously. **パラメータ:** * **shift** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The shift amount. * **axis** ([*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- Axis to roll. If `None`, the array is rolled as a flattened array. Defaults to `None`. **戻り値:** Array with rolled elements. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If axis is out of bounds. **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → PolyArray[_Dim]`** Substitute variables in all elements of the array. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- A mapping from variables to numeric values or polynomials. **戻り値:** Array after substitution. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`sum(self, axis: Literal[None] = None) → Poly`** **`sum(self: PolyArray[Dim1], axis: int | tuple[int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: tuple[int, int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: int | tuple[int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int, int]) → Poly`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: int | tuple[int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int, int]) → Poly`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: int | tuple[int]) → PolyArray[Dim3]`** **`sum(self: PolyArray[_Dim], axis: tuple[()]) → PolyArray[_Dim]`** **`sum(self: PolyArray[Dim], axis: int | tuple[int, ...]) → Poly | PolyArray[Dim]`** Sum array elements over the specified axis or axes. Without `axis`, all elements are summed into a single polynomial. With `axis`, the output type depends on the reduced dimensions. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axis (typing.Literal[None]): The axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim3]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[_Dim]): self > * axis (tuple[()]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[_Dim]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * axis (int | tuple[int, ...]): The axis or axes to reduce. > > **Returns:** > > Poly | PolyArray[Dim]: Summation result. Shape depends on `axis`. **`swapaxes(self, axis1: int, axis2: int) → PolyArray[_Dim]`** Return a view with two axes swapped. **パラメータ:** * **axis1** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The first axis. * **axis2** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The second axis. **戻り値:** Array with the two axes swapped. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If either axis is out of bounds. **`take(self, indices: int, axis: Literal[None] = None) → Poly`** **`take(self, indices: list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim], indices: int | list[int], axis: int | None = None) → PolyArray[Dim]`** **`take(self: PolyArray[Dim2], indices: int, axis: int) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim2], indices: list[int], axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: int, axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: list[int], axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: int, axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: list[int], axis: int) → PolyArray[Dim4]`** Take elements from the array along an axis. If `axis` is `None`, indices are interpreted on the flattened array. Elements are always copied, even when a view could be returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * indices (int): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.Poly: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * indices (list[int]): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * indices (int | list[int]): A single index or a list of indices. > * axis (int | None): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim4]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. **`to_list(self: PolyArray[Dim0]) → Poly`** **`to_list(self: PolyArray[Dim1]) → list[Poly]`** **`to_list(self: PolyArray[Dim2]) → list[list[Poly]]`** **`to_list(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`to_list(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`to_list(self: PolyArray[Dim]) → list`** Convert the polynomial array to nested Python lists. For 0D arrays, return the scalar polynomial itself. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`to_numpy(self) → numpy.ndarray[dtype=float64]`** Convert the polynomial array to a NumPy `float64` ndarray. **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`tolist(self: PolyArray[Dim0]) → Poly`** **`tolist(self: PolyArray[Dim1]) → list[Poly]`** **`tolist(self: PolyArray[Dim2]) → list[list[Poly]]`** **`tolist(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`tolist(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`tolist(self: PolyArray[Dim]) → list`** Alias of [`to_list()`](#amplify.PolyArray.to_list). > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`tonumpy(self) → numpy.ndarray[dtype=float64]`** Alias of [`to_numpy()`](#amplify.PolyArray.to_numpy). **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`transpose(self, axes: tuple[int, ...] | None = None) → PolyArray[_Dim]`** **`transpose(self, *axes: int) → PolyArray[_Dim]`** Permute axes and return a transposed view. If `axes` is not specified, the axis order is reversed. Negative axes are supported and are normalized using the array dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axes (tuple[int, ...] | None): Axis permutation. If `None`, the axis order is reversed. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * \*axes (int): Axis permutation specified as positional arguments. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. **`view(self) → PolyArray[_Dim]`** Return a view of the same underlying data. **戻り値:** View of the same underlying data. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`property T`** A transposed view of the array. Equivalent to [`transpose()`](#amplify.PolyArray.transpose) with default axis order. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__nb_signature__ = 'class PolyArray(typing.Generic[_Dim])'`** **`property flat`** A 1D view of the array. Unlike [`flatten()`](#amplify.PolyArray.flatten), this property is a view. **戻り値の型:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property shape`** The shape of the array. Read this property to get the current shape as a tuple. Set this property to reshape the array in-place if the requested shape is compatible with the current size. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...] **`property size`** The total number of elements in the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) --- # Matrix **`class Matrix`** This class represents a quadratic objective in coefficient-matrix form, expressed as $x^\top Q x + p^\top x + c$. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Matrix.__init__) | | | [`evaluate`](#amplify.Matrix.evaluate) | Evaluate the matrix objective using the provided variable assignments. | | [`to_poly`](#amplify.Matrix.to_poly) | Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). | **Attributes** | | | | --- | --- | | [`constant`](#amplify.Matrix.constant) | Constant term `c`. | | [`linear`](#amplify.Matrix.linear) | Linear coefficient array `p`. | | [`quadratic`](#amplify.Matrix.quadratic) | Quadratic coefficient array `Q`. | | [`variable_array`](#amplify.Matrix.variable_array) | Variable array `x` used in the matrix representation. | **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) → str`** Return a developer-friendly string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** Return a human-readable string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** Evaluate the matrix objective using the provided variable assignments. Substitute variables in `x` with the given `values` and evaluate `x^\top Q x + p^\top x + c`. If `default` is not specified, variables not included in `values` are substituted with a reasonable default value. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: Evaluated objective value. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > * default (float): Default value used for variables not included in `values`. > > **Returns:** > > float: Evaluated objective value. **`to_poly(self) → Poly`** Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **戻り値:** Polynomial converted from this matrix form. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property constant`** Constant term `c`. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`property linear`** Linear coefficient array `p`. For a variable array `x` with `n` dimensions, the linear coefficient array `p` also has `n` dimensions. When `x` is one-dimensional, `p` is a 1D vector. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property quadratic`** Quadratic coefficient array `Q`. For a variable array `x` with `n` dimensions, the quadratic coefficient array `Q` has `2n` dimensions. When `x` is one-dimensional, `Q` is a 2D matrix. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property variable_array`** Variable array `x` used in the matrix representation. Use this array when constructing constraints for a matrix objective. **戻り値:** Variable array used in this representation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] --- # Variable **`class Variable`** Class for variable information. Instances are typically obtained via [`as_variable()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) or [`variables`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.variables). **Methods** | | | | --- | --- | | [`__init__`](#amplify.Variable.__init__) | | **Attributes** | | | | --- | --- | | [`id`](#amplify.Variable.id) | Variable ID number. | | [`lower_bound`](#amplify.Variable.lower_bound) | Lower bound of the variable. | | [`name`](#amplify.Variable.name) | Variable name. | | [`type`](#amplify.Variable.type) | Variable type. | | [`upper_bound`](#amplify.Variable.upper_bound) | Upper bound of the variable. | **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__repr__(self) → str`** Return a developer-friendly string representation of the variable. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** Return a human-readable string representation of the variable. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property id`** Variable ID number. An integer assigned starting from `0` in order of issuance. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property lower_bound`** Lower bound of the variable. This property is valid for Integer or Real variables. [`None`](https://docs.python.org/3/library/constants.html#None) means $-\infty$. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. **戻り値:** Corresponding value in [`VariableType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType). **戻り値の型:** [*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) **`property upper_bound`** Upper bound of the variable. This property is valid for Integer or Real variables. [`None`](https://docs.python.org/3/library/constants.html#None) means $+\infty$. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* --- # VariableGenerator **`class VariableGenerator`** Provides functionality to generate a decision variable or an array of decision variables. **Methods** | | | | --- | --- | | [`__init__`](#amplify.VariableGenerator.__init__) | | | [`array`](#amplify.VariableGenerator.array) | Generate an array of variables. | | [`matrix`](#amplify.VariableGenerator.matrix) | Generate a quadratic polynomial in coefficient-matrix form. | | [`scalar`](#amplify.VariableGenerator.scalar) | Generate a scalar variable. | **Attributes** | | | | --- | --- | | [`variables`](#amplify.VariableGenerator.variables) | List of all variables created. | **`__init__(self) → None`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[()], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim0]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[int] | int, bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim1]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[int, int], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim2]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[int, int, int], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim3]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[int, int, int, int], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim4]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, arg0: int, ) → PolyArray[Dim1]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, arg0: int, arg1: int, ) → PolyArray[Dim2]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, arg0: int, arg1: int, arg2: int, ) → PolyArray[Dim3]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, arg0: int, arg1: int, arg2: int, arg3: int, ) → PolyArray[Dim4]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → PolyArray[Dim]`** **`array( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, *shape: int, ) → PolyArray[Dim]`** Generate an array of variables. Variables are generated in an n-dimensional array. Each variable has the same type and bounds (if any). > [!NOTE] > > **Overload 1.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[()]): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim0]: Generated variable array. > [!NOTE] > > **Overload 2.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[int] | int): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim1]: Generated variable array. > [!NOTE] > > **Overload 3.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[int, int]): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim2]: Generated variable array. > [!NOTE] > > **Overload 4.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[int, int, int]): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim3]: Generated variable array. > [!NOTE] > > **Overload 5.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[int, int, int, int]): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim4]: Generated variable array. > [!NOTE] > > **Overload 6.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * arg0 (int): First element of the NumPy-like shape of the array. > > **Returns:** > > amplify.PolyArray[Dim1]: Generated variable array. > [!NOTE] > > **Overload 7.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * arg0 (int): First element of the NumPy-like shape of the array. > * arg1 (int): Second element of the NumPy-like shape of the array. > > **Returns:** > > amplify.PolyArray[Dim2]: Generated variable array. > [!NOTE] > > **Overload 8.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * arg0 (int): First element of the NumPy-like shape of the array. > * arg1 (int): Second element of the NumPy-like shape of the array. > * arg2 (int): Third element of the NumPy-like shape of the array. > > **Returns:** > > amplify.PolyArray[Dim3]: Generated variable array. > [!NOTE] > > **Overload 9.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * arg0 (int): First element of the NumPy-like shape of the array. > * arg1 (int): Second element of the NumPy-like shape of the array. > * arg2 (int): Third element of the NumPy-like shape of the array. > * arg3 (int): Fourth element of the NumPy-like shape of the array. > > **Returns:** > > amplify.PolyArray[Dim4]: Generated variable array. > [!NOTE] > > **Overload 10.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > **If either of the bounds is not specified, it will be unbounded in that direction.** > > Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > **Each variable is automatically assigned a name consisting of this string and a specific index.** > > Defaults to `''`. > > **Returns:** > > amplify.PolyArray[Dim]: Generated variable array. > [!NOTE] > > **Overload 11.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **\*shape (int): The NumPy-like shape of the variable array.** > > For example, `(3, 4)` generates a two-dimensional variable array with 3 rows and 4 columns. > > **Returns:** > > amplify.PolyArray[Dim]: Generated variable array. **`matrix( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, shape: int | tuple[int, ...], bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → Matrix`** **`matrix( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, *shape: int, ) → Matrix`** Generate a quadratic polynomial in coefficient-matrix form. A variable array of the specified shape is generated together with the coefficient matrix. The polynomial represented by the coefficient matrix is defined as $(x^T) Q x + (p^T) x + c$, where Q is the quadratic coefficient matrix, p is the linear coefficient array, c is the constant term, and x is the variable array. > [!NOTE] > > **Overload 1.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **shape (int | tuple[int, ...]): The shape of the array. It can be specified in two ways:** > > * A single integer, e.g., 5, which will generate a one-dimensional variable array with 5 elements. > * A NumPy-like shape, e.g., `(3, 4)`, which will generate a two-dimensional variable array with 3 rows and 4 columns. > * **bounds (tuple[float | None, ...]): The lower and upper bounds of the variables.** > > If either bound is omitted, the variable is unbounded in that direction. Defaults to `(None, None)`. > * **name (str): The name of the variable array.** > > Each variable is automatically assigned a name consisting of this string and a specific index. Defaults to `''`. > > **Returns:** > > amplify.Matrix: Coefficient matrix and generated variable array. > [!NOTE] > > **Overload 2.** > > **Args:** > > * type (typing.Literal['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType): The type of variables. > * **\*shape (int): The shape of the array.** > > This overload is provided for backward compatibility. > > **Returns:** > > amplify.Matrix: Coefficient matrix and generated variable array. **`scalar( self, type: Literal['Binary', 'Ising', 'Integer', 'Real'] | VariableType, bounds: tuple[float | None, ...] = (None, None), name: str = '', ) → Poly`** Generate a scalar variable. The variable will have the specified type and bounds (if any). **パラメータ:** * **type** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Binary', 'Ising', 'Integer', 'Real'] | amplify.VariableType*) -- The type of the variable. * **bounds** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)*[*[*float*](https://docs.python.org/3/library/functions.html#float) *| None, ...]*) -- The lower and upper bounds of the variable. Defaults to `(None, None)`. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- The name of the variable. Defaults to `''`. **戻り値:** Generated variable. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property variables`** List of all variables created. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # sum **`sum(array: PolyArray[_Dim], axis: Literal[None] = None) → Poly`** **`sum(array: PolyArray[Dim1], axis: int | tuple[int]) → Poly`** **`sum(array: PolyArray[Dim2], axis: tuple[int, int]) → Poly`** **`sum(array: PolyArray[Dim2], axis: int | tuple[int]) → PolyArray[Dim1]`** **`sum(array: PolyArray[Dim3], axis: tuple[int, int, int]) → Poly`** **`sum(array: PolyArray[Dim3], axis: tuple[int, int]) → PolyArray[Dim1]`** **`sum(array: PolyArray[Dim3], axis: int | tuple[int]) → PolyArray[Dim2]`** **`sum(array: PolyArray[Dim4], axis: tuple[int, int, int, int]) → Poly`** **`sum(array: PolyArray[Dim4], axis: tuple[int, int, int]) → PolyArray[Dim1]`** **`sum(array: PolyArray[Dim4], axis: tuple[int, int]) → PolyArray[Dim2]`** **`sum(array: PolyArray[Dim4], axis: int | tuple[int]) → PolyArray[Dim3]`** **`sum(array: PolyArray[_Dim], axis: tuple[()]) → PolyArray[_Dim]`** **`sum(array: PolyArray[Dim], axis: int | tuple[int, ...]) → Poly | PolyArray[Dim]`** **`sum(arg: Sequence[Poly | float] | Iterator[Poly | float]) → Poly`** **`sum( arg: Sequence[Constraint | ConstraintList] | Iterator[Constraint | ConstraintList], ) → ConstraintList`** **`sum(stop: int, func: Callable[[int], Poly]) → Poly`** **`sum(start: int, stop: int, func: Callable[[int], Poly]) → Poly`** **`sum(start: int, stop: int, step: int, func: Callable[[int], Poly]) → Poly`** **`sum(sequence: Sequence[_T], func: Callable[[_T], Poly]) → Poly`** **`sum(iterable: Iterable[_T], func: Callable[[_T], Poly]) → Poly`** **`sum(iterator: Iterator[_T], func: Callable[[_T], Poly]) → Poly`** **`sum(iterable: Iterable, /, start: object = 0) → Any`** Sum elements of a polynomial array, sequence, or iterator. Sum a sequence or iterator efficiently. Sum a sequence or iterator of constraints. Deprecated overload of [`sum()`](#amplify.sum). Map each element and sum the mapped values. When the argument is a [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray), this function is equivalent to the [`sum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.sum) method of [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray). If `axis` is `None`, all elements are summed and a [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) is returned. If `axis` is specified, reduction is applied along that axis and a [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) or [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) is returned depending on the result shape. When the argument elements are [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint), or [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList), this function behaves like Python's built-in [`sum()`](#amplify.sum) but uses an algorithm that reduces intermediate growth during accumulation. In this context, built-in [`sum()`](#amplify.sum) can show $O(n^2)$-like behavior, while this function is typically closer to $O(n)$. Here, $n$ denotes the total number of terms in a [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) or the total number of elements in a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList). The overload that takes `start`, `stop`, `func` has been deprecated since Amplify v1.0.0 and will be removed in a future release. Use `amplify.sum(iterable, func)` instead. If a sequence (iterable or iterator) and a function are provided, this function maps each element to a polynomial and sums the mapped polynomials. > [!NOTE] > > **Overload 1.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * axis (typing.Literal[None]): Axis or axes to reduce. If `None`, sum all elements. Defaults to `None`. > > **Returns:** > > amplify.Poly: Summed polynomial or polynomial array. > > **Raises:** > > ValueError: If `axis` is out of bounds or invalid. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * axis (int | tuple[int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * axis (tuple[int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * axis (int | tuple[int]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * axis (tuple[int, int]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * axis (int | tuple[int]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * axis (tuple[int, int]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * axis (int | tuple[int]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * axis (tuple[()]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * axis (int | tuple[int, ...]): Axis or axes to reduce. If `None`, sum all elements. > > **Returns:** > > amplify.Poly | amplify.PolyArray[Dim]: Summed polynomial or polynomial array. > > **Raises:** > > ValueError: If `axis` is out of bounds or invalid. > [!NOTE] > > **Overload 14.** > > **Args:** > > * arg (collections.abc.Sequence[amplify.Poly | float] | collections.abc.Iterator[amplify.Poly | float]): Input sequence or iterator to sum. > > **Returns:** > > amplify.Poly: Summed result. > [!NOTE] > > **Overload 15.** > > **Args:** > > * arg (collections.abc.Sequence[amplify.Constraint | amplify.ConstraintList] | collections.abc.Iterator[amplify.Constraint | amplify.ConstraintList]): Input sequence or iterator to sum. > > **Returns:** > > amplify.ConstraintList: Sum of all elements. > [!NOTE] > > **Overload 16.** > > **Args:** > > * stop (int) > * func (collections.abc.Callable[[int], amplify.Poly]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 17.** > > **Args:** > > * start (int) > * stop (int) > * func (collections.abc.Callable[[int], amplify.Poly]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 18.** > > **Args:** > > * start (int) > * stop (int) > * step (int) > * func (collections.abc.Callable[[int], amplify.Poly]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 19.** > > **Args:** > > * sequence (Sequence[_T]): Sequence or iterator of elements to map and sum. > * func (Callable[[_T], Poly]): Mapping function applied to each element. > > **Returns:** > > amplify.Poly: Sum of mapped elements. > [!NOTE] > > **Overload 20.** > > **Args:** > > * iterable (Iterable[_T]): Sequence or iterator of elements to map and sum. > * func (Callable[[_T], Poly]): Mapping function applied to each element. > > **Returns:** > > amplify.Poly: Sum of mapped elements. > [!NOTE] > > **Overload 21.** > > **Args:** > > * iterator (Iterator[_T]): Sequence or iterator of elements to map and sum. > * func (Callable[[_T], Poly]): Mapping function applied to each element. > > **Returns:** > > amplify.Poly: Sum of mapped elements. > [!NOTE] > > **Overload 22.** > > **Args:** > > * iterable (Iterable) > * start (object): Defaults to `0`. > > **Returns:** > > typing.Any: --- # einsum **`einsum(subscripts: str, *operands: PolyArray | ndarray) → Poly | PolyArray[Dim]`** Einstein summation for polynomial arrays and NumPy arrays. Compute the expression defined by `subscripts` using `PolyArray` and/or NumPy operands, similar to `numpy.einsum`. **パラメータ:** * **subscripts** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Subscript notation. For example, `'ij,jk->ik'` for matrix multiplication or `'i,i->'` for dot product. * `*operands` ([*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) *|* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)) -- Operands (`PolyArray` or `numpy.ndarray`). **戻り値:** Computed result for `subscripts`. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] **例外:** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) -- If no operand is provided or an operand type is invalid. --- # dot **`dot(arg0: amplify.PolyArray, arg1: amplify.PolyArray | ndarray[], /) → Poly | PolyArray[Dim]`** **`dot(arg0: ndarray[], arg1: amplify.PolyArray, /) → Poly | PolyArray[Dim]`** Compute dot product for polynomial arrays and NumPy arrays. Specifically, - If both operands are 1-D, perform an inner product and return a [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). - If either operand is 0-D, perform element-wise multiplication. - If the left operand is 1-D or more and the right operand is 2-D or more, compute the product and sum over the last axis of the left operand and the second-to-last axis of the right operand. - If the right operand is 1-D, it is treated as a 2-D array with shape (N, 1). > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg0 (amplify.PolyArray) > * arg1 (amplify.PolyArray | ndarray) > > **Returns:** > > amplify.Poly | amplify.PolyArray[Dim]: Dot-product result. > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg0 (ndarray) > * arg1 (amplify.PolyArray) > > **Returns:** > > amplify.Poly | amplify.PolyArray[Dim]: Dot-product result. --- # matmul **`matmul(arg0: amplify.PolyArray, arg1: amplify.PolyArray | ndarray[], /) → Poly | PolyArray[Dim]`** **`matmul(arg0: ndarray[], arg1: amplify.PolyArray, /) → Poly | PolyArray[Dim]`** Matrix multiplication for polynomial arrays and NumPy arrays. If both operands are 2-D, perform matrix multiplication. If one operand is 1-D and the other is 2-D, perform vector-matrix or matrix-vector multiplication. If both operands are 1-D, perform dot product. If either operand is a 3-D array or higher, perform batched matrix multiplication. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg0 (amplify.PolyArray) > * arg1 (amplify.PolyArray | ndarray) > > **Returns:** > > amplify.Poly | amplify.PolyArray[Dim]: Matrix multiplication result. > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg0 (ndarray) > * arg1 (amplify.PolyArray) > > **Returns:** > > amplify.Poly | amplify.PolyArray[Dim]: --- # newaxis **`newaxis = None`** --- # VariableType **`class VariableType`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Enum of decision variable types: Binary, Ising, Integer, and Real. **Members** **`Binary = 0`** **`Integer = 2`** **`Ising = 1`** **`Real = 3`** --- # Dim **`class Dim`** Base class for PolyArray dimension types. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim0 **`class Dim0`** ベースクラス: [`Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 0D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim1 **`class Dim1`** ベースクラス: [`Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 1D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim2 **`class Dim2`** ベースクラス: [`Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 2D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim3 **`class Dim3`** ベースクラス: [`Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 3D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim4 **`class Dim4`** ベースクラス: [`Dim`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 4D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Constraint ## Constraint classes and functions ### Class | | | | --- | --- | | [`amplify.Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) | Constraint class representing equality or inequality conditions on polynomial expressions. | | [`amplify.ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) | List-like container of [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) objects. | ### Functions | | | | --- | --- | | [`amplify.equal_to`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) | Create an equality constraint. | | [`amplify.one_hot`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) | Create a one-hot constraint. | | [`amplify.less_equal`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) | Create a less-than-or-equal constraint. | | [`amplify.greater_equal`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) | Create a greater-than-or-equal constraint. | | [`amplify.clamp`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) | Create a range constraint. | | [`amplify.domain_wall`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) | Create domain wall constraints for a variable array. | ### Enum | | | | --- | --- | | [`amplify.PenaltyFormulation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation) | Penalty function formulation strategy used for constraint conversion. | --- # Constraint **`class Constraint`** Constraint class representing equality or inequality conditions on polynomial expressions. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Constraint.__init__) | Construct a constraint from bounds and a penalty polynomial. | | [`is_satisfied`](#amplify.Constraint.is_satisfied) | Check whether the constraint is satisfied. | **Attributes** | | | | --- | --- | | [`conditional`](#amplify.Constraint.conditional) | Constraint condition as `(left, op, right)` tuple. | | [`label`](#amplify.Constraint.label) | Constraint label used for identification. | | [`penalty`](#amplify.Constraint.penalty) | Penalty polynomial associated with this constraint. | | [`weight`](#amplify.Constraint.weight) | Constraint weight. | **`__add__(self, arg: Constraint, /) → ConstraintList`** Combine two constraints into a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList). **パラメータ:** **arg** ([*Constraint*](#amplify.Constraint)) **戻り値:** A new [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) containing both constraints. **戻り値の型:** [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__imul__(self, arg: float, /) → Constraint`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`__init__( self, left: Poly, bounds: tuple[float | None, float | None], penalty: Poly, label: str = '', threshold: float = 0.0, ) → None`** **`__init__(self, left: Poly, eq: float, penalty: Poly, label: str = '', threshold: float = 0.0) → None`** **`__init__(self, left: Poly, le: float, penalty: Poly, label: str = '', threshold: float = 0.0) → None`** **`__init__(self, left: Poly, ge: float, penalty: Poly, label: str = '', threshold: float = 0.0) → None`** Construct a constraint from bounds and a penalty polynomial. > [!NOTE] > > **Overload 1.** > > **Args:** > > * left (amplify.Poly): Left-hand side polynomial. > * bounds (tuple[float | None, float | None]): Bounds as `(lower, upper)`. At least one must be specified. > * penalty (amplify.Poly): Penalty polynomial. > * label (str): Constraint label. Defaults to `''`. > * threshold (float): Satisfaction threshold. Defaults to `0.0`. > [!NOTE] > > **Overload 2.** > > **Args:** > > * left (amplify.Poly): Left-hand side polynomial. > * eq (float): Right-hand side value for equality. > * penalty (amplify.Poly): Penalty polynomial. > * label (str): Constraint label. Defaults to `''`. > * threshold (float): Satisfaction threshold. Defaults to `0.0`. > [!NOTE] > > **Overload 3.** > > **Args:** > > * left (amplify.Poly): Left-hand side polynomial. > * le (float): Upper bound value. > * penalty (amplify.Poly): Penalty polynomial. > * label (str): Constraint label. Defaults to `''`. > * threshold (float): Satisfaction threshold. Defaults to `0.0`. > [!NOTE] > > **Overload 4.** > > **Args:** > > * left (amplify.Poly): Left-hand side polynomial. > * ge (float): Lower bound value. > * penalty (amplify.Poly): Penalty polynomial. > * label (str): Constraint label. Defaults to `''`. > * threshold (float): Satisfaction threshold. Defaults to `0.0`. **`__itruediv__(self, arg: float, /) → Constraint`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`__mul__(self, arg: float, /) → Constraint`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: int, /) → Constraint`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) → Constraint`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__truediv__(self, arg: float, /) → Constraint`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Constraint*](#amplify.Constraint) **`is_satisfied(self, values: Values) → bool`** **`is_satisfied( self, mapping: Mapping[Poly, float | int] | Mapping[Variable, float | int], ) → bool`** Check whether the constraint is satisfied. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values for variables, typically `result.best.values`. > > **Returns:** > > bool: `True` if the condition is satisfied. > [!NOTE] > > **Overload 2.** > > **Args:** > > * mapping (collections.abc.Mapping[amplify.Poly, float | int] | collections.abc.Mapping[amplify.Variable, float | int]): Mapping from variable to numeric value. > > **Returns:** > > bool: `True` if the condition is satisfied. **`property conditional`** Constraint condition as `(left, op, right)` tuple. **戻り値:** Left polynomial, operator literal, and right-hand side value(s). **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)['EQ', 'GE', 'GT', 'LE', 'LT', 'BW'], float | tuple[float, float]] **`property label`** Constraint label used for identification. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property penalty`** Penalty polynomial associated with this constraint. **戻り値:** Penalty expression used for this constraint. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property weight`** Constraint weight. Larger values enforce this constraint more strongly when penalty methods are used. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) --- # ConstraintList **`class ConstraintList`** List-like container of [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) objects. **Methods** | | | | --- | --- | | [`__init__`](#amplify.ConstraintList.__init__) | __init__ | | [`append`](#amplify.ConstraintList.append) | Append a constraint to the end of the list. | | [`clear`](#amplify.ConstraintList.clear) | Remove all constraints from the list. | | [`copy`](#amplify.ConstraintList.copy) | Return a shallow copy of the constraint list. | | [`count`](#amplify.ConstraintList.count) | Return the number of occurrences of a constraint in the list. | | [`extend`](#amplify.ConstraintList.extend) | Extend the list with constraints from a sequence. | | [`index`](#amplify.ConstraintList.index) | Return the index of the first occurrence of a constraint. | | [`insert`](#amplify.ConstraintList.insert) | Insert a constraint at a given position. | | [`pop`](#amplify.ConstraintList.pop) | Remove and return a constraint. | | [`remove`](#amplify.ConstraintList.remove) | Remove the first matching constraint from the list. | | [`reverse`](#amplify.ConstraintList.reverse) | Reverse the constraint list in place. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.ConstraintList.Iterator) **`__next__(self) → Constraint`** **戻り値の型:** [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) **`__add__(self, arg: ConstraintList, /) → ConstraintList`** **`__add__(self, arg: Constraint, /) → ConstraintList`** __add__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.ConstraintList) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (amplify.Constraint) > > **Returns:** > > amplify.ConstraintList: **`__copy__(self) → ConstraintList`** **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__deepcopy__(self, memo: object | None = None) → ConstraintList`** **パラメータ:** **memo** ([*object*](https://docs.python.org/3/library/functions.html#object) *| None*) -- Defaults to `None`. **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) → Constraint`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) **`__iadd__(self, arg: ConstraintList, /) → ConstraintList`** **`__iadd__(self, arg: Constraint, /) → ConstraintList`** __iadd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.ConstraintList) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (amplify.Constraint) > > **Returns:** > > amplify.ConstraintList: **`__imul__(self, arg: float, /) → ConstraintList`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__init__(self) → None`** **`__init__(self, arg: Sequence[Constraint]) → None`** **`__init__(self, arg: Iterable[Constraint]) → None`** __init__ > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (collections.abc.Sequence[amplify.Constraint]) > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (collections.abc.Iterable[amplify.Constraint]) **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.ConstraintList.Iterator) **`__itruediv__(self, arg: float, /) → ConstraintList`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__len__(self) → int`** Number of constraints in the list. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__mul__(self, arg: float, /) → ConstraintList`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint, /) → ConstraintList`** **`__radd__(self, arg: int, /) → ConstraintList`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Constraint) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (int) > > **Returns:** > > amplify.ConstraintList: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) → ConstraintList`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`__setitem__(self, key: int, value: Constraint) → None`** **パラメータ:** * **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) * **value** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__truediv__(self, arg: float, /) → ConstraintList`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`append(self, value: Constraint) → None`** Append a constraint to the end of the list. **パラメータ:** **value** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`clear(self) → None`** Remove all constraints from the list. **`copy(self) → ConstraintList`** Return a shallow copy of the constraint list. **戻り値の型:** [*ConstraintList*](#amplify.ConstraintList) **`count(self, value: Constraint) → int`** Return the number of occurrences of a constraint in the list. **パラメータ:** **value** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) -- Constraint to count. **戻り値:** Number of occurrences. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`extend(self, sequence: Sequence[Constraint]) → None`** Extend the list with constraints from a sequence. **パラメータ:** **sequence** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)*]*) **`index(self, value: Constraint) → int`** **`index(self, value: Constraint, start: int) → int`** **`index(self, value: Constraint, start: int, end: int) → int`** Return the index of the first occurrence of a constraint. > [!NOTE] > > **Overload 1.** > > **Args:** > > * value (amplify.Constraint): Constraint to find. > > **Returns:** > > int: Index of the first match. > [!NOTE] > > **Overload 2.** > > **Args:** > > * value (amplify.Constraint): Constraint to find. > * start (int): Start index. > > **Returns:** > > int: Index of the first match. > [!NOTE] > > **Overload 3.** > > **Args:** > > * value (amplify.Constraint): Constraint to find. > * start (int): Start index. > * end (int): End index. > > **Returns:** > > int: Index of the first match. **`insert(self, index: int, value: Constraint) → None`** Insert a constraint at a given position. **パラメータ:** * **index** ([*int*](https://docs.python.org/3/library/functions.html#int)) * **value** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`pop(self, index: int | None = None) → Constraint`** Remove and return a constraint. **パラメータ:** **index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- Index to pop. If omitted, pop the last item. Defaults to `None`. **戻り値:** Popped constraint. **戻り値の型:** [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) **`remove(self, value: Constraint) → None`** Remove the first matching constraint from the list. **パラメータ:** **value** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`reverse(self) → None`** Reverse the constraint list in place. --- # equal_to **`equal_to(poly: Poly, right: float, label: str = '') → Constraint`** **`equal_to(array: PolyArray[_Dim], right: float, label: str = '', *, axis: Literal[None] = None) → Constraint`** **`equal_to( array: PolyArray[Dim], right: float, label: str = '', *, axis: int | tuple[int, ...], ) → Constraint | ConstraintList`** **`equal_to(array: PolyArray[_Dim], right: float, label: str = '', *, axis: tuple[()]) → ConstraintList`** **`equal_to(array: PolyArray[Dim1], right: float, label: str = '', *, axis: int | tuple[int]) → Constraint`** **`equal_to(array: PolyArray[Dim2], right: float, label: str = '', *, axis: tuple[int, int]) → Constraint`** **`equal_to(array: PolyArray[Dim2], right: float, label: str = '', *, axis: int | tuple[int]) → ConstraintList`** **`equal_to(array: PolyArray[Dim3], right: float, label: str = '', *, axis: tuple[int, int, int]) → Constraint`** **`equal_to( array: PolyArray[Dim3], right: float, label: str = '', *, axis: int | tuple[int] | tuple[int, int], ) → ConstraintList`** **`equal_to(array: PolyArray[Dim4], right: float, label: str = '', *, axis: tuple[int, int, int, int]) → Constraint`** **`equal_to( array: PolyArray[Dim4], right: float, label: str = '', *, axis: int | tuple[int] | tuple[int, int] | tuple[int, int, int], ) → ConstraintList`** Create an equality constraint. For a single polynomial `poly`, constrain `poly == right`. For an array with `axis=None` (default), constrain the sum of all elements of `array` to be equal to right, returning a single [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). For an array with `axis` specified, reduce along the given axis or axes. Return a [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) with one constraint per remaining slice otherwise. > [!NOTE] > > **Overload 1.** > > **Args:** > > * poly (amplify.Poly): poly > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > > **Returns:** > > amplify.Constraint: Constraint object. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * axis (typing.Literal[None]): Axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Constraint: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * axis (int | tuple[int, ...]): Axis or axes to reduce. > > **Returns:** > > amplify.Constraint | amplify.ConstraintList: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * right (float) > * label (str): Defaults to `''`. > * axis (tuple[()]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * right (float) > * label (str): Defaults to `''`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * axis (tuple[int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * axis (int | tuple[int] | tuple[int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * axis (int | tuple[int] | tuple[int, int] | tuple[int, int, int]) > > **Returns:** > > amplify.ConstraintList: --- # one_hot **`one_hot(poly: Poly, label: str = '') → Constraint`** **`one_hot(array: PolyArray[_Dim], label: str = '', *, axis: Literal[None] = None) → Constraint`** **`one_hot(array: PolyArray[Dim], label: str = '', *, axis: int | tuple[int, ...]) → Constraint | ConstraintList`** **`one_hot(array: PolyArray[_Dim], label: str = '', *, axis: tuple[()]) → ConstraintList`** **`one_hot(array: PolyArray[Dim1], label: str = '', *, axis: int | tuple[int]) → Constraint`** **`one_hot(array: PolyArray[Dim2], label: str = '', *, axis: tuple[int, int]) → Constraint`** **`one_hot(array: PolyArray[Dim2], label: str = '', *, axis: int | tuple[int]) → ConstraintList`** **`one_hot(array: PolyArray[Dim3], label: str = '', *, axis: tuple[int, int, int]) → Constraint`** **`one_hot(array: PolyArray[Dim3], label: str = '', *, axis: int | tuple[int] | tuple[int, int]) → ConstraintList`** **`one_hot(array: PolyArray[Dim4], label: str = '', *, axis: tuple[int, int, int, int]) → Constraint`** **`one_hot( array: PolyArray[Dim4], label: str = '', *, axis: int | tuple[int] | tuple[int, int] | tuple[int, int, int], ) → ConstraintList`** Create a one-hot constraint. Equivalent to [`equal_to()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) with right-hand side `1`. For a single polynomial `poly`, constrain `poly == 1`. For an array with `axis=None` (default), constrain the sum of all elements of `array` to be equal to 1, returning a single [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). For an array with `axis` specified, reduce along the given axis or axes. Return a [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) with one constraint per remaining slice otherwise. > [!NOTE] > > **Overload 1.** > > **Args:** > > * poly (amplify.Poly): poly > * label (str): Constraint label. Defaults to `''`. > > **Returns:** > > amplify.Constraint: Constraint object. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * label (str): Constraint label. Defaults to `''`. > * axis (typing.Literal[None]): Axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Constraint: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * label (str): Constraint label. Defaults to `''`. > * axis (int | tuple[int, ...]): Axis or axes to reduce. > > **Returns:** > > amplify.Constraint | amplify.ConstraintList: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * label (str): Defaults to `''`. > * axis (tuple[()]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * label (str): Defaults to `''`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * label (str): Defaults to `''`. > * axis (tuple[int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * label (str): Defaults to `''`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * label (str): Defaults to `''`. > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * label (str): Defaults to `''`. > * axis (int | tuple[int] | tuple[int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * label (str): Defaults to `''`. > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * label (str): Defaults to `''`. > * axis (int | tuple[int] | tuple[int, int] | tuple[int, int, int]) > > **Returns:** > > amplify.ConstraintList: --- # less_equal **`less_equal( poly: Poly, right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, ) → Constraint`** **`less_equal( array: PolyArray[_Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: Literal[None] = None, ) → Constraint`** **`less_equal( array: PolyArray[Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int, ...], ) → Constraint | ConstraintList`** **`less_equal( array: PolyArray[_Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[()], ) → ConstraintList`** **`less_equal( array: PolyArray[Dim1], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → Constraint`** **`less_equal( array: PolyArray[Dim2], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int], ) → Constraint`** **`less_equal( array: PolyArray[Dim2], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → ConstraintList`** **`less_equal( array: PolyArray[Dim3], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int], ) → Constraint`** **`less_equal( array: PolyArray[Dim3], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int], ) → ConstraintList`** **`less_equal( array: PolyArray[Dim4], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int, int], ) → Constraint`** **`less_equal( array: PolyArray[Dim4], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int] | tuple[int, int, int], ) → ConstraintList`** Create a less-than-or-equal constraint. For a single polynomial `poly`, constrain `poly <= right`. For an array with `axis=None` (default), constrain the sum of all elements of `array` to be less than or equal to right, returning a single [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). For an array with `axis` specified, reduce along the given axis or axes. Return a [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) with one constraint per remaining slice otherwise. > [!NOTE] > > **Overload 1.** > > **Args:** > > * poly (amplify.Poly): poly > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > > **Returns:** > > amplify.Constraint: Constraint object. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (typing.Literal[None]): Axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Constraint: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int, ...]): Axis or axes to reduce. > > **Returns:** > > amplify.Constraint | amplify.ConstraintList: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[()]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int] | tuple[int, int, int]) > > **Returns:** > > amplify.ConstraintList: --- # greater_equal **`greater_equal( poly: Poly, right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, ) → Constraint`** **`greater_equal( array: PolyArray[_Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: Literal[None] = None, ) → Constraint`** **`greater_equal( array: PolyArray[Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int, ...], ) → Constraint | ConstraintList`** **`greater_equal( array: PolyArray[_Dim], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[()], ) → ConstraintList`** **`greater_equal( array: PolyArray[Dim1], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → Constraint`** **`greater_equal( array: PolyArray[Dim2], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int], ) → Constraint`** **`greater_equal( array: PolyArray[Dim2], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → ConstraintList`** **`greater_equal( array: PolyArray[Dim3], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int], ) → Constraint`** **`greater_equal( array: PolyArray[Dim3], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int], ) → ConstraintList`** **`greater_equal( array: PolyArray[Dim4], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int, int], ) → Constraint`** **`greater_equal( array: PolyArray[Dim4], right: float, label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int] | tuple[int, int, int], ) → ConstraintList`** Create a greater-than-or-equal constraint. For a single polynomial `poly`, constrain `poly >= right`. For an array with `axis=None` (default), constrain the sum of all elements of `array` to be greater than or equal to right, returning a single [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). For an array with `axis` specified, reduce along the given axis or axes. Return a [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) with one constraint per remaining slice otherwise. > [!NOTE] > > **Overload 1.** > > **Args:** > > * poly (amplify.Poly): poly > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > > **Returns:** > > amplify.Constraint: Constraint object. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (typing.Literal[None]): Axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Constraint: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * right (float): Right-hand side value. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int, ...]): Axis or axes to reduce. > > **Returns:** > > amplify.Constraint | amplify.ConstraintList: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[()]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (float) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int] | tuple[int, int, int]) > > **Returns:** > > amplify.ConstraintList: --- # clamp **`clamp( poly: Poly, bounds: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, ) → Constraint`** **`clamp( array: PolyArray[_Dim], bounds: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: Literal[None] = None, ) → Constraint`** **`clamp( array: PolyArray[Dim], bounds: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int, ...], ) → Constraint | ConstraintList`** **`clamp( array: PolyArray[Dim1], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → Constraint`** **`clamp( array: PolyArray[Dim2], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int], ) → Constraint`** **`clamp( array: PolyArray[Dim2], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int], ) → ConstraintList`** **`clamp( array: PolyArray[Dim3], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int], ) → Constraint`** **`clamp( array: PolyArray[Dim3], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int], ) → ConstraintList`** **`clamp( array: PolyArray[Dim4], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[int, int, int, int], ) → Constraint`** **`clamp( array: PolyArray[Dim4], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: int | tuple[int] | tuple[int, int] | tuple[int, int, int], ) → ConstraintList`** **`clamp( array: PolyArray[_Dim], right: tuple[float | None, float | None], label: str = '', *, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, axis: tuple[()], ) → ConstraintList`** Create a range constraint. Constrain the expression to lie within bounds. `(None, upper)` is equivalent to [`less_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), `(lower, None)` to [`greater_equal()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal). For a single polynomial `poly`, constrain `lower <= poly <= upper`. For an array with `axis=None` (default), constrain the sum of all elements of `array` to lie within bounds, returning a single [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). For an array with `axis` specified, reduce along the given axis or axes. Return a [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) with one constraint per remaining slice otherwise. > [!NOTE] > > **Overload 1.** > > **Args:** > > * poly (amplify.Poly): poly > * bounds (tuple[float | None, float | None]): Bounds as `(lower, upper)`. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > > **Returns:** > > amplify.Constraint: Constraint object. > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * bounds (tuple[float | None, float | None]): Bounds as `(lower, upper)`. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (typing.Literal[None]): Axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Constraint: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 3.** > > **Args:** > > * array (amplify.PolyArray[Dim]): array > * bounds (tuple[float | None, float | None]): Bounds as `(lower, upper)`. > * label (str): Constraint label. Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Penalty formulation method. Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int, ...]): Axis or axes to reduce. > > **Returns:** > > amplify.Constraint | amplify.ConstraintList: Single constraint when all axes are reduced; otherwise one constraint per remaining slice. > [!NOTE] > > **Overload 4.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 5.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 6.** > > **Args:** > > * array (amplify.PolyArray[Dim2]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 7.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 8.** > > **Args:** > > * array (amplify.PolyArray[Dim3]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 9.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[int, int, int, int]) > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 10.** > > **Args:** > > * array (amplify.PolyArray[Dim4]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (int | tuple[int] | tuple[int, int] | tuple[int, int, int]) > > **Returns:** > > amplify.ConstraintList: > [!NOTE] > > **Overload 11.** > > **Args:** > > * array (amplify.PolyArray[_Dim]) > * right (tuple[float | None, float | None]) > * label (str): Defaults to `''`. > * penalty_formulation (typing.Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation): Defaults to `PenaltyFormulation.Default`. > * axis (tuple[()]) > > **Returns:** > > amplify.ConstraintList: --- # domain_wall **`domain_wall(array: PolyArray[Dim1], label: str = '', *, ascending: bool = True) → Constraint`** **`domain_wall(array: PolyArray[_Dim], label: str = '', *, ascending: bool = True) → ConstraintList`** Create domain wall constraints for a variable array. For 1D arrays, return a single constraint. For higher-dimensional arrays, apply the same construction to each slice of the last axis and return a constraint list. > [!NOTE] > > **Overload 1.** > > **Args:** > > * array (amplify.PolyArray[Dim1]) > * label (str): Defaults to `''`. > * ascending (bool): Defaults to `True`. > > **Returns:** > > amplify.Constraint: > [!NOTE] > > **Overload 2.** > > **Args:** > > * array (amplify.PolyArray[_Dim]): array > * label (str): Base label for generated constraints. Defaults to `''`. > * ascending (bool): If `True` (default), the wall transitions from `0` to `1`; if `False`, from `1` to `0`. Defaults to `True`. > > **Returns:** > > amplify.ConstraintList: Single constraint for 1D input; otherwise one constraint per slice on the last axis. --- # PenaltyFormulation **`class PenaltyFormulation`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Penalty function formulation strategy used for constraint conversion. **Members** **`Default = 0`** **`IntegerVariable = 1`** **`LinearRelaxation = 4`** **`QuadraticRelaxation = 5`** **`RealVariable = 2`** **`Relaxation = 3`** --- # Model ## Model classes and functions ### Class | | | | --- | --- | | [`amplify.Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) | Combinatorial optimization model containing objective and constraints. | ### Enum | | | | --- | --- | | [`amplify.IntegerEncodingMethod`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod) | Encoding method for integer variables during model conversion. | | [`amplify.RealEncodingMethod`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md#amplify.RealEncodingMethod) | Encoding method for real variables during model conversion. | | [`amplify.QuadratizationMethod`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod) | Method used to reduce higher-order terms during conversion. | --- # Model **`class Model`** Combinatorial optimization model containing objective and constraints. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Model.__init__) | Construct a model. | | [`copy`](#amplify.Model.copy) | Return a copy of the model. | | [`get_variables`](#amplify.Model.get_variables) | Return the variables appearing in the model. | | [`to_intermediate_model`](#amplify.Model.to_intermediate_model) | Convert the model to an intermediate model according to degree and encoding settings. | | [`to_unconstrained_poly`](#amplify.Model.to_unconstrained_poly) | Convert model constraints into penalty form and return an unconstrained objective polynomial. | **Attributes** | | | | --- | --- | | [`constraints`](#amplify.Model.constraints) | Constraints held by the model. | | [`objective`](#amplify.Model.objective) | Objective function held by the model. | | [`variables`](#amplify.Model.variables) | List of variables in the model. | **`__add__(self, arg: Poly | Constraint | ConstraintList, /) → Model`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **戻り値の型:** [*Model*](#amplify.Model) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__iadd__(self, arg: Poly | Constraint | ConstraintList, /) → Model`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **戻り値の型:** [*Model*](#amplify.Model) **`__init__(self) → None`** **`__init__(self, objective: Poly | Matrix) → None`** **`__init__(self, constraint: Constraint | ConstraintList) → None`** **`__init__(self, objective: Poly | Matrix, constraint: Constraint | ConstraintList) → None`** Construct a model. If no arguments are given, create an empty model with zero objective and no constraints. If a polynomial is given, construct a model with the polynomial as the objective. If constraints are given, Construct a model with the constraints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix): Objective function. > [!NOTE] > > **Overload 3.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList): Constraints to include. > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix): Objective function. > * constraint (amplify.Constraint | amplify.ConstraintList): Constraints to include. **`__isub__(self, arg: Poly, /) → Model`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **戻り値の型:** [*Model*](#amplify.Model) **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Poly | Constraint | ConstraintList, /) → Model`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **戻り値の型:** [*Model*](#amplify.Model) **`__repr__(self) → str`** Return a developer-friendly string representation of the model. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** Return a human-readable string representation of the model. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly, /) → Model`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **戻り値の型:** [*Model*](#amplify.Model) **`copy(self) → Model`** Return a copy of the model. **戻り値:** Copy of the model. **戻り値の型:** [*Model*](#amplify.Model) **`get_variables(self, with_penalty: bool = False) → list[Variable]`** Return the variables appearing in the model. When `with_penalty` is `True`, this may trigger penalty construction for constraints and include auxiliary variables introduced by the penalty formulation. **パラメータ:** **with_penalty** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- Whether to include auxiliary variables introduced by penalty formulation. Defaults to `False`. **戻り値:** Variables that appear in the model. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] **`to_intermediate_model( self, acceptable_degrees: AcceptableDegrees, integer_encoding_method: Literal['Unary', 'Linear', 'Binary', 'Default'] | IntegerEncodingMethod = IntegerEncodingMethod.Default, real_encoding_method: Literal['Random4', 'Random8', 'Random16', 'Random32'] | RealEncodingMethod = RealEncodingMethod.Random16, quadratization_method: Literal['IshikawaKZFD', 'Substitute'] | QuadratizationMethod = QuadratizationMethod.Substitute, substitution_multiplier: float = 1.0, ) → tuple[Model, IntermediateMapping]`** Convert the model to an intermediate model according to degree and encoding settings. Performs variable conversion (integer/real to binary as needed), optional degree reduction, and variable remapping based on the required degrees. **パラメータ:** * **acceptable_degrees** ([*AcceptableDegrees*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees)) -- Acceptable degree settings. * **integer_encoding_method** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Unary', 'Linear', 'Binary', 'Default'] | amplify.IntegerEncodingMethod*) -- Integer variable conversion method. Defaults to `IntegerEncodingMethod.Default`. * **real_encoding_method** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Random4', 'Random8', 'Random16', 'Random32'] | amplify.RealEncodingMethod*) -- Real variable conversion method. Defaults to `RealEncodingMethod.Random16`. * **quadratization_method** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['IshikawaKZFD', 'Substitute'] | amplify.QuadratizationMethod*) -- Quadratization method. Defaults to `QuadratizationMethod.Substitute`. * **substitution_multiplier** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Multiplier for substitution penalty scaling (used only with `QuadratizationMethod.Substitute`). Defaults to `1.0`. **戻り値:** Converted model and mapping information. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](#amplify.Model), [*IntermediateMapping*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.IntermediateMapping)] **`to_unconstrained_poly(self) → Poly`** Convert model constraints into penalty form and return an unconstrained objective polynomial. **戻り値:** Unconstrained objective polynomial. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property constraints`** Constraints held by the model. **戻り値の型:** [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) **`property objective`** Objective function held by the model. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) **`property variables`** List of variables in the model. Equivalent to [`get_variables()`](#amplify.Model.get_variables) with `with_penalty=False`. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # IntegerEncodingMethod **`class IntegerEncodingMethod`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Encoding method for integer variables during model conversion. **Members** **`Binary = 2`** **`Default = 3`** **`Linear = 1`** **`Unary = 0`** --- # RealEncodingMethod **`class RealEncodingMethod`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Encoding method for real variables during model conversion. **Members** **`Random16 = 272`** **`Random32 = 288`** **`Random4 = 260`** **`Random8 = 264`** --- # QuadratizationMethod **`class QuadratizationMethod`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Method used to reduce higher-order terms during conversion. **Members** **`ISHIKAWA_KZFD = 0`** **`IshikawaKZFD = 0`** **`SUBSTITUTION = 1`** **`Substitute = 1`** --- # Graph Embedding ## Graph classes and functions ### Class | | | | --- | --- | | [`amplify.Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) | Physical graph information used by graph-embedding solvers. | ### Function | | | | --- | --- | | [`amplify.embed`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) | Perform graph embedding and return embedding information. | | [`amplify.to_edges`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.to_edges.md#amplify.to_edges) | Convert a polynomial to its graph edge list. | ### Enum | | | | --- | --- | | [`amplify.EmbeddingMethod`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod) | Graph embedding algorithm to apply. | --- # Graph **`class Graph`** Physical graph information used by graph-embedding solvers. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Graph.__init__) | | **Attributes** | | | | --- | --- | | [`adjacency`](#amplify.Graph.adjacency) | List of neighbor nodes for each node. | | [`edges`](#amplify.Graph.edges) | List of graph edges as node ID pairs. | | [`nodes`](#amplify.Graph.nodes) | List of node IDs in the graph. | | [`shape`](#amplify.Graph.shape) | Graph size parameters. | | [`type`](#amplify.Graph.type) | Graph type name, e.g. `"Chimera"`, `"Pegasus"` for [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) and `"Kings"` for [`HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient). | **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property adjacency`** List of neighbor nodes for each node. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*int*](https://docs.python.org/3/library/functions.html#int)]] **`property edges`** List of graph edges as node ID pairs. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), [*int*](https://docs.python.org/3/library/functions.html#int)]] **`property nodes`** List of node IDs in the graph. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*int*](https://docs.python.org/3/library/functions.html#int)] **`property shape`** Graph size parameters. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*int*](https://docs.python.org/3/library/functions.html#int)] **`property type`** Graph type name, e.g. `"Chimera"`, `"Pegasus"` for [`DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) and `"Kings"` for [`HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient). **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) --- # embed **`embed( poly: Poly, client_graph: Graph, embedding_method: Literal['Default', 'Minor', 'Clique', 'Parallel'] | EmbeddingMethod = EmbeddingMethod.Default, embedding_timeout: timedelta = datetime.timedelta(seconds=10), chain_strength: float = 1.0, ) → tuple[amplify.Poly, list[numpy.ndarray[dtype=uint32]], list[tuple[int, int]]]`** Perform graph embedding and return embedding information. Take a [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) and a [`Graph`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph), and return a tuple containing the embedded polynomial, the embedding mapping, and the graph converted from the input polynomial. **パラメータ:** * **poly** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) -- Polynomial to embed. * **client_graph** ([*Graph*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph)) -- Physical graph of the target client. * **embedding_method** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Default', 'Minor', 'Clique', 'Parallel'] | amplify.EmbeddingMethod*) -- Graph embedding algorithm. Defaults to `EmbeddingMethod.Default`. * **embedding_timeout** ([*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta)) -- Timeout for graph embedding search. Defaults to `datetime.timedelta(seconds=10)`. * **chain_strength** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Weight of the chain penalty added to the objective function. Defaults to `1.0`. **戻り値:** Embedded polynomial, embedding chains, and graph representation of the input polynomial. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)[dtype=uint32]], [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), [*int*](https://docs.python.org/3/library/functions.html#int)]]] --- # to_edges **`to_edges(poly: Poly) → list[tuple[int, int]]`** Convert a polynomial to its graph edge list. Second-order terms are converted to edges, and first-order terms are represented as self-loops. **パラメータ:** **poly** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) -- Polynomial to convert. **戻り値:** Edges represented by node ID pairs. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), [*int*](https://docs.python.org/3/library/functions.html#int)]] --- # EmbeddingMethod **`class EmbeddingMethod`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Graph embedding algorithm to apply. **Members** **`Clique = 2`** **`Default = 0`** **`Minor = 1`** **`Parallel = 3`** --- # Client ## Client classes and functions ### Clients | | | | --- | --- | | [`amplify.BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) | Base class of all clients in the Amplify SDK | | [`amplify.AmplifyAEClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) | | | [`amplify.FixstarsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) | | | [`amplify.DWaveSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) | | | [`amplify.LeapHybridSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) | | | [`amplify.LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient) | | | [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) | | | [`amplify.FujitsuDA3cClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient) | | | [`amplify.ToshibaSQBM2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client) | | | [`amplify.GurobiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) | | | [`amplify.NECVA2Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) | | | [`amplify.HitachiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) | | ### Class | | | | --- | --- | | [`amplify.AcceptableDegrees`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) | Container of acceptable polynomial degrees by variable type for objective and constraints. | ### Enum | | | | --- | --- | | [`amplify.Degree`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree) | Polynomial degree enumeration. | --- # BaseClient **`class BaseClient`** Base class of all clients in the Amplify SDK **Methods** | | | | --- | --- | | [`__init__`](#amplify.BaseClient.__init__) | | **`__init__(*args, **kwargs)`** --- # AmplifyAEClient **`class AmplifyAEClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.AmplifyAEClient.__init__) | | | [`solve`](#amplify.AmplifyAEClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.AmplifyAEClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`async_threshold_ms`](#amplify.AmplifyAEClient.async_threshold_ms) | Returns: datetime.timedelta | None: | | [`compression`](#amplify.AmplifyAEClient.compression) | Returns: bool: | | [`parameters`](#amplify.AmplifyAEClient.parameters) | Returns: amplify.AmplifyAEClient.Parameters: | | [`proxy`](#amplify.AmplifyAEClient.proxy) | Returns: str | None: | | [`solver`](#amplify.AmplifyAEClient.solver) | Returns: amplify.AmplifyAEClient.Solver: | | [`token`](#amplify.AmplifyAEClient.token) | Returns: str: | | [`url`](#amplify.AmplifyAEClient.url) | Returns: str: | | [`version`](#amplify.AmplifyAEClient.version) | Returns: str: | | [`write_request_data`](#amplify.AmplifyAEClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.AmplifyAEClient.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property duplicate_solutions`** Returns: bool | None: **`property num_gpus`** Returns: int | None: **`property penalty_weight_calibration`** Returns: bool | None: **`property time_limit_ms`** Returns: datetime.timedelta | None: **`class Result`** **`class Solution`** **`class Status`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Feasible = 1`** **`Infeasible = 0`** **`Optimal = 2`** **`__nb_enum__ = `** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property objective`** Returns: float: **`property status`** Returns: amplify.AmplifyAEClient.Result.Solution.Status: **`property time_stamp_ms`** Returns: datetime.timedelta: **`property values`** Returns: numpy.ndarray: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property execution_time_ms`** Returns: datetime.timedelta: **`property num_flips`** Returns: int: **`property num_gpus`** Returns: int: **`property num_samplings`** Returns: int: **`property queue_time_ms`** Returns: datetime.timedelta: **`property solutions`** Returns: list[amplify.AmplifyAEClient.Result.Solution]: **`property started_at`** Returns: datetime.datetime: **`property submitted_at`** Returns: datetime.datetime: **`property version`** Returns: str: **`property warnings`** Returns: list[str]: **`class Solver`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Constraint = 0`** **`Pubo = 1`** **`Qubo = 2`** **`__nb_enum__ = `** **`__init__(self) → None`** **`__init__(self, token: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, ) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.AmplifyAEClient.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.AmplifyAEClient.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.AmplifyAEClient.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property async_threshold_ms`** Returns: datetime.timedelta | None: **`property compression`** Returns: bool: **`property parameters`** Returns: amplify.AmplifyAEClient.Parameters: **`property proxy`** Returns: str | None: **`property solver`** Returns: amplify.AmplifyAEClient.Solver: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # FixstarsClient **`class FixstarsClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.FixstarsClient.__init__) | | | [`solve`](#amplify.FixstarsClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.FixstarsClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`async_threshold`](#amplify.FixstarsClient.async_threshold) | Returns: datetime.timedelta | None: | | [`compression`](#amplify.FixstarsClient.compression) | Returns: bool: | | [`parameters`](#amplify.FixstarsClient.parameters) | Returns: amplify.FixstarsClient.Parameters: | | [`proxy`](#amplify.FixstarsClient.proxy) | Returns: str | None: | | [`token`](#amplify.FixstarsClient.token) | Returns: str: | | [`url`](#amplify.FixstarsClient.url) | Returns: str: | | [`version`](#amplify.FixstarsClient.version) | Returns: str: | | [`write_request_data`](#amplify.FixstarsClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.FixstarsClient.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`class Outputs`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property duplicate`** Returns: bool | None: **`property energies`** Returns: bool | None: **`property feasibilities`** Returns: bool | None: **`property num_outputs`** Returns: int | None: **`property sort`** Returns: bool | None: **`property spins`** Returns: bool | None: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property num_gpus`** Returns: int | None: **`property outputs`** Returns: amplify.FixstarsClient.Parameters.Outputs: **`property penalty_calibration`** Returns: bool | None: **`property timeout`** Returns: datetime.timedelta | None: **`class Result`** **`class ExecutionParameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property num_gpus`** Returns: int: **`property num_iterations`** Returns: int: **`property penalty_calibration`** Returns: bool: **`property penalty_multipliers`** Returns: numpy.ndarray: **`property timeout`** Returns: datetime.timedelta: **`property version`** Returns: str: **`class ExecutionTime`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property annealing_time`** Returns: datetime.timedelta: **`property cpu_time`** Returns: datetime.timedelta: **`property queue_time`** Returns: datetime.timedelta: **`property time_stamps`** Returns: list[datetime.timedelta]: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property energies`** Returns: numpy.ndarray: **`property execution_parameters`** Returns: amplify.FixstarsClient.Result.ExecutionParameters: **`property execution_time`** Returns: amplify.FixstarsClient.Result.ExecutionTime: **`property feasibilities`** Returns: numpy.ndarray: **`property message`** Returns: str: **`property spins`** Returns: list[numpy.ndarray[dtype=int8, writable=False]]: **`__init__(self) → None`** **`__init__(self, token: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, ) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.FixstarsClient.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.FixstarsClient.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.FixstarsClient.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property async_threshold`** Returns: datetime.timedelta | None: **`property compression`** Returns: bool: **`property parameters`** Returns: amplify.FixstarsClient.Parameters: **`property proxy`** Returns: str | None: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # DWaveSamplerClient **`class DWaveSamplerClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.DWaveSamplerClient.__init__) | | | [`solve`](#amplify.DWaveSamplerClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.DWaveSamplerClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`compress_qpu_problem_data`](#amplify.DWaveSamplerClient.compress_qpu_problem_data) | Returns: bool | None: | | [`graph`](#amplify.DWaveSamplerClient.graph) | Returns: amplify.Graph: | | [`parameters`](#amplify.DWaveSamplerClient.parameters) | Returns: amplify.DWaveSamplerClient.Parameters: | | [`properties`](#amplify.DWaveSamplerClient.properties) | Returns: dict[str, typing.Any]: | | [`proxy`](#amplify.DWaveSamplerClient.proxy) | Returns: str | None: | | [`solver`](#amplify.DWaveSamplerClient.solver) | Returns: str: | | [`solver_names`](#amplify.DWaveSamplerClient.solver_names) | Returns: list[str]: | | [`token`](#amplify.DWaveSamplerClient.token) | Returns: str: | | [`url`](#amplify.DWaveSamplerClient.url) | Returns: str: | | [`version`](#amplify.DWaveSamplerClient.version) | Returns: str: | | [`write_request_data`](#amplify.DWaveSamplerClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.DWaveSamplerClient.write_response_data) | Returns: pathlib.Path | None: | **`class AnswerMode`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__nb_enum__ = `** **`histogram = 0`** **`raw = 1`** **`class Parameters`** **`__init__(self) → None`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property anneal_offsets`** Returns: list[float] | None: **`property anneal_schedule`** Returns: list[tuple[float, float]] | None: **`property annealing_time`** The value in microseconds. Fractional values are preserved. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property answer_mode`** Returns: amplify.DWaveSamplerClient.AnswerMode | None: **`property auto_scale`** Returns: bool | None: **`property fast_anneal`** Returns: bool | None: **`property flux_biases`** Returns: list[float] | None: **`property flux_drift_compensation`** Returns: bool | None: **`property h_gain_schedule`** Returns: list[tuple[float, float]] | None: **`property initial_state`** Returns: dict[int, int] | None: **`property label`** Returns: str | None: **`property num_reads`** Returns: int | None: **`property programming_thermalization`** The value in microseconds. Fractional values are preserved. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property readout_thermalization`** The value in microseconds. Fractional values are preserved. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property reduce_intersample_correlation`** Returns: bool | None: **`property reinitialize_state`** Returns: bool | None: **`__init__(self) → None`** **`__init__(self, token: str = '', solver: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **solver** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve(self, objective: Poly, dry_run: Literal[False] = False) → SampleSet`** **`solve(self, objective: Poly, dry_run: Literal[True]) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > dimod.sampleset.SampleSet: > [!NOTE] > > **Overload 2.** > > **Args:** > > * objective (amplify.Poly) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property compress_qpu_problem_data`** Returns: bool | None: **`property graph`** Returns: amplify.Graph: **`property parameters`** Returns: amplify.DWaveSamplerClient.Parameters: **`property properties`** Returns: dict[str, typing.Any]: **`property proxy`** Returns: str | None: **`property solver`** Returns: str: **`property solver_names`** Returns: list[str]: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # LeapHybridSamplerClient **`class LeapHybridSamplerClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.LeapHybridSamplerClient.__init__) | | | [`solve`](#amplify.LeapHybridSamplerClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.LeapHybridSamplerClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`compress_qpu_problem_data`](#amplify.LeapHybridSamplerClient.compress_qpu_problem_data) | Returns: bool | None: | | [`parameters`](#amplify.LeapHybridSamplerClient.parameters) | Returns: amplify.LeapHybridSamplerClient.Parameters: | | [`properties`](#amplify.LeapHybridSamplerClient.properties) | Returns: dict[str, typing.Any]: | | [`proxy`](#amplify.LeapHybridSamplerClient.proxy) | Returns: str | None: | | [`solver`](#amplify.LeapHybridSamplerClient.solver) | Returns: str: | | [`solver_names`](#amplify.LeapHybridSamplerClient.solver_names) | Returns: list[str]: | | [`token`](#amplify.LeapHybridSamplerClient.token) | Returns: str: | | [`url`](#amplify.LeapHybridSamplerClient.url) | Returns: str: | | [`version`](#amplify.LeapHybridSamplerClient.version) | Returns: str: | | [`write_request_data`](#amplify.LeapHybridSamplerClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.LeapHybridSamplerClient.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`__init__(self) → None`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property label`** Returns: str | None: **`property time_limit`** Returns: datetime.timedelta | None: **`__init__(self) → None`** **`__init__(self, token: str = '', solver: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **solver** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, ) → SampleSet`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > dimod.sampleset.SampleSet: > [!NOTE] > > **Overload 2.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property compress_qpu_problem_data`** Returns: bool | None: **`property parameters`** Returns: amplify.LeapHybridSamplerClient.Parameters: **`property properties`** Returns: dict[str, typing.Any]: **`property proxy`** Returns: str | None: **`property solver`** Returns: str: **`property solver_names`** Returns: list[str]: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # LeapHybridCQMSamplerClient **`class LeapHybridCQMSamplerClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.LeapHybridCQMSamplerClient.__init__) | | | [`solve`](#amplify.LeapHybridCQMSamplerClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.LeapHybridCQMSamplerClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`compress_qpu_problem_data`](#amplify.LeapHybridCQMSamplerClient.compress_qpu_problem_data) | Returns: bool | None: | | [`parameters`](#amplify.LeapHybridCQMSamplerClient.parameters) | Returns: amplify.LeapHybridCQMSamplerClient.Parameters: | | [`properties`](#amplify.LeapHybridCQMSamplerClient.properties) | Returns: dict[str, typing.Any]: | | [`proxy`](#amplify.LeapHybridCQMSamplerClient.proxy) | Returns: str | None: | | [`solver`](#amplify.LeapHybridCQMSamplerClient.solver) | Returns: str: | | [`solver_names`](#amplify.LeapHybridCQMSamplerClient.solver_names) | Returns: list[str]: | | [`token`](#amplify.LeapHybridCQMSamplerClient.token) | Returns: str: | | [`url`](#amplify.LeapHybridCQMSamplerClient.url) | Returns: str: | | [`version`](#amplify.LeapHybridCQMSamplerClient.version) | Returns: str: | | [`write_request_data`](#amplify.LeapHybridCQMSamplerClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.LeapHybridCQMSamplerClient.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`__init__(self) → None`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property label`** Returns: str | None: **`property time_limit`** Returns: datetime.timedelta | None: **`__init__(self) → None`** **`__init__(self, token: str = '', solver: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **solver** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, ) → SampleSet`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → SampleSet`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → SampleSet`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > dimod.sampleset.SampleSet: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > dimod.sampleset.SampleSet: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > dimod.sampleset.SampleSet: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property compress_qpu_problem_data`** Returns: bool | None: **`property parameters`** Returns: amplify.LeapHybridCQMSamplerClient.Parameters: **`property properties`** Returns: dict[str, typing.Any]: **`property proxy`** Returns: str | None: **`property solver`** Returns: str: **`property solver_names`** Returns: list[str]: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # FujitsuDA4Client **`class FujitsuDA4Client`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.FujitsuDA4Client.__init__) | | | [`async_solve`](#amplify.FujitsuDA4Client.async_solve) | async_solve | | [`cancel_job`](#amplify.FujitsuDA4Client.cancel_job) | | | [`delete_job_result`](#amplify.FujitsuDA4Client.delete_job_result) | | | [`get_job_result`](#amplify.FujitsuDA4Client.get_job_result) | | | [`get_jobs`](#amplify.FujitsuDA4Client.get_jobs) | | | [`health_check`](#amplify.FujitsuDA4Client.health_check) | | | [`solve`](#amplify.FujitsuDA4Client.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.FujitsuDA4Client.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`parameters`](#amplify.FujitsuDA4Client.parameters) | Returns: amplify.FujitsuDA4Client.Parameters: | | [`proxy`](#amplify.FujitsuDA4Client.proxy) | Returns: str | None: | | [`set_inequalities`](#amplify.FujitsuDA4Client.set_inequalities) | Returns: bool: | | [`set_one_way_one_hot_groups`](#amplify.FujitsuDA4Client.set_one_way_one_hot_groups) | Returns: bool: | | [`set_penalty_binary_polynomial`](#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) | Returns: bool: | | [`set_two_way_one_hot_groups`](#amplify.FujitsuDA4Client.set_two_way_one_hot_groups) | Returns: bool: | | [`token`](#amplify.FujitsuDA4Client.token) | Returns: str: | | [`type_id`](#amplify.FujitsuDA4Client.type_id) | Returns: str | None: | | [`url`](#amplify.FujitsuDA4Client.url) | Returns: str: | | [`version`](#amplify.FujitsuDA4Client.version) | Returns: str: | | [`write_request_data`](#amplify.FujitsuDA4Client.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.FujitsuDA4Client.write_response_data) | Returns: pathlib.Path | None: | **`class CommonError`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property code`** Returns: int: **`property message`** Returns: str: **`property title`** Returns: str: **`class JobStatus`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Canceled = 3`** **`Deleted = 5`** **`Done = 0`** **`Error = 4`** **`Running = 1`** **`Waiting = 2`** **`__nb_enum__ = `** **`class JobStatusInfo`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property job_id`** Returns: str: **`property job_status`** Returns: amplify.FujitsuDA4Client.JobStatus: **`property start_time`** Returns: datetime.datetime: **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property gs_cutoff`** Returns: int | None: **`property gs_level`** Returns: int | None: **`property internal_penalty`** Returns: int | None: **`property max_penalty_coef`** Returns: int | None: **`property num_group`** Returns: int | None: **`property num_output_solution`** Returns: int | None: **`property num_run`** Returns: int | None: **`property one_hot_cutoff`** Returns: int | None: **`property one_hot_level`** Returns: int | None: **`property penalty_auto_mode`** Returns: int | None: **`property penalty_coef`** Returns: int | None: **`property penalty_inc_rate`** Returns: int | None: **`property target_energy`** Returns: float | None: **`property time_limit_sec`** Returns: datetime.timedelta | None: **`class Progress`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property energy`** Returns: float: **`property penalty_energy`** Returns: float: **`property time`** Returns: datetime.timedelta: **`QuboResponse`** [`Result`](#amplify.FujitsuDA4Client.Result) の別名です。 **`class QuboSolution`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property configuration`** Returns: dict[str, bool]: **`property energy`** Returns: float: **`property frequency`** Returns: int: **`property penalty_energy`** Returns: float: **`class QuboSolutionList`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property progress`** Returns: list[amplify.FujitsuDA4Client.Progress]: **`property result_status`** Returns: bool: **`property solutions`** Returns: list[amplify.FujitsuDA4Client.QuboSolution]: **`property timing`** Returns: amplify.FujitsuDA4Client.SolverTiming: **`class Result`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property message`** Returns: str: **`property qubo_solution`** Returns: amplify.FujitsuDA4Client.QuboSolutionList: **`property status`** Returns: amplify.FujitsuDA4Client.JobStatus: **`class SolverTiming`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property solve_time`** Returns: datetime.timedelta: **`property total_elapsed_time`** Returns: datetime.timedelta: **`__init__(self) → None`** **`__init__(self, token: str = '', type_id: str | None = None, url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **type_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`async_solve(self, objective: Poly) → str`** **`async_solve(self, constraint: Constraint | ConstraintList) → str`** **`async_solve(self, objective: Poly, constraint: Constraint | ConstraintList) → str`** async_solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly) > > **Returns:** > > str: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > str: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly) > * constraint (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > str: **`cancel_job(self, job_id: str) → JobStatus`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*JobStatus*](#amplify.FujitsuDA4Client.JobStatus) **`delete_job_result(self, job_id: str) → Result`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*Result*](#amplify.FujitsuDA4Client.Result) **`get_job_result(self, job_id: str) → Result`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*Result*](#amplify.FujitsuDA4Client.Result) **`get_jobs(self) → list[JobStatusInfo]`** **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*JobStatusInfo*](#amplify.FujitsuDA4Client.JobStatusInfo)] **`health_check(self) → CommonError | None`** **戻り値の型:** [*CommonError*](#amplify.FujitsuDA4Client.CommonError) | *None* **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, objective: Poly | Matrix, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property parameters`** Returns: amplify.FujitsuDA4Client.Parameters: **`property proxy`** Returns: str | None: **`property set_inequalities`** Returns: bool: **`property set_one_way_one_hot_groups`** Returns: bool: **`property set_penalty_binary_polynomial`** Returns: bool: **`property set_two_way_one_hot_groups`** Returns: bool: **`property token`** Returns: str: **`property type_id`** Returns: str | None: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # FujitsuDA3cClient **`class FujitsuDA3cClient`** ベースクラス: [`FujitsuDA4Client`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) **Methods** | | | | --- | --- | | [`__init__`](#amplify.FujitsuDA3cClient.__init__) | | | [`async_solve`](#amplify.FujitsuDA3cClient.async_solve) | async_solve | | [`cancel_job`](#amplify.FujitsuDA3cClient.cancel_job) | | | [`delete_job_result`](#amplify.FujitsuDA3cClient.delete_job_result) | | | [`get_job_result`](#amplify.FujitsuDA3cClient.get_job_result) | | | [`get_jobs`](#amplify.FujitsuDA3cClient.get_jobs) | | | [`health_check`](#amplify.FujitsuDA3cClient.health_check) | | | [`solve`](#amplify.FujitsuDA3cClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.FujitsuDA3cClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`parameters`](#amplify.FujitsuDA3cClient.parameters) | Returns: amplify.FujitsuDA4Client.Parameters: | | [`proxy`](#amplify.FujitsuDA3cClient.proxy) | Returns: str | None: | | [`set_inequalities`](#amplify.FujitsuDA3cClient.set_inequalities) | Returns: bool: | | [`set_one_way_one_hot_groups`](#amplify.FujitsuDA3cClient.set_one_way_one_hot_groups) | Returns: bool: | | [`set_penalty_binary_polynomial`](#amplify.FujitsuDA3cClient.set_penalty_binary_polynomial) | Returns: bool: | | [`set_two_way_one_hot_groups`](#amplify.FujitsuDA3cClient.set_two_way_one_hot_groups) | Returns: bool: | | [`token`](#amplify.FujitsuDA3cClient.token) | Returns: str: | | [`type_id`](#amplify.FujitsuDA3cClient.type_id) | Returns: str | None: | | [`url`](#amplify.FujitsuDA3cClient.url) | Returns: str: | | [`version`](#amplify.FujitsuDA3cClient.version) | Returns: str: | | [`write_request_data`](#amplify.FujitsuDA3cClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.FujitsuDA3cClient.write_response_data) | Returns: pathlib.Path | None: | **`class CommonError`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property code`** Returns: int: **`property message`** Returns: str: **`property title`** Returns: str: **`class JobStatus`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Canceled = 3`** **`Deleted = 5`** **`Done = 0`** **`Error = 4`** **`Running = 1`** **`Waiting = 2`** **`__nb_enum__ = `** **`class JobStatusInfo`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property job_id`** Returns: str: **`property job_status`** Returns: amplify.FujitsuDA4Client.JobStatus: **`property start_time`** Returns: datetime.datetime: **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property gs_cutoff`** Returns: int | None: **`property gs_level`** Returns: int | None: **`property internal_penalty`** Returns: int | None: **`property max_penalty_coef`** Returns: int | None: **`property num_group`** Returns: int | None: **`property num_output_solution`** Returns: int | None: **`property num_run`** Returns: int | None: **`property one_hot_cutoff`** Returns: int | None: **`property one_hot_level`** Returns: int | None: **`property penalty_auto_mode`** Returns: int | None: **`property penalty_coef`** Returns: int | None: **`property penalty_inc_rate`** Returns: int | None: **`property target_energy`** Returns: float | None: **`property time_limit_sec`** Returns: datetime.timedelta | None: **`class Progress`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property energy`** Returns: float: **`property penalty_energy`** Returns: float: **`property time`** Returns: datetime.timedelta: **`QuboResponse`** [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) の別名です。 **`class QuboSolution`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property configuration`** Returns: dict[str, bool]: **`property energy`** Returns: float: **`property frequency`** Returns: int: **`property penalty_energy`** Returns: float: **`class QuboSolutionList`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property progress`** Returns: list[amplify.FujitsuDA4Client.Progress]: **`property result_status`** Returns: bool: **`property solutions`** Returns: list[amplify.FujitsuDA4Client.QuboSolution]: **`property timing`** Returns: amplify.FujitsuDA4Client.SolverTiming: **`class Result`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property message`** Returns: str: **`property qubo_solution`** Returns: amplify.FujitsuDA4Client.QuboSolutionList: **`property status`** Returns: amplify.FujitsuDA4Client.JobStatus: **`class SolverTiming`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property solve_time`** Returns: datetime.timedelta: **`property total_elapsed_time`** Returns: datetime.timedelta: **`__init__(self) → None`** **`__init__(self, token: str = '', type_id: str | None = None, url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **type_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`async_solve(self, objective: Poly) → str`** **`async_solve(self, constraint: Constraint | ConstraintList) → str`** **`async_solve(self, objective: Poly, constraint: Constraint | ConstraintList) → str`** async_solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly) > > **Returns:** > > str: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > str: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly) > * constraint (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > str: **`cancel_job(self, job_id: str) → JobStatus`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*JobStatus*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatus) **`delete_job_result(self, job_id: str) → Result`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) **`get_job_result(self, job_id: str) → Result`** **パラメータ:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **戻り値の型:** [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) **`get_jobs(self) → list[JobStatusInfo]`** **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*JobStatusInfo*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatusInfo)] **`health_check(self) → CommonError | None`** **戻り値の型:** [*CommonError*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.CommonError) | *None* **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, retry_after_delete: bool = True, delete_after_solve: bool = True, ) → Result`** **`solve( self, objective: Poly | Matrix, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], retry_after_delete: bool = True, delete_after_solve: bool = True, ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > > **Returns:** > > amplify.FujitsuDA4Client.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > * retry_after_delete (bool): Defaults to `True`. > * delete_after_solve (bool): Defaults to `True`. **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property parameters`** Returns: amplify.FujitsuDA4Client.Parameters: **`property proxy`** Returns: str | None: **`property set_inequalities`** Returns: bool: **`property set_one_way_one_hot_groups`** Returns: bool: **`property set_penalty_binary_polynomial`** Returns: bool: **`property set_two_way_one_hot_groups`** Returns: bool: **`property token`** Returns: str: **`property type_id`** Returns: str | None: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # ToshibaSQBM2Client **`class ToshibaSQBM2Client`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.ToshibaSQBM2Client.__init__) | | | [`health_check`](#amplify.ToshibaSQBM2Client.health_check) | | | [`solve`](#amplify.ToshibaSQBM2Client.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.ToshibaSQBM2Client.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`compression`](#amplify.ToshibaSQBM2Client.compression) | Returns: bool: | | [`parameters`](#amplify.ToshibaSQBM2Client.parameters) | Returns: amplify.ToshibaSQBM2Client.Parameters: | | [`proxy`](#amplify.ToshibaSQBM2Client.proxy) | Returns: str | None: | | [`solver`](#amplify.ToshibaSQBM2Client.solver) | Returns: amplify.ToshibaSQBM2Client.Solver: | | [`token`](#amplify.ToshibaSQBM2Client.token) | Returns: str: | | [`url`](#amplify.ToshibaSQBM2Client.url) | Returns: str: | | [`version`](#amplify.ToshibaSQBM2Client.version) | Returns: str: | | [`write_request_data`](#amplify.ToshibaSQBM2Client.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.ToshibaSQBM2Client.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property C`** Returns: float | None: **`property HMCsteps`** Returns: int | None: **`property HMCweight`** Returns: int | None: **`property PD3Orate`** Returns: int | None: **`property algo`** Returns: int | None: **`property algos`** Returns: str | None: **`property blocks`** Returns: int | None: **`property detail_level`** Returns: int | None: **`property detail_log`** Returns: int | None: **`property dt`** Returns: float | None: **`property loops`** Returns: int | None: **`property maxout`** Returns: int | None: **`property maxwait`** Returns: datetime.timedelta | None: **`property multishot`** Returns: int | None: **`property phi`** Returns: float | None: **`property steps`** Returns: int | None: **`property target`** Returns: float | None: **`property timeout`** Returns: datetime.timedelta | None: **`class Result`** ベースクラス: [`Solution`](#amplify.ToshibaSQBM2Client.Solution) **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property count`** Returns: int: **`property id`** Returns: str: **`property message`** Returns: str: **`property others`** Returns: list[amplify.ToshibaSQBM2Client.Solution]: **`property param`** Returns: amplify.ToshibaSQBM2Client.Parameters: **`property result`** Returns: numpy.ndarray: **`property runs`** Returns: int: **`property time`** Returns: datetime.timedelta: **`property value`** Returns: float: **`property wait`** Returns: datetime.timedelta: **`class Solution`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property count`** Returns: int: **`property param`** Returns: amplify.ToshibaSQBM2Client.Parameters: **`property result`** Returns: numpy.ndarray: **`property value`** Returns: float: **`class Solver`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Pubo = 2`** **`Qplib = 1`** **`Qubo = 0`** **`__nb_enum__ = `** **`__init__(self) → None`** **`__init__(self, token: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`health_check(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`solve( self, objective: Poly | Matrix, dry_run: Literal[False] = False, ) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.ToshibaSQBM2Client.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.ToshibaSQBM2Client.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.ToshibaSQBM2Client.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property compression`** Returns: bool: **`property parameters`** Returns: amplify.ToshibaSQBM2Client.Parameters: **`property proxy`** Returns: str | None: **`property solver`** Returns: amplify.ToshibaSQBM2Client.Solver: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # GurobiClient **`class GurobiClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.GurobiClient.__init__) | | | [`solve`](#amplify.GurobiClient.solve) | solve | | [`tune`](#amplify.GurobiClient.tune) | tune | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.GurobiClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`library_path`](#amplify.GurobiClient.library_path) | Returns: str | None: | | [`parameters`](#amplify.GurobiClient.parameters) | Returns: amplify.GurobiClient.Parameters: | | [`version`](#amplify.GurobiClient.version) | Returns: str: | | [`write_request_data`](#amplify.GurobiClient.write_request_data) | Returns: str | None: | | [`write_response_data`](#amplify.GurobiClient.write_response_data) | Returns: str | None: | **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property agg_fill`** Returns: int | None: **`property aggregate`** Returns: int | None: **`property bar_conv_tol`** Returns: float | None: **`property bar_correctors`** Returns: int | None: **`property bar_homogeneous`** Returns: int | None: **`property bar_iter_limit`** Returns: int | None: **`property bar_order`** Returns: int | None: **`property bar_qcp_conv_tol`** Returns: float | None: **`property best_bd_stop`** Returns: float | None: **`property best_obj_stop`** Returns: float | None: **`property bqp_cuts`** Returns: int | None: **`property branch_dir`** Returns: int | None: **`property clique_cuts`** Returns: int | None: **`property cloud_access_id`** Returns: str | None: **`property cloud_host`** Returns: str | None: **`property cloud_pool`** Returns: str | None: **`property cloud_secret_key`** Returns: str | None: **`property compute_server`** Returns: str | None: **`property concurrent_jobs`** Returns: int | None: **`property concurrent_method`** Returns: int | None: **`property concurrent_mip`** Returns: int | None: **`property cover_cuts`** Returns: int | None: **`property crossover`** Returns: int | None: **`property crossover_basis`** Returns: int | None: **`property cs_app_name`** Returns: str | None: **`property cs_auth_token`** Returns: str | None: **`property cs_batch_mode`** Returns: int | None: **`property cs_client_log`** Returns: int | None: **`property cs_group`** Returns: str | None: **`property cs_idle_timeout`** Returns: int | None: **`property cs_manager`** Returns: str | None: **`property cs_priority`** Returns: int | None: **`property cs_queue_timeout`** Returns: float | None: **`property cs_router`** Returns: str | None: **`property csapi_access_id`** Returns: str | None: **`property csapi_secret`** Returns: str | None: **`property cstls_insecure`** Returns: int | None: **`property cut_agg_passes`** Returns: int | None: **`property cut_passes`** Returns: int | None: **`property cutoff`** Returns: float | None: **`property cuts`** Returns: int | None: **`property degen_moves`** Returns: int | None: **`property disconnected`** Returns: int | None: **`property display_interval`** Returns: int | None: **`property distributed_mip_jobs`** Returns: int | None: **`property dual_implied_cuts`** Returns: int | None: **`property dual_reductions`** Returns: int | None: **`property feas_relax_big_m`** Returns: float | None: **`property feasibility_tol`** Returns: float | None: **`property flow_cover_cuts`** Returns: int | None: **`property flow_path_cuts`** Returns: int | None: **`property func_max_val`** Returns: float | None: **`property func_nonlinear`** Returns: int | None: **`property func_piece_error`** Returns: float | None: **`property func_piece_length`** Returns: float | None: **`property func_piece_ratio`** Returns: float | None: **`property func_pieces`** Returns: int | None: **`property gomory_passes`** Returns: int | None: **`property gub_cover_cuts`** Returns: int | None: **`property heuristics`** Returns: float | None: **`property ignore_names`** Returns: int | None: **`property iis_method`** Returns: int | None: **`property implied_cuts`** Returns: int | None: **`property improve_start_gap`** Returns: float | None: **`property improve_start_nodes`** Returns: float | None: **`property improve_start_time`** Returns: float | None: **`property inf_proof_cuts`** Returns: int | None: **`property inf_unbd_info`** Returns: int | None: **`property int_feas_tol`** Returns: float | None: **`property integrality_focus`** Returns: int | None: **`property iteration_limit`** Returns: float | None: **`property job_id`** Returns: str | None: **`property json_sol_detail`** Returns: int | None: **`property lazy_constraints`** Returns: int | None: **`property license_id`** Returns: int | None: **`property lift_project_cuts`** Returns: int | None: **`property log_file`** Returns: pathlib.Path | None: **`property log_to_console`** Returns: bool | None: **`property lp_warm_start`** Returns: int | None: **`property markowitz_tol`** Returns: float | None: **`property mem_limit`** Returns: float | None: **`property method`** Returns: int | None: **`property min_rel_nodes`** Returns: int | None: **`property mip_focus`** Returns: int | None: **`property mip_gap`** Returns: float | None: **`property mip_gap_abs`** Returns: float | None: **`property mip_sep_cuts`** Returns: int | None: **`property miqcp_method`** Returns: int | None: **`property mir_cuts`** Returns: int | None: **`property mixing_cuts`** Returns: int | None: **`property mod_k_cuts`** Returns: int | None: **`property multi_obj_method`** Returns: int | None: **`property multi_obj_pre`** Returns: int | None: **`property network_alg`** Returns: int | None: **`property network_cuts`** Returns: int | None: **`property nlp_heur`** Returns: int | None: **`property no_rel_heur_time`** Returns: float | None: **`property no_rel_heur_work`** Returns: float | None: **`property no_rel_heuristic`** Returns: int | None: **`property node_limit`** Returns: float | None: **`property node_method`** Returns: int | None: **`property nodefile_dir`** Returns: pathlib.Path | None: **`property nodefile_start`** Returns: float | None: **`property non_convex`** Returns: int | None: **`property norm_adjust`** Returns: int | None: **`property numeric_focus`** Returns: int | None: **`property obbt`** Returns: int | None: **`property obj_number`** Returns: int | None: **`property obj_scale`** Returns: float | None: **`property optimality_tol`** Returns: float | None: **`property output_flag`** Returns: int | None: **`property partition_place`** Returns: int | None: **`property perturb_value`** Returns: float | None: **`property pool_gap`** Returns: float | None: **`property pool_gap_abs`** Returns: float | None: **`property pool_search_mode`** Returns: int | None: **`property pool_solutions`** Returns: int | None: **`property pre_crush`** Returns: int | None: **`property pre_dep_row`** Returns: int | None: **`property pre_dual`** Returns: int | None: **`property pre_miqcp_form`** Returns: int | None: **`property pre_passes`** Returns: int | None: **`property pre_q_linearize`** Returns: int | None: **`property pre_sparsify`** Returns: int | None: **`property presolve`** Returns: int | None: **`property proj_implied_cuts`** Returns: int | None: **`property psd_cuts`** Returns: int | None: **`property psd_tol`** Returns: float | None: **`property pump_passes`** Returns: int | None: **`property qcp_dual`** Returns: int | None: **`property quad`** Returns: int | None: **`property record`** Returns: int | None: **`property relax_lift_cuts`** Returns: int | None: **`property result_file`** Returns: pathlib.Path | None: **`property rins`** Returns: int | None: **`property rlt_cuts`** Returns: int | None: **`property scale_flag`** Returns: int | None: **`property scenario_number`** Returns: int | None: **`property seed`** Returns: int | None: **`property server_password`** Returns: str | None: **`property server_timeout`** Returns: int | None: **`property sift_method`** Returns: int | None: **`property sifting`** Returns: int | None: **`property simplex_pricing`** Returns: int | None: **`property soft_mem_limit`** Returns: float | None: **`property sol_files`** Returns: str | None: **`property solution_limit`** Returns: int | None: **`property solution_number`** Returns: int | None: **`property solution_target`** Returns: int | None: **`property start_node_limit`** Returns: int | None: **`property start_number`** Returns: int | None: **`property strong_cg_cuts`** Returns: int | None: **`property sub_mip_cuts`** Returns: int | None: **`property sub_mip_nodes`** Returns: int | None: **`property symmetry`** Returns: int | None: **`property thread_limit`** Returns: int | None: **`property threads`** Returns: int | None: **`property time_limit`** Returns: datetime.timedelta | None: **`property token_server`** Returns: str | None: **`property ts_port`** Returns: int | None: **`property tune_cleanup`** Returns: float | None: **`property tune_criterion`** Returns: int | None: **`property tune_dynamic_jobs`** Returns: int | None: **`property tune_jobs`** Returns: int | None: **`property tune_metric`** Returns: int | None: **`property tune_output`** Returns: int | None: **`property tune_results`** Returns: int | None: **`property tune_target_mip_gap`** Returns: float | None: **`property tune_target_time`** Returns: float | None: **`property tune_time_limit`** Returns: datetime.timedelta | None: **`property tune_trials`** Returns: int | None: **`property update_mode`** Returns: int | None: **`property username`** Returns: str | None: **`property var_branch`** Returns: int | None: **`property wls_access_id`** Returns: str | None: **`property wls_config`** Returns: str | None: **`property wls_proxy`** Returns: str | None: **`property wls_secret`** Returns: str | None: **`property wls_token`** Returns: str | None: **`property wls_token_duration`** Returns: int | None: **`property wls_token_refresh`** Returns: float | None: **`property work_limit`** Returns: float | None: **`property worker_password`** Returns: str | None: **`property worker_pool`** Returns: str | None: **`property zero_half_cuts`** Returns: int | None: **`property zero_obj_nodes`** Returns: int | None: **`class Result`** **`class OptimizationStatusCode`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Cutoff = 6`** **`InfOrUnbd = 4`** **`Infeasible = 3`** **`Inprogress = 14`** **`Interrupted = 11`** **`IterationLimit = 7`** **`Loaded = 1`** **`MemLimit = 17`** **`NodeLimit = 8`** **`Numeric = 12`** **`Optimal = 2`** **`SolutionLimit = 10`** **`Suboptimal = 13`** **`TimeLimit = 9`** **`Unbounded = 5`** **`Unknown = 0`** **`UserObjLimit = 15`** **`WorkLimit = 16`** **`__nb_enum__ = `** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property bar_iter_count`** Returns: int | None: **`property bound_vio`** Returns: float | None: **`property constr_vio`** Returns: float | None: **`property farkas_proof`** Returns: float | None: **`property int_vio`** Returns: float | None: **`property iter_count`** Returns: float | None: **`property mip_gap`** Returns: float | None: **`property node_count`** Returns: float | None: **`property obj_bound`** Returns: float | None: **`property obj_bound_c`** Returns: float | None: **`property obj_val`** Returns: float | None: **`property pool_obj_bound`** Returns: float | None: **`property pool_obj_val`** Returns: numpy.ndarray: **`property runtime`** Returns: datetime.timedelta: **`property sol_count`** Returns: int | None: **`property status`** Returns: amplify.GurobiClient.Result.OptimizationStatusCode: **`property time_stamps`** Returns: list[tuple[float, datetime.timedelta]]: **`property var_names`** Returns: list[str] | None: **`property x`** Returns: numpy.ndarray: **`property xn`** Returns: list[numpy.ndarray[dtype=float64, writable=False]] | None: **`__init__(self) → None`** **`__init__(self, library_path: str) → None`** **パラメータ:** **library_path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve(self, objective: Poly | Matrix, dry_run: Literal[False] = False) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.GurobiClient.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.GurobiClient.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.GurobiClient.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`tune(self, objective: Poly | Matrix) → None`** **`tune(self, constraint: Constraint | ConstraintList) → None`** **`tune(self, objective: Poly | Matrix, constraint: Constraint | ConstraintList) → None`** tune > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property library_path`** Returns: str | None: **`property parameters`** Returns: amplify.GurobiClient.Parameters: **`property version`** Returns: str: **`property write_request_data`** Returns: str | None: **`property write_response_data`** Returns: str | None: --- # NECVA2Client **`class NECVA2Client`** ベースクラス: [`NECVA2Client`](#amplify.NECVA2Client) **Methods** | | | | --- | --- | | [`__init__`](#amplify.NECVA2Client.__init__) | | | [`solve`](#amplify.NECVA2Client.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.NECVA2Client.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`parameters`](#amplify.NECVA2Client.parameters) | Returns: amplify.NECVA2Client.Parameters: | | [`proxy`](#amplify.NECVA2Client.proxy) | Returns: str | None: | | [`set_andzero`](#amplify.NECVA2Client.set_andzero) | Returns: bool: | | [`set_fixed`](#amplify.NECVA2Client.set_fixed) | Returns: bool: | | [`set_maxone`](#amplify.NECVA2Client.set_maxone) | Returns: bool: | | [`set_minmaxone`](#amplify.NECVA2Client.set_minmaxone) | Returns: bool: | | [`set_onehot`](#amplify.NECVA2Client.set_onehot) | Returns: bool: | | [`set_orone`](#amplify.NECVA2Client.set_orone) | Returns: bool: | | [`set_supplement`](#amplify.NECVA2Client.set_supplement) | Returns: bool: | | [`token`](#amplify.NECVA2Client.token) | Returns: str: | | [`url`](#amplify.NECVA2Client.url) | Returns: str: | | [`version`](#amplify.NECVA2Client.version) | Returns: str: | | [`write_request_data`](#amplify.NECVA2Client.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.NECVA2Client.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property beta_list`** Returns: list[float] | None: **`property beta_range`** Returns: tuple[float, float, int] | None: **`property dense`** Returns: bool | None: **`property num_reads`** Returns: int | None: **`property num_results`** Returns: int | None: **`property num_sweeps`** Returns: int | None: **`property timeout`** Returns: datetime.timedelta | None: **`property ve_num`** Returns: int | None: **`property vector_mode`** Returns: amplify.NECVA2Client.VectorMode | None: **`class Result`** **`class Result`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property constraint`** Returns: bool: **`property energy`** Returns: float: **`property memory_usage`** Returns: float: **`property spin`** Returns: dict[str, int]: **`property time`** Returns: datetime.timedelta: **`class Timing`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property execution_time`** Returns: datetime.timedelta: **`property queue_time`** Returns: datetime.timedelta: **`property solve_qubo_time`** Returns: datetime.timedelta: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property result`** Returns: list[amplify.NECVA2Client.Result.Result]: **`property timing`** Returns: amplify.NECVA2Client.Result.Timing: **`class VectorMode`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Accuracy = 0`** **`Speed = 1`** **`__nb_enum__ = `** **`__init__(self) → None`** **`__init__(self, token: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve(self, objective: Poly | Matrix, dry_run: Literal[False] = False) → Result`** **`solve( self, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[False] = False, ) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** **`solve(self, constraint: Constraint | ConstraintList, dry_run: Literal[True]) → None`** **`solve( self, objective: Poly | Matrix, constraint: Constraint | ConstraintList, dry_run: Literal[True], ) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.NECVA2Client.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.NECVA2Client.Result: > [!NOTE] > > **Overload 3.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.NECVA2Client.Result: > [!NOTE] > > **Overload 4.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 5.** > > **Args:** > > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) > [!NOTE] > > **Overload 6.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * constraint (amplify.Constraint | amplify.ConstraintList) > * dry_run (typing.Literal[True]) **`__deprecated__ = 'NECVA2Client is deprecated because NEC Vector Annealing (VA) Service 2.0 ended on April 1, 2025.'`** **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property parameters`** Returns: amplify.NECVA2Client.Parameters: **`property proxy`** Returns: str | None: **`property set_andzero`** Returns: bool: **`property set_fixed`** Returns: bool: **`property set_maxone`** Returns: bool: **`property set_minmaxone`** Returns: bool: **`property set_onehot`** Returns: bool: **`property set_orone`** Returns: bool: **`property set_supplement`** Returns: bool: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # HitachiClient **`class HitachiClient`** ベースクラス: [`BaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) **Methods** | | | | --- | --- | | [`__init__`](#amplify.HitachiClient.__init__) | | | [`solve`](#amplify.HitachiClient.solve) | solve | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.HitachiClient.acceptable_degrees) | Returns: amplify.AcceptableDegrees: | | [`graph`](#amplify.HitachiClient.graph) | Returns: amplify.Graph: | | [`parameters`](#amplify.HitachiClient.parameters) | Returns: amplify.HitachiClient.Parameters: | | [`proxy`](#amplify.HitachiClient.proxy) | Returns: str | None: | | [`token`](#amplify.HitachiClient.token) | Returns: str: | | [`url`](#amplify.HitachiClient.url) | Returns: str: | | [`version`](#amplify.HitachiClient.version) | Returns: str: | | [`write_request_data`](#amplify.HitachiClient.write_request_data) | Returns: pathlib.Path | None: | | [`write_response_data`](#amplify.HitachiClient.write_response_data) | Returns: pathlib.Path | None: | **`class Parameters`** **`class Outputs`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property averaged_energy`** Returns: bool | None: **`property averaged_spins`** Returns: bool | None: **`property energies`** Returns: bool | None: **`property execution_time`** Returns: bool | None: **`property num_outputs`** Returns: int | None: **`property spins`** Returns: bool | None: **`class TemperatureParameters`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property temperature_initial`** Returns: float | None: **`property temperature_num_steps`** Returns: int | None: **`property temperature_step_length`** Returns: int | None: **`property temperature_target`** Returns: float | None: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property num_executions`** Returns: int | None: **`property outputs`** Returns: amplify.HitachiClient.Parameters.Outputs: **`property parameters`** Returns: amplify.HitachiClient.Parameters.TemperatureParameters: **`property type`** Returns: int: **`class Result`** **`class Result`** **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property averaged_energy`** Returns: float | None: **`property averaged_spins`** Returns: list[tuple[int, int, float]] | None: **`property energies`** Returns: numpy.ndarray: **`property execution_time`** Returns: datetime.timedelta: **`property spins`** Returns: list[list[tuple[int, int, int]]]: **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property job_id`** Returns: str: **`property message`** Returns: str | None: **`property result`** Returns: amplify.HitachiClient.Result.Result: **`property status`** Returns: int: **`__init__(self) → None`** **`__init__(self, token: str = '', url: str = '', proxy: str | None = None) → None`** **パラメータ:** * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Defaults to `''`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Defaults to `None`. **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`solve(self, objective: Poly | Matrix, dry_run: Literal[False] = False) → Result`** **`solve(self, objective: Poly | Matrix, dry_run: Literal[True]) → None`** solve > [!NOTE] > > **Overload 1.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[False]): Defaults to `False`. > > **Returns:** > > amplify.HitachiClient.Result: > [!NOTE] > > **Overload 2.** > > **Args:** > > * objective (amplify.Poly | amplify.Matrix) > * dry_run (typing.Literal[True]) **`property acceptable_degrees`** Returns: amplify.AcceptableDegrees: **`property graph`** Returns: amplify.Graph: **`property parameters`** Returns: amplify.HitachiClient.Parameters: **`property proxy`** Returns: str | None: **`property token`** Returns: str: **`property url`** Returns: str: **`property version`** Returns: str: **`property write_request_data`** Returns: pathlib.Path | None: **`property write_response_data`** Returns: pathlib.Path | None: --- # AcceptableDegrees **`class AcceptableDegrees`** Container of acceptable polynomial degrees by variable type for objective and constraints. **Methods** | | | | --- | --- | | [`__init__`](#amplify.AcceptableDegrees.__init__) | Construct acceptable degree settings. | **Attributes** | | | | --- | --- | | [`equality_constraints`](#amplify.AcceptableDegrees.equality_constraints) | Acceptable degrees for equality constraints. | | [`inequality_constraints`](#amplify.AcceptableDegrees.inequality_constraints) | Acceptable degrees for inequality constraints. | | [`objective`](#amplify.AcceptableDegrees.objective) | Acceptable degrees for objective terms. | **`__init__( self, objective: dict[VariableType | Literal['Binary', 'Ising', 'Integer', 'Real'], Degree | Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int] = {VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}, equality_constraints: dict[VariableType | Literal['Binary', 'Ising', 'Integer', 'Real'], Degree | Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int] = {VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}, inequality_constraints: dict[VariableType | Literal['Binary', 'Ising', 'Integer', 'Real'], Degree | Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int] = {VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}, ) → None`** Construct acceptable degree settings. **パラメータ:** * **objective** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) *|* [*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Binary', 'Ising', 'Integer', 'Real'], amplify.Degree | typing.Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int]*) -- Acceptable degrees for objective terms by variable type. Defaults to `{VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}`. * **equality_constraints** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) *|* [*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Binary', 'Ising', 'Integer', 'Real'], amplify.Degree | typing.Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int]*) -- Acceptable degrees for equality constraints by variable type. Defaults to `{VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}`. * **inequality_constraints** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) *|* [*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Binary', 'Ising', 'Integer', 'Real'], amplify.Degree | typing.Literal['Zero', 'Linear', 'Quadratic', 'Cubic', 'Quartic', 'HighOrder'] | int]*) -- Acceptable degrees for inequality constraints by variable type. Defaults to `{VariableType.Binary: Degree.Zero, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero}`. **`property equality_constraints`** Acceptable degrees for equality constraints. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] **`property inequality_constraints`** Acceptable degrees for inequality constraints. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] **`property objective`** Acceptable degrees for objective terms. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] --- # Degree **`class Degree`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Polynomial degree enumeration. **Members** **`Cubic = 3`** **`HighOrder = 5`** **`Linear = 1`** **`Quadratic = 2`** **`Quartic = 4`** **`Zero = 0`** --- # Solve ## Solve classes and functions ### Class | | | | --- | --- | | [`amplify.Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | Container of optimization solutions and conversion/runtime metadata. | | [`amplify.Values`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) | Mapping from variables to numeric values in a solution. | ### Function | | | | --- | --- | | [`amplify.solve`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) | Solve a combinatorial optimization problem. | | [`amplify.parallel_solve`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) | Solve multiple problems in parallel. | --- # Result **`class Result`** Container of optimization solutions and conversion/runtime metadata. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Result.__init__) | | | [`sort`](#amplify.Result.sort) | Sort solutions by feasibility and objective value. | **Attributes** | | | | --- | --- | | [`best`](#amplify.Result.best) | Best solution in the result set. | | [`client_result`](#amplify.Result.client_result) | Solver/client result. | | [`embedding`](#amplify.Result.embedding) | Graph embedding information. | | [`execution_time`](#amplify.Result.execution_time) | The time the solver used to solve the problem. | | [`filter_solution`](#amplify.Result.filter_solution) | Whether to filter out infeasible solutions. | | [`intermediate`](#amplify.Result.intermediate) | Model conversion information. | | [`num_solves`](#amplify.Result.num_solves) | Number of solve executions aggregated. | | [`response_time`](#amplify.Result.response_time) | The time between sending the request and receiving the response from the solver. | | [`solutions`](#amplify.Result.solutions) | View of all solutions. | | [`split`](#amplify.Result.split) | Split view for each independent solve. | | [`total_time`](#amplify.Result.total_time) | Total time including conversion and solve. | **`class GraphConversion`** Graph embedding conversion details used during solving. **`class ChainBreakFractions`** List-like view of chain break fractions. **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.GraphConversion.ChainBreakFractions.Iterator) **`__next__(self) → float`** **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) → float`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.GraphConversion.ChainBreakFractions.Iterator) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property chain_break_fractions`** Chain break fraction for each solve. **戻り値の型:** [*ChainBreakFractions*](#amplify.Result.GraphConversion.ChainBreakFractions) **`property chains`** Embedding chains for each logical variable. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)[dtype=uint32, writable=False]] **`property dst_graph`** Destination (physical) graph used for embedding. **戻り値の型:** [*Graph*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) **`property num_variables`** Number of physical variables used after embedding. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property poly`** Embedded polynomial. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property src_graph`** Source (input polynomial) graph for embedding. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), [*int*](https://docs.python.org/3/library/functions.html#int)]] **`property values_list`** Physical variable assignments for each solve. **戻り値の型:** [*ValuesList*](#amplify.Result.ValuesList) **`class ModelConversion`** Model conversion details used during solving. **`class IntermediateMapping`** Mapping between original and intermediate variables during model conversion. **`class ItemsView`** View of key-value pairs in [`IntermediateMapping`](#amplify.Result.ModelConversion.IntermediateMapping). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) → ItemsView`** **戻り値の型:** [*ItemsView*](#amplify.Result.ModelConversion.IntermediateMapping.ItemsView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → tuple[Poly, Poly]`** **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)] **`class KeysView`** View of keys in [`IntermediateMapping`](#amplify.Result.ModelConversion.IntermediateMapping). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__contains__(self, arg: Poly, /) → bool`** **`__contains__(self, arg: object, /) → bool`** __contains__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly) > > **Returns:** > > bool: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__init__(*args, **kwargs)`** **`__iter__(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`class ValuesView`** View of values in [`IntermediateMapping`](#amplify.Result.ModelConversion.IntermediateMapping). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) → ValuesView`** **戻り値の型:** [*ValuesView*](#amplify.Result.ModelConversion.IntermediateMapping.ValuesView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__contains__(self, arg: Poly, /) → bool`** **`__contains__(self, arg: object, /) → bool`** __contains__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly) > > **Returns:** > > bool: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__getitem__(self, arg: Poly, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__init__(*args, **kwargs)`** **`__iter__(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`items(self) → ItemsView`** **戻り値の型:** [*ItemsView*](#amplify.Result.ModelConversion.IntermediateMapping.ItemsView) **`keys(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`values(self) → ValuesView`** **戻り値の型:** [*ValuesView*](#amplify.Result.ModelConversion.IntermediateMapping.ValuesView) **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property mapping`** Mapping from input variables to intermediate expressions. **戻り値の型:** [*IntermediateMapping*](#amplify.Result.ModelConversion.IntermediateMapping) **`property model`** Intermediate model. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`property num_variables`** Number of variables in the intermediate model. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property values_list`** Intermediate variable assignments for each solve. **戻り値の型:** [*ValuesList*](#amplify.Result.ValuesList) **`class Solution`** Single solution entry in [`Result`](#amplify.Result). **`__init__(*args, **kwargs)`** **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property feasible`** Whether all constraints are satisfied. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`property objective`** Objective function value. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`property time`** Time at which the solver found this solution. **戻り値の型:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property values`** Variable assignments of the solution. **戻り値の型:** [*Values*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) **`class SolutionList`** List-like view of solutions. **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__next__(self) → Solution`** **戻り値の型:** [*Solution*](#amplify.Result.Solution) **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) → Solution`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Solution*](#amplify.Result.Solution) **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`class SplitView`** List-of-list-like view of solutions that splits solutions by independent solves. **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) → Result`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Result*](#amplify.Result) **`__init__(*args, **kwargs)`** **`__iter__(self) → SplitView`** **戻り値の型:** [*SplitView*](#amplify.Result.SplitView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → Result`** **戻り値の型:** [*Result*](#amplify.Result) **`class ValuesList`** List-like view of value mappings for solutions. **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.ValuesList.Iterator) **`__next__(self) → Values`** **戻り値の型:** [*Values*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) → Values`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Values*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.ValuesList.Iterator) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__getitem__(self, key: int) → Solution`** **パラメータ:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Solution*](#amplify.Result.Solution) **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`sort(self) → None`** Sort solutions by feasibility and objective value. **`__nb_signature__ = 'class Result(typing.Generic[_BaseClient_co])'`** **`property best`** Best solution in the result set. **戻り値の型:** [*Solution*](#amplify.Result.Solution) **`property client_result`** Solver/client result. **戻り値の型:** [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result) | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Result) | [*SampleSet*](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | [*SampleSet*](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | [*SampleSet*](https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod/sampleset.html#dimod.SampleSet) | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result) | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result) | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result) | amplify.DASClient.Result | [*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result) | [*object*](https://docs.python.org/3/library/functions.html#object) | *None* **`property embedding`** Graph embedding information. **戻り値の型:** [*GraphConversion*](#amplify.Result.GraphConversion) | *None* **`property execution_time`** The time the solver used to solve the problem. **戻り値の型:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property filter_solution`** Whether to filter out infeasible solutions. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`property intermediate`** Model conversion information. **戻り値の型:** [*ModelConversion*](#amplify.Result.ModelConversion) **`property num_solves`** Number of solve executions aggregated. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property response_time`** The time between sending the request and receiving the response from the solver. **戻り値の型:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property solutions`** View of all solutions. **戻り値の型:** [*SolutionList*](#amplify.Result.SolutionList) **`property split`** Split view for each independent solve. **戻り値の型:** [*SplitView*](#amplify.Result.SplitView) **`property total_time`** Total time including conversion and solve. **戻り値の型:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) --- # Values **`class Values`** Mapping from variables to numeric values in a solution. **Methods** | | | | --- | --- | | [`__init__`](#amplify.Values.__init__) | | | [`items`](#amplify.Values.items) | | | [`keys`](#amplify.Values.keys) | | | [`values`](#amplify.Values.values) | | **`class ItemsView`** View of key-value pairs in [`Values`](#amplify.Values). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) → ItemsView`** **戻り値の型:** [*ItemsView*](#amplify.Values.ItemsView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → tuple[Poly, float]`** **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [*float*](https://docs.python.org/3/library/functions.html#float)] **`class KeysView`** View of keys in [`Values`](#amplify.Values). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__contains__(self, arg: Poly, /) → bool`** **`__contains__(self, arg: object, /) → bool`** __contains__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly) > > **Returns:** > > bool: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__init__(*args, **kwargs)`** **`__iter__(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Values.KeysView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`class ValuesView`** View of values in [`Values`](#amplify.Values). **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) → ValuesView`** **戻り値の型:** [*ValuesView*](#amplify.Values.ValuesView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) → float`** **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__bool__(self) → bool`** **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__contains__(self, arg: Poly, /) → bool`** **`__contains__(self, arg: object, /) → bool`** __contains__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly) > > **Returns:** > > bool: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__getitem__(self, arg: Poly, /) → float`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__init__(*args, **kwargs)`** **`__iter__(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Values.KeysView) **`__len__(self) → int`** **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`items(self) → ItemsView`** **戻り値の型:** [*ItemsView*](#amplify.Values.ItemsView) **`keys(self) → KeysView`** **戻り値の型:** [*KeysView*](#amplify.Values.KeysView) **`values(self) → ValuesView`** **戻り値の型:** [*ValuesView*](#amplify.Values.ValuesView) --- # solve **`solve( model: Model | Poly | Matrix | Constraint | ConstraintList, client: amplify._BaseClient, *, dry_run: Literal[False] = False, integer_encoding_method: Literal['Unary', 'Linear', 'Binary', 'Default'] | IntegerEncodingMethod = IntegerEncodingMethod.Default, real_encoding_method: Literal['Random4', 'Random8', 'Random16', 'Random32'] | RealEncodingMethod = RealEncodingMethod.Random16, quadratization_method: Literal['IshikawaKZFD', 'Substitute'] | QuadratizationMethod = QuadratizationMethod.Substitute, substitution_multiplier: float = 1.0, embedding_method: Literal['Default', 'Minor', 'Clique', 'Parallel'] | EmbeddingMethod = EmbeddingMethod.Default, embedding_timeout: float | timedelta = 10.0, chain_strength: float = 1.0, num_solves: int = 1, filter_solution: bool = True, sort_solution: bool = True, ) → Result[amplify._BaseClient]`** **`solve( model: Model | Poly | Matrix | Constraint | ConstraintList, client: BaseClient | amplify.CustomClientProtocol, *, dry_run: Literal[True], integer_encoding_method: Literal['Unary', 'Linear', 'Binary', 'Default'] | IntegerEncodingMethod = IntegerEncodingMethod.Default, real_encoding_method: Literal['Random4', 'Random8', 'Random16', 'Random32'] | RealEncodingMethod = RealEncodingMethod.Random16, quadratization_method: Literal['IshikawaKZFD', 'Substitute'] | QuadratizationMethod = QuadratizationMethod.Substitute, substitution_multiplier: float = 1.0, embedding_method: Literal['Default', 'Minor', 'Clique', 'Parallel'] | EmbeddingMethod = EmbeddingMethod.Default, embedding_timeout: float | timedelta = 10.0, chain_strength: float = 1.0, num_solves: int = 1, filter_solution: bool = True, sort_solution: bool = True, ) → Result`** Solve a combinatorial optimization problem. Pass a model (or model-constructible object) and a solver client. The SDK automatically performs model conversion and embedding as needed. Use keyword arguments to configure conversion and embedding behavior. > [!NOTE] > > **Overload 1.** > > **Args:** > > * model (amplify.Model | amplify.Poly | amplify.Matrix | amplify.Constraint | amplify.ConstraintList): Optimization problem to solve. > * client (amplify._BaseClient): Client used to solve the problem. > * dry_run (typing.Literal[False]): When `True`, perform conversion only (no solver execution). Defaults to `False`. > * integer_encoding_method (typing.Literal['Unary', 'Linear', 'Binary', 'Default'] | amplify.IntegerEncodingMethod): Algorithm for converting integer variables to binary/Ising variables. Defaults to `IntegerEncodingMethod.Default`. > * real_encoding_method (typing.Literal['Random4', 'Random8', 'Random16', 'Random32'] | amplify.RealEncodingMethod): Algorithm for converting real variables to binary/Ising variables. Defaults to `RealEncodingMethod.Random16`. > * quadratization_method (typing.Literal['IshikawaKZFD', 'Substitute'] | amplify.QuadratizationMethod): Algorithm for reducing degree of polynomial. Defaults to `QuadratizationMethod.Substitute`. > * substitution_multiplier (float): Multiplier for substitution penalty scaling (used only with [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute)). Defaults to `1.0`. > * embedding_method (typing.Literal['Default', 'Minor', 'Clique', 'Parallel'] | amplify.EmbeddingMethod): Embedding algorithm. Defaults to `EmbeddingMethod.Default`. > * embedding_timeout (float | datetime.timedelta): Embedding timeout in seconds. Defaults to `10.0`. > * chain_strength (float): Chain strength for embedding. Defaults to `1.0`. > * num_solves (int): Number of independent solves. Defaults to `1`. > * filter_solution (bool): Whether to filter out infeasible solutions, default is `True`. Defaults to `True`. > * sort_solution (bool): Whether to sort solutions by objective value, default is `True`. Defaults to `True`. > > **Returns:** > > amplify.Result[amplify._BaseClient]: Optimization output. > [!NOTE] > > **Overload 2.** > > **Args:** > > * model (amplify.Model | amplify.Poly | amplify.Matrix | amplify.Constraint | amplify.ConstraintList): Optimization problem to solve. > * client (amplify.BaseClient | amplify.CustomClientProtocol): Client used to solve the problem. > * dry_run (typing.Literal[True]): When `True`, perform conversion only (no solver execution). > * integer_encoding_method (typing.Literal['Unary', 'Linear', 'Binary', 'Default'] | amplify.IntegerEncodingMethod): Algorithm for converting integer variables to binary/Ising variables. Defaults to `IntegerEncodingMethod.Default`. > * real_encoding_method (typing.Literal['Random4', 'Random8', 'Random16', 'Random32'] | amplify.RealEncodingMethod): Algorithm for converting real variables to binary/Ising variables. Defaults to `RealEncodingMethod.Random16`. > * quadratization_method (typing.Literal['IshikawaKZFD', 'Substitute'] | amplify.QuadratizationMethod): Algorithm for reducing degree of polynomial. Defaults to `QuadratizationMethod.Substitute`. > * substitution_multiplier (float): Multiplier for substitution penalty scaling (used only with [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute)). Defaults to `1.0`. > * embedding_method (typing.Literal['Default', 'Minor', 'Clique', 'Parallel'] | amplify.EmbeddingMethod): Embedding algorithm. Defaults to `EmbeddingMethod.Default`. > * embedding_timeout (float | datetime.timedelta): Embedding timeout in seconds. Defaults to `10.0`. > * chain_strength (float): Chain strength for embedding. Defaults to `1.0`. > * num_solves (int): Number of independent solves. Defaults to `1`. > * filter_solution (bool): Whether to filter out infeasible solutions, default is `True`. Defaults to `True`. > * sort_solution (bool): Whether to sort solutions by objective value, default is `True`. Defaults to `True`. > > **Returns:** > > amplify.Result: Optimization output. --- # parallel_solve **`parallel_solve( model: Sequence[Model | Poly | Matrix | Constraint | ConstraintList] | Model | Poly | Matrix | Constraint | ConstraintList, client: BaseClient | amplify.CustomClientProtocol | Sequence[BaseClient | amplify.CustomClientProtocol], *, dry_run: Sequence[bool] | bool = False, integer_encoding_method: Sequence[Literal['Unary', 'Linear', 'Binary', 'Default'] | IntegerEncodingMethod] | Literal['Unary', 'Linear', 'Binary', 'Default'] | IntegerEncodingMethod = IntegerEncodingMethod.Default, real_encoding_method: Sequence[Literal['Random4', 'Random8', 'Random16', 'Random32'] | RealEncodingMethod] | Literal['Random4', 'Random8', 'Random16', 'Random32'] | RealEncodingMethod = RealEncodingMethod.Random16, quadratization_method: Sequence[Literal['IshikawaKZFD', 'Substitute'] | QuadratizationMethod] | Literal['IshikawaKZFD', 'Substitute'] | QuadratizationMethod = QuadratizationMethod.Substitute, substitution_multiplier: Sequence[float] | float = 1.0, embedding_method: Sequence[Literal['Default', 'Minor', 'Clique', 'Parallel'] | EmbeddingMethod] | Literal['Default', 'Minor', 'Clique', 'Parallel'] | EmbeddingMethod = EmbeddingMethod.Default, embedding_timeout: Sequence[timedelta | float] | timedelta | float = 10.0, chain_strength: Sequence[float] | float = 1.0, num_solves: Sequence[int] | int = 1, filter_solution: Sequence[bool] | bool = True, sort_solution: Sequence[bool] | bool = True, concurrency: int = 0, ) → list[Result | None]`** Solve multiple problems in parallel. Solve multiple `(model, client)` jobs concurrently. Both `model` and `client` accept either a single object or a sequence. - If one of them is a sequence, the single object is broadcast to all jobs. - If both are sequences, they must have the same length and are paired element-wise. Most keyword arguments also accept either a single value or a sequence and follow the same broadcasting rule. **パラメータ:** * **model** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) *|* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) *|* [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)*] |* [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) *|* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) *|* [*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Problems to solve. * **client** ([*BaseClient*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) *| amplify.CustomClientProtocol |* [*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*BaseClient*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BaseClient.md#amplify.BaseClient) *| amplify.CustomClientProtocol]*) -- Clients used for solving. * **dry_run** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*bool*](https://docs.python.org/3/library/functions.html#bool)*] |* [*bool*](https://docs.python.org/3/library/functions.html#bool)) -- When `True`, perform conversion only (no solver execution). Defaults to `False`. * **integer_encoding_method** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Unary', 'Linear', 'Binary', 'Default'] | amplify.IntegerEncodingMethod] | typing.Literal['Unary', 'Linear', 'Binary', 'Default'] | amplify.IntegerEncodingMethod*) -- Algorithm for converting integer variables to binary/Ising variables. Defaults to `IntegerEncodingMethod.Default`. * **real_encoding_method** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Random4', 'Random8', 'Random16', 'Random32'] | amplify.RealEncodingMethod] | typing.Literal['Random4', 'Random8', 'Random16', 'Random32'] | amplify.RealEncodingMethod*) -- Algorithm for converting real variables to binary/Ising variables. Defaults to `RealEncodingMethod.Random16`. * **quadratization_method** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['IshikawaKZFD', 'Substitute'] | amplify.QuadratizationMethod] | typing.Literal['IshikawaKZFD', 'Substitute'] | amplify.QuadratizationMethod*) -- Algorithm for reducing degree of polynomial. Defaults to `QuadratizationMethod.Substitute`. * **substitution_multiplier** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*] |* [*float*](https://docs.python.org/3/library/functions.html#float)) -- Multiplier for substitution penalty scaling (used only with [`Substitute`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute)). Defaults to `1.0`. * **embedding_method** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Default', 'Minor', 'Clique', 'Parallel'] | amplify.EmbeddingMethod] | typing.Literal['Default', 'Minor', 'Clique', 'Parallel'] | amplify.EmbeddingMethod*) -- Embedding algorithm. Defaults to `EmbeddingMethod.Default`. * **embedding_timeout** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) *|* [*float*](https://docs.python.org/3/library/functions.html#float)*] |* [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) -- Embedding timeout in seconds. Defaults to `10.0`. * **chain_strength** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*] |* [*float*](https://docs.python.org/3/library/functions.html#float)) -- Chain strength for embedding. Defaults to `1.0`. * **num_solves** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of independent solves. Defaults to `1`. * **filter_solution** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*bool*](https://docs.python.org/3/library/functions.html#bool)*] |* [*bool*](https://docs.python.org/3/library/functions.html#bool)) -- Whether to filter out infeasible solutions, default is `True`. Defaults to `True`. * **sort_solution** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*bool*](https://docs.python.org/3/library/functions.html#bool)*] |* [*bool*](https://docs.python.org/3/library/functions.html#bool)) -- Whether to sort solutions by objective value, default is `True`. Defaults to `True`. * **concurrency** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Max concurrency (`0` lets the SDK choose). Defaults to `0`. **戻り値:** Results for each job. An entry can be `None` if all solves in that job failed. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Result*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | *None*] --- # Misc. ## Function | | | | --- | --- | | [`amplify.set_num_threads`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.set_num_threads.md#amplify.set_num_threads) | Set the number of threads used for parallel computation. | | [`amplify.load_lp`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) | Load an LP file and construct a model. | | [`amplify.save_lp`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_lp.md#amplify.save_lp) | Save a model to an LP file. | | [`amplify.load_qplib`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib) | Load a QPLIB file and construct a model. | | [`amplify.save_qplib`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.save_qplib.md#amplify.save_qplib) | Save a model to a QPLIB file. | | [`amplify.set_seed`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.set_seed.md#amplify.set_seed) | Set the seed for random number generation. | ## Attribute | | | | --- | --- | | [`amplify.__version__`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.__version__.md#amplify.__version__) | The version of the SDK. | --- # set_num_threads **`set_num_threads(arg: int, /) → None`** Set the number of threads used for parallel computation. This function sets the number of threads used for parallel computation in Amplify. If set to `0`, Amplify attempts to use the number of concurrent threads supported by the hardware. This setting affects [`einsum()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) and graph embedding when [`Minor`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) is used. In parallel solving with [`parallel_solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve), the number of threads can be set independently, with a default that is at least the number of jobs. **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of threads to use. --- # load_lp **`load_lp( filename: str | PathLike, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, ) → tuple[Model, VariableGenerator]`** Load an LP file and construct a model. The LP format follows a supported subset of the Gurobi LP format. Return the loaded model and its associated variable generator. **パラメータ:** * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike)) -- filename * **penalty_formulation** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation*) -- Penalty formulation used for inequality constraints. Defaults to `PenaltyFormulation.Default`. **戻り値:** Loaded model and its associated variable generator. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [*VariableGenerator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)] --- # save_lp **`save_lp(model: Model, filename: str | PathLike) → None`** Save a model to an LP file. **パラメータ:** * **model** ([*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) -- model * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike)) -- Output file path. --- # load_qplib **`load_qplib( filename: str | PathLike, penalty_formulation: Literal['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | PenaltyFormulation = PenaltyFormulation.Default, ) → tuple[Model, VariableGenerator]`** Load a QPLIB file and construct a model. The QPLIB format follows a supported subset of the QPLIB specification. Return the loaded model and its associated variable generator. **パラメータ:** * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike)) -- filename * **penalty_formulation** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal)*['Default', 'IntegerVariable', 'RealVariable', 'Relaxation', 'LinearRelaxation', 'QuadraticRelaxation'] | amplify.PenaltyFormulation*) -- Penalty formulation used for inequality constraints. Defaults to `PenaltyFormulation.Default`. **戻り値:** Loaded model and its associated variable generator. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [*VariableGenerator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)] --- # save_qplib **`save_qplib(model: Model, filename: str | PathLike) → None`** Save a model to a QPLIB file. **パラメータ:** * **model** ([*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) -- model * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike)) -- Output file path. --- # set_seed **`set_seed(arg: int, /) → None`** Set the seed for random number generation. This function sets the seed for random number generation in Amplify. This affects randomized encoding methods. Note that this function does not affect the randomness of external solvers used through Amplify clients. **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Seed value to set. --- # __version__ **`__version__ = '1.6.3'`** The version of the SDK. --- # Quantum * [Client](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/client.md) * [QuantumBaseClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md) * [AerClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md) * [AQTClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md) * [BraketSimulatorClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md) * [IBMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md) * [IonQClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md) * [IQMClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md) * [QulacsClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md) * [RigettiClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md) * [QUDORAClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md) * [OqtopusClient](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md) * [Algorithm](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md) * [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md#module-amplify) * [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md#rqaoa) * [Common](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/algorithm.md#common) * [Minimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/minimize.md) * [ScipyMinimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md) * [ScipyMinimizeOptions](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md) * [ScipyMinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md) * [NoOpMinimize](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md) * [NoOpMinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md) * [MinimizeProtocol](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md) * [MinimizeResult](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md) * [Sampler](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/sampler.md) * [SamplerProtocol](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md) * [SamplingDurations](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md) * [AerDeviceType](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md) * [QiskitJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md) * [QulacsJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md) * [BraketJobMeta](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md) * [Circuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/circuit.md) * [QiskitCircuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md) * [QulacsCircuit](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md) * [Misc.](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/quantum/misc.md) * [IsingSeqFreqList](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md) --- # Client | | | | --- | --- | | [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient) | Abstract base class for clients that target a specific backend sampler. | | [`AerClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) | Client that executes quantum circuits using the Qiskit Aer simulator. | | [`AQTClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) | Client that executes quantum circuits on AQT hardware via Amazon Braket. | | [`BraketSimulatorClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) | Client that executes quantum circuits on Amazon Braket simulators. | | [`IBMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) | Client that executes quantum circuits on IBM Quantum hardware. | | [`IonQClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) | Client that executes quantum circuits on IonQ hardware. | | [`IQMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) | Client that executes quantum circuits on IQM hardware via Amazon Braket. | | [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) | Client that executes quantum circuits using the Qulacs simulator. | | [`RigettiClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) | Client that executes quantum circuits on Rigetti hardware via Amazon Braket. | | [`QUDORAClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) | Client that executes quantum circuits on QUDORA hardware. | | [`OqtopusClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) | Client that executes quantum circuits on OQTOPUS Cloud. | --- # QuantumBaseClient **`class QuantumBaseClient`** ベースクラス: `_QuantumBaseClient`[`AlgoType`], [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`AlgoType`, `SamplingMeta_co`, `CircType_co`] Abstract base class for clients that target a specific backend sampler. Instantiate a concrete subclass such as [`QulacsClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) or [`IBMClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) rather than using this class directly. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QuantumBaseClient.__init__) | Initialize a QuantumBaseClient. | | [`solve`](#amplify.QuantumBaseClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.QuantumBaseClient.version) | Return the version string of the amplify-quantum package. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.QuantumBaseClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.QuantumBaseClient.algo) | The algorithm class used by this client. | | [`parameters`](#amplify.QuantumBaseClient.parameters) | Algorithm parameters instance. | **`__init__(algo: type[AlgoType]) → None`** Initialize a QuantumBaseClient. **パラメータ:** **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use. Must conform to the [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) protocol. **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → Result[SamplingMeta_co] | None`** **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → Result[SamplingMeta_co] | None`** **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the version string of the amplify-quantum package. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). --- # AerClient **`class AerClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QiskitJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits using the Qiskit Aer simulator. Runs circuits locally on CPU or GPU via Aer, or can noise-model a specific QPU by providing its name. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.AerClient.__init__) | Initialize an AerClient. | | [`get_options`](#amplify.AerClient.get_options) | Current AerSimulator options, including `device` and `method`. | | [`set_options`](#amplify.AerClient.set_options) | Set AerSimulator options. | | [`solve`](#amplify.AerClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.AerClient.version) | Return the qiskit-aer package version. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.AerClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.AerClient.algo) | The algorithm class used by this client. | | [`channel`](#amplify.AerClient.channel) | IBM Quantum channel type (e.g., `"ibm_quantum_platform"`), or `None`. | | [`device`](#amplify.AerClient.device) | Simulation device. | | [`method`](#amplify.AerClient.method) | Aer simulation method (e.g., `"automatic"`, `"statevector"`). | | [`noise_model`](#amplify.AerClient.noise_model) | Name of the target backend to simulate, or `None` for an ideal simulator. | | [`proxy`](#amplify.AerClient.proxy) | Proxy server URL used for network requests, or `None` for no proxy. | | [`qiskit_pass_manager`](#amplify.AerClient.qiskit_pass_manager) | Qiskit transpilation pass manager. | | [`token`](#amplify.AerClient.token) | IBM Quantum API token used to authenticate, or `None` if not set. | | [`url`](#amplify.AerClient.url) | IBM Quantum service URL, or `None` to use the default endpoint. | | [`verify`](#amplify.AerClient.verify) | Whether to verify SSL certificates, or `None` to use the system default. | | [`parameters`](#amplify.AerClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], token: str | None = None, url: str | None = None, proxy: str | None = None, verify: bool | None = None, noise_model: str | None = None, channel: ChannelType | None = None, qiskit_pass_manager: PassManager | EllipsisType | None = Ellipsis, device: AerDeviceType = 'CPU', method: str = 'automatic', **options, ) → None`** Initialize an AerClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- IBM Quantum API token. Required when *noise_model* refers to a real IBM backend (used to fetch the noise model). * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- IBM Quantum service URL. Uses the default endpoint if `None`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Proxy server URL for network requests. * **verify** ([*bool*](https://docs.python.org/3/library/functions.html#bool) *| None*) -- Whether to verify SSL certificates. Uses the system default if `None`. * **noise_model** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Name of the backend to simulate. Accepts `"fake_*"` names for built-in fake backends, `"ibm_*"` names to noise-model a real IBM device, or any other name which is converted automatically. If `None`, an ideal simulator is used. * **channel** (*ChannelType | None*) -- IBM Quantum channel type (e.g., `"ibm_quantum_platform"`). Only relevant when *noise_model* refers to a real IBM backend. * **qiskit_pass_manager** (*PassManager | EllipsisType | None*) -- Custom Qiskit transpilation pass manager. If `...` (default), a preset pass manager is generated automatically. Pass `None` to skip transpilation. * **device** (*AerDeviceType*) -- Simulation device. One of `"CPU"`, `"GPU"`, or `"Thrust"`. Defaults to `"CPU"`. * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Aer simulation method (e.g., `"automatic"`, `"statevector"`, `"density_matrix"`). Defaults to `"automatic"`. * `**options` -- Additional options forwarded to [`qiskit_aer.AerSimulator.set_options()`](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html#qiskit_aer.AerSimulator.set_options). **`get_options() → dict[str, Any]`** Current AerSimulator options, including `device` and `method`. **`set_options(**options) → None`** Set AerSimulator options. **パラメータ:** `**options` -- Options forwarded to [`qiskit_aer.AerSimulator.set_options()`](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html#qiskit_aer.AerSimulator.set_options). `device` and `method` are handled specially and update the corresponding properties. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the qiskit-aer package version. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property channel: ChannelType | None`** IBM Quantum channel type (e.g., `"ibm_quantum_platform"`), or `None`. **`property device: Literal['CPU', 'GPU', 'Thrust']`** Simulation device. One of `"CPU"`, `"GPU"`, or `"Thrust"`. **`property method: str`** Aer simulation method (e.g., `"automatic"`, `"statevector"`). **`property noise_model: str | None`** Name of the target backend to simulate, or `None` for an ideal simulator. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property proxy: str | None`** Proxy server URL used for network requests, or `None` for no proxy. **`property qiskit_pass_manager: PassManager | EllipsisType | None`** Qiskit transpilation pass manager. `...` (default) generates a preset pass manager automatically; `None` skips transpilation. **`property token: str | None`** IBM Quantum API token used to authenticate, or `None` if not set. **`property url: str | None`** IBM Quantum service URL, or `None` to use the default endpoint. **`property verify: bool | None`** Whether to verify SSL certificates, or `None` to use the system default. --- # AQTClient **`class AQTClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on AQT hardware via Amazon Braket. Connects to AQT devices through the Amazon Braket service and runs circuits on the specified device. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.AQTClient.__init__) | Initialize an AQTClient. | | [`solve`](#amplify.AQTClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.AQTClient.version) | Return the backend version string. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.AQTClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.AQTClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.AQTClient.device) | Name of the target AQT device. | | [`provider`](#amplify.AQTClient.provider) | Provider used to connect to the AQT device. | | [`parameters`](#amplify.AQTClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], device: str = 'IbexQ1', provider: AwsSession | None = None, ) → None`** Initialize an AQTClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Name or ARN of the AQT device. Defaults to the first non-underscore member of `braket.devices.Devices.AQT`. * **provider** (*AwsSession | None*) -- Provider used to connect to the AQT device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the backend version string. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: str`** Name of the target AQT device. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property provider: AwsSession | None`** Provider used to connect to the AQT device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. Set to None to clear configured credentials. --- # BraketSimulatorClient **`class BraketSimulatorClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on Amazon Braket simulators. Supports both local simulators (`braket_sv`, `braket_dm`) and managed AWS simulators (`SV1`, `DM1`). Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.BraketSimulatorClient.__init__) | Initialize a BraketSimulatorClient. | | [`solve`](#amplify.BraketSimulatorClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.BraketSimulatorClient.version) | Return the backend version string. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.BraketSimulatorClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.BraketSimulatorClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.BraketSimulatorClient.device) | Name of the target Braket simulator. | | [`provider`](#amplify.BraketSimulatorClient.provider) | Authentication for AWS-managed simulators. | | [`parameters`](#amplify.BraketSimulatorClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], device: Literal['braket_sv', 'braket_dm', 'SV1', 'DM1'] = 'braket_sv', provider: AwsSession | None = None, ) → None`** Initialize a BraketSimulatorClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **device** (*BraketSimulatorName*) -- Simulator name. One of `"braket_sv"`, `"braket_dm"`, `"SV1"`, or `"DM1"`. * **provider** (*AwsSession | None*) -- Authentication for AWS-managed simulators (`"SV1"`, `"DM1"`). Set to an `braket.aws.AwsSession` to configure credentials. Required for on-demand simulators; ignored for local simulators (`"braket_sv"`, `"braket_dm"`). **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the backend version string. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: Literal['braket_sv', 'braket_dm', 'SV1', 'DM1']`** Name of the target Braket simulator. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property provider: AwsSession | None`** Authentication for AWS-managed simulators. Set to an `braket.aws.AwsSession` to configure credentials. Required for on-demand simulators (`"SV1"`, `"DM1"`); ignored for local simulators (`"braket_sv"`, `"braket_dm"`). Set to None to clear configured credentials. --- # IBMClient **`class IBMClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QiskitJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)], [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`AlgoType`] Client that executes quantum circuits on IBM Quantum hardware. Connects to the IBM Quantum platform using an API token and runs circuits on the specified QPU (or the least-busy available one). Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.IBMClient.__init__) | Initialize an IBMClient. | | [`solve`](#amplify.IBMClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.IBMClient.version) | Return the IBM Quantum backend version. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.IBMClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.IBMClient.algo) | The algorithm class used by this client. | | [`channel`](#amplify.IBMClient.channel) | IBM Quantum channel type (e.g., `"ibm_quantum_platform"`), or `None`. | | [`device`](#amplify.IBMClient.device) | Name of the target IBM Quantum backend, or `None` to select automatically. | | [`proxy`](#amplify.IBMClient.proxy) | Proxy server URL used for network requests, or `None` for no proxy. | | [`qiskit_pass_manager`](#amplify.IBMClient.qiskit_pass_manager) | Qiskit transpilation pass manager. | | [`token`](#amplify.IBMClient.token) | IBM Quantum API token used to authenticate, or `None` if not set. | | [`url`](#amplify.IBMClient.url) | IBM Quantum service URL, or `None` to use the default endpoint. | | [`verify`](#amplify.IBMClient.verify) | Whether to verify SSL certificates, or `None` to use the system default. | | [`parameters`](#amplify.IBMClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], token: str | None = None, url: str | None = None, proxy: str | None = None, verify: bool | None = None, device: str | None = None, channel: ChannelType | None = None, qiskit_pass_manager: PassManager | EllipsisType | None = Ellipsis, ) → None`** Initialize an IBMClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- IBM Quantum API token. Required to access real hardware. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- IBM Quantum service URL. Uses the default endpoint if `None`. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Proxy server URL for network requests. * **verify** ([*bool*](https://docs.python.org/3/library/functions.html#bool) *| None*) -- Whether to verify SSL certificates. Uses the system default if `None`. * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Name of the IBM Quantum backend (e.g., `"ibm_brisbane"`). If `None`, the least-busy available backend is selected automatically. * **channel** (*ChannelType | None*) -- IBM Quantum channel type (e.g., `"ibm_quantum_platform"`). * **qiskit_pass_manager** (*PassManager | EllipsisType | None*) -- Custom Qiskit transpilation pass manager. If `...` (default), a preset pass manager is generated automatically. Pass `None` to skip transpilation. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the IBM Quantum backend version. **例外:** [**RuntimeError**](https://docs.python.org/3/library/exceptions.html#RuntimeError) -- If the backend cannot be initialized (e.g., invalid or missing token). **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property channel: Literal['ibm_quantum_platform', 'ibm_cloud', 'local'] | None`** IBM Quantum channel type (e.g., `"ibm_quantum_platform"`), or `None`. **`property device: str | None`** Name of the target IBM Quantum backend, or `None` to select automatically. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property proxy: str | None`** Proxy server URL used for network requests, or `None` for no proxy. **`property qiskit_pass_manager: PassManager | EllipsisType | None`** Qiskit transpilation pass manager. `...` (default) generates a preset pass manager automatically; `None` skips transpilation. **`property token: str | None`** IBM Quantum API token used to authenticate, or `None` if not set. **`property url: str | None`** IBM Quantum service URL, or `None` to use the default endpoint. **`property verify: bool | None`** Whether to verify SSL certificates, or `None` to use the system default. --- # IonQClient **`class IonQClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta) | `IonQJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on IonQ hardware. Connects to IonQ trapped-ion devices either directly through the IonQ API or through the Amazon Braket service and runs circuits on the specified device. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.IonQClient.__init__) | Initialize an IonQClient. | | [`get_options`](#amplify.IonQClient.get_options) | Get the current sampler options. | | [`set_options`](#amplify.IonQClient.set_options) | Set sampler options. | | [`solve`](#amplify.IonQClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.IonQClient.version) | Return the backend version string. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.IonQClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.IonQClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.IonQClient.device) | Name of the target IonQ device. | | [`provider`](#amplify.IonQClient.provider) | Provider used to connect to the IonQ device. | | [`url`](#amplify.IonQClient.url) | URL for the IonQ API endpoint. | | [`token`](#amplify.IonQClient.token) | Token for authenticating with the IonQ API. | | [`parameters`](#amplify.IonQClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], device: str = 'Forte-1', provider: AwsSession | None = None, token: str | None = None, url: str | None = None, error_mitigation: Literal['debias'] | None = None, **options, ) → None`** Initialize an IonQClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Name or ARN of the IonQ device. Defaults to "Forte-1". * **provider** (*AwsSession | None*) -- Provider used to connect to the IonQ device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- IonQ API token for authentication. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- URL for the IonQ API endpoint. * **error_mitigation** (*Literal["debias"] | None*) -- Error mitigation strategy. Pass "debias" to enable debiasing. None to disable error mitigation. Defaults to None. * `**options` -- Additional options to configure the sampler. **`get_options() → dict[str, Any]`** Get the current sampler options. **`set_options(**options) → None`** Set sampler options. Options will be cleared when the provider is switched. Values passed here take precedence over the error_mitigation attribute. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the backend version string. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: str`** Name of the target IonQ device. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property provider: AwsSession | None`** Provider used to connect to the IonQ device. Set to a `braket.aws.AwsSession` to connect via Amazon Braket. Set to `None` to use the IonQ API directly with [`url`](#amplify.IonQClient.url) and [`token`](#amplify.IonQClient.token). **`token: str | None`** Token for authenticating with the IonQ API. **`url: str | None`** URL for the IonQ API endpoint. If None, inferred from the token. --- # IQMClient **`class IQMClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on IQM hardware via Amazon Braket. Connects to IQM superconducting devices through the Amazon Braket service and runs circuits on the specified device. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.IQMClient.__init__) | Initialize an IQMClient. | | [`solve`](#amplify.IQMClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.IQMClient.version) | Return the backend version string. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.IQMClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.IQMClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.IQMClient.device) | Name of the target IQM device. | | [`provider`](#amplify.IQMClient.provider) | Provider used to connect to the IQM device. | | [`parameters`](#amplify.IQMClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], device: str = 'Garnet', provider: AwsSession | None = None, ) → None`** Initialize an IQMClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Name or ARN of the IQM device. Defaults to the first non-underscore member of `braket.devices.Devices.IQM`. * **provider** (*AwsSession | None*) -- Provider used to connect to the IQM device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the backend version string. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: str`** Name of the target IQM device. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property provider: AwsSession | None`** Provider used to connect to the IQM device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. Set to None to clear configured credentials. --- # QulacsClient **`class QulacsClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QulacsJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta), [`QulacsCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md#amplify.QulacsCircuit)] Client that executes quantum circuits using the Qulacs simulator. Runs circuits locally using Qulacs state-vector simulation. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QulacsClient.__init__) | Initialize a QuantumBaseClient. | | [`solve`](#amplify.QulacsClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.QulacsClient.version) | Return the Qulacs package version. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.QulacsClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.QulacsClient.algo) | The algorithm class used by this client. | | [`parameters`](#amplify.QulacsClient.parameters) | Algorithm parameters instance. | **`__init__(algo: type[AlgoType]) → None`** Initialize a QuantumBaseClient. **パラメータ:** **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use. Must conform to the [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) protocol. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the Qulacs package version. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). --- # RigettiClient **`class RigettiClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on Rigetti hardware via Amazon Braket. Connects to Rigetti superconducting devices through the Amazon Braket service and runs circuits on the specified device. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.RigettiClient.__init__) | Initialize a RigettiClient. | | [`solve`](#amplify.RigettiClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.RigettiClient.version) | Return the backend version string. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.RigettiClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.RigettiClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.RigettiClient.device) | Name of the target Rigetti device. | | [`provider`](#amplify.RigettiClient.provider) | Provider used to connect to the Rigetti device. | | [`parameters`](#amplify.RigettiClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], device: str = 'Ankaa3', provider: AwsSession | None = None, ) → None`** Initialize a RigettiClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Name or ARN of the Rigetti device. Defaults to the first non-underscore member of `braket.devices.Devices.Rigetti`. * **provider** (*AwsSession | None*) -- Provider used to connect to the Rigetti device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the backend version string. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: str`** Name of the target Rigetti device. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property provider: AwsSession | None`** Provider used to connect to the Rigetti device. Currently only Braket connection is supported; set to an `braket.aws.AwsSession` to configure credentials. Set to None to clear configured credentials. --- # QUDORAClient **`class QUDORAClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, `_QudoraJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on QUDORA hardware. Connects to the QUDORA platform using an API token and runs circuits on the specified device. Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QUDORAClient.__init__) | Initialize a QUDORAClient. | | [`solve`](#amplify.QUDORAClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.QUDORAClient.version) | Return the installed `qudora_sdk` package version. | **Attributes** | | | | --- | --- | | [`acceptable_degrees`](#amplify.QUDORAClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.QUDORAClient.algo) | The algorithm class used by this client. | | [`device`](#amplify.QUDORAClient.device) | Name of the target QUDORA device. | | [`device_settings`](#amplify.QUDORAClient.device_settings) | Device-specific settings forwarded to the QUDORA backend on each job submission. | | [`qiskit_pass_manager`](#amplify.QUDORAClient.qiskit_pass_manager) | Qiskit transpilation pass manager. | | [`token`](#amplify.QUDORAClient.token) | QUDORA API token used to authenticate, or `None` if not set. | | [`url`](#amplify.QUDORAClient.url) | QUDORA service URL, or `None` to use the default endpoint. | | [`parameters`](#amplify.QUDORAClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], token: str | None = None, url: str | None = None, device: str = 'Qamelion', qiskit_pass_manager: PassManager | EllipsisType | None = Ellipsis, device_settings: dict | None = None, ) → None`** Initialize a QUDORAClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- QUDORA API token. Required to access the service. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- QUDORA service URL. If `None`, the default endpoint is selected automatically based on the token prefix. * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Name of the QUDORA device. Defaults to `"Qamelion"`. * **qiskit_pass_manager** (*PassManager | EllipsisType | None*) -- Custom Qiskit transpilation pass manager. If `...` (default), a preset pass manager is generated automatically. Pass `None` to skip transpilation. * **device_settings** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *| None*) -- Device-specific settings forwarded to the QUDORA backend on each job submission. **`solve(objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the installed `qudora_sdk` package version. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property device: str`** Name of the target QUDORA device. **`property device_settings: dict | None`** Device-specific settings forwarded to the QUDORA backend on each job submission. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`property qiskit_pass_manager: PassManager | EllipsisType | None`** Qiskit transpilation pass manager. `...` (default) generates a preset pass manager automatically; `None` skips transpilation. **`property token: str | None`** QUDORA API token used to authenticate, or `None` if not set. **`property url: str | None`** QUDORA service URL, or `None` to use the default endpoint. --- # OqtopusClient **`class OqtopusClient`** ベースクラス: [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, `OqtopusJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit)] Client that executes quantum circuits on OQTOPUS Cloud. Authenticates with the OQTOPUS platform using an `OqtopusConfig` instance passed as [`provider`](#amplify.OqtopusClient.provider) when set. Otherwise, falls back to [`url`](#amplify.OqtopusClient.url)/ [`token`](#amplify.OqtopusClient.token) (and an optional [`proxy`](#amplify.OqtopusClient.proxy)) when both are set. If both [`url`](#amplify.OqtopusClient.url) and [`token`](#amplify.OqtopusClient.token) are unset, falls back to whatever `quri-parts-oqtopus` resolves by default (see `OqtopusSamplingBackend`). Accepts any algorithm conforming to [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) via the *algo* parameter. **Methods** | | | | --- | --- | | [`__init__`](#amplify.OqtopusClient.__init__) | Initialize an OqtopusClient. | | [`solve`](#amplify.OqtopusClient.solve) | Call the solver service to solve the given optimization problem. | | [`version`](#amplify.OqtopusClient.version) | Return the installed `quri-parts-oqtopus` package version. | **Attributes** | | | | --- | --- | | [`provider`](#amplify.OqtopusClient.provider) | `OqtopusConfig` used to authenticate with the OQTOPUS service. | | [`proxy`](#amplify.OqtopusClient.proxy) | Proxy server URL. | | [`token`](#amplify.OqtopusClient.token) | OQTOPUS API token. | | [`url`](#amplify.OqtopusClient.url) | OQTOPUS service URL. | | [`acceptable_degrees`](#amplify.OqtopusClient.acceptable_degrees) | Polynomial degrees accepted by the algorithm for the objective and constraints. | | [`algo`](#amplify.OqtopusClient.algo) | The algorithm class used by this client. | | [`description`](#amplify.OqtopusClient.description) | Description to assign to submitted OQTOPUS jobs. | | [`device`](#amplify.OqtopusClient.device) | Name of the target OQTOPUS device, or `None` to select automatically. | | [`job_type`](#amplify.OqtopusClient.job_type) | Job type forwarded to OQTOPUS. | | [`mitigation_info`](#amplify.OqtopusClient.mitigation_info) | Error-mitigation information forwarded to OQTOPUS. | | [`name`](#amplify.OqtopusClient.name) | Name to assign to submitted OQTOPUS jobs. | | [`qiskit_pass_manager`](#amplify.OqtopusClient.qiskit_pass_manager) | Qiskit transpilation pass manager. | | [`simulator_info`](#amplify.OqtopusClient.simulator_info) | Simulator information forwarded to OQTOPUS. | | [`transpiler_info`](#amplify.OqtopusClient.transpiler_info) | Transpiler information forwarded to OQTOPUS. | | [`parameters`](#amplify.OqtopusClient.parameters) | Algorithm parameters instance. | **`__init__( algo: type[AlgoType], token: str | None = None, url: str | None = None, proxy: str | None = None, provider: OqtopusConfig | None = None, device: str | None = None, qiskit_pass_manager: PassManager | EllipsisType | None = Ellipsis, name: str | None = None, description: str | None = None, transpiler_info: dict | None = None, simulator_info: dict | None = None, mitigation_info: dict | None = None, job_type: str | None = None, ) → None`** Initialize an OqtopusClient. **パラメータ:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) -- The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). * **token** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- OQTOPUS API token. Used together with *url* when *provider* is not given. * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- OQTOPUS service URL. Used together with *token* when *provider* is not given. * **proxy** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Proxy server URL. Used when *provider* is not given. * **provider** (*OqtopusConfig | None*) -- `OqtopusConfig` used to authenticate with the OQTOPUS service. Takes precedence over *token*/*url*/*proxy* when given. When `None`, falls back to *token*/*url*/*proxy* if both *token* and *url* are set; if both are unset, falls back to whatever `quri-parts-oqtopus` resolves by default (see `OqtopusSamplingBackend`). * **device** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Name of the target OQTOPUS device. If `None`, the first available device is selected automatically. * **qiskit_pass_manager** (*PassManager | EllipsisType | None*) -- Custom Qiskit transpilation pass manager. If `...` (default), a preset pass manager is generated automatically. Pass `None` to skip transpilation. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Name to assign to submitted OQTOPUS jobs. * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Description to assign to submitted OQTOPUS jobs. * **transpiler_info** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *| None*) -- Transpiler information forwarded to OQTOPUS. * **simulator_info** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *| None*) -- Simulator information forwarded to OQTOPUS. * **mitigation_info** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *| None*) -- Error-mitigation information forwarded to OQTOPUS. * **job_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *| None*) -- Job type forwarded to OQTOPUS. **`solve( objective: Poly | Matrix, constraints: ConstraintList | None, dry_run: bool = False, ) → CustomClientResultProtocol | None`** Call the solver service to solve the given optimization problem. **パラメータ:** * **objective** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) -- The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) *| None*) -- Constraints for the problem. If `None`, no constraints are applied. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`version() → str`** Return the installed `quri-parts-oqtopus` package version. **`property acceptable_degrees: AcceptableDegrees`** Polynomial degrees accepted by the algorithm for the objective and constraints. **`property algo: type[AlgoType]`** The algorithm class used by this client. **`property description: str | None`** Description to assign to submitted OQTOPUS jobs. **`property device: str | None`** Name of the target OQTOPUS device, or `None` to select automatically. **`property job_type: str | None`** Job type forwarded to OQTOPUS. **`property mitigation_info: dict | None`** Error-mitigation information forwarded to OQTOPUS. **`property name: str | None`** Name to assign to submitted OQTOPUS jobs. **`parameters`** Algorithm parameters instance. The concrete type depends on the algorithm; for [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). **`provider: OqtopusConfig | None`** `OqtopusConfig` used to authenticate with the OQTOPUS service. **`proxy: str | None`** Proxy server URL. Ignored when [`provider`](#amplify.OqtopusClient.provider) is set. **`property qiskit_pass_manager: PassManager | EllipsisType | None`** Qiskit transpilation pass manager. `...` (default) generates a preset pass manager automatically; `None` skips transpilation. **`property simulator_info: dict | None`** Simulator information forwarded to OQTOPUS. **`token: str | None`** OQTOPUS API token. Ignored when [`provider`](#amplify.OqtopusClient.provider) is set. **`property transpiler_info: dict | None`** Transpiler information forwarded to OQTOPUS. **`url: str | None`** OQTOPUS service URL. Ignored when [`provider`](#amplify.OqtopusClient.provider) is set. --- # Algorithm ## QAOA | | | | --- | --- | | [`QAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) | Quantum Approximate Optimization Algorithm (QAOA). | | [`QAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) | Selects the QAOA circuit construction strategy. | | [`QAOAResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAResult.md#amplify.QAOAResult) | Raw result produced by a single QAOA run. | | [`QAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) | Total timing breakdown for a QAOA run. | | [`QAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem) | Record of a single objective function evaluation during QAOA optimization. | ## RQAOA | | | | --- | --- | | [`RQAOA`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) | Recursive Quantum Approximate Optimization Algorithm (RQAOA). | | [`RQAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) | Selects the QAOA circuit construction strategy used within each RQAOA iteration. | | [`RQAOAResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAResult.md#amplify.RQAOAResult) | Raw result produced by a single RQAOA run. | | [`RQAOADurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) | Total timing breakdown for an RQAOA run. | | [`RQAOAHistoryItem`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem) | Record of a single iteration during RQAOA optimization. | | [`NormalElimination`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NormalElimination.md#amplify.NormalElimination) | Record of a variable explicitly eliminated during an RQAOA iteration. | | [`UnintentionalElimination`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.UnintentionalElimination.md#amplify.UnintentionalElimination) | Record of a variable eliminated as a side effect of another variable's elimination. | ## Common | | | | --- | --- | | [`QuantumAlgoProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md#amplify.QuantumAlgoProtocol) | Protocol for quantum optimization algorithms. | --- # QAOA **`class QAOA`** Quantum Approximate Optimization Algorithm (QAOA). A variational quantum algorithm that alternates between a cost Hamiltonian and a mixer Hamiltonian to find approximate solutions to combinatorial optimization problems encoded as Ising models. Pass this class to any [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient) subclass to run QAOA on the corresponding backend. **Methods** | | | | --- | --- | | [`acceptable_degrees`](#amplify.QAOA.acceptable_degrees) | Return the polynomial degrees accepted by the selected QAOA variant. | | [`run`](#amplify.QAOA.run) | Run QAOA on the given optimization model. | **`class Parameters`** Configuration parameters for a QAOA run. **`__eq__(other)`** Return self==value. **`__init__(reps: int = 10, shots: int = 1024, alpha: float = 1.0, qaoa_type: QAOAType | tuple[type[QAOAImplProtocol], AcceptableDegrees] = QAOAType.AUTO, minimize: MinimizeProtocol = ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'alpha': Field(name='alpha',type='float',default=1.0,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'minimize': Field(name='minimize',type='MinimizeProtocol',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'qaoa_type': Field(name='qaoa_type',type='QAOAType | tuple[type[QAOAImplProtocol], AcceptableDegrees]',default=, )>,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'reps': Field(name='reps',type='int',default=10,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'shots': Field(name='shots',type='int',default=1024,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('reps', 'shots', 'alpha', 'qaoa_type', 'minimize')`** **`alpha: float = 1.0`** The confidence level alpha for the objective function; that is, the fraction of the lowest-energy measurement outcomes to average. Must be in the range (0.0, 1.0]. A value of 1.0 corresponds to the standard expected value. **`minimize: MinimizeProtocol`** Classical optimizer used to tune the variational circuit parameters. Defaults to [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) with the COBYLA method. **`qaoa_type: QAOAType | tuple[type[QAOAImplProtocol], AcceptableDegrees] = (, )`** QAOA implementation to use. Either a [`QAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) value for the built-in strategies, or a custom class implementing the `QAOAImplProtocol` interface. **`reps: int = 10`** Number of QAOA layers (circuit depth *p*). Increasing this value may improve solution quality at the cost of a deeper circuit. > Must be greater than or equal to 0. **`shots: int = 1024`** Number of measurement shots per circuit evaluation. Must be greater than or equal to 0. **`class Result`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Result of a QAOA run. **`__init__(result: QAOAResult[SamplingMeta_co]) → None`** **`durations: QAOADurations`** Total timing breakdown for the entire QAOA run. **`history: Sequence[QAOAHistoryItem[SamplingMeta_co]]`** Per-evaluation records accumulated during classical optimization, in the order they were evaluated. **`num_execution: int`** Number of objective function evaluations performed during classical optimization. **`optimized_cost: float`** Best (lowest) cost value found. **`optimized_counts: IsingSeqFreqList`** Measurement results from the circuit evaluated at [`optimized_parameters`](#amplify.QAOA.Result.optimized_parameters), as a list of `(spin_sequence, frequency)` pairs. **`optimized_parameters: tuple[float, ...]`** Circuit parameter values that produced the best cost. **`static acceptable_degrees(parameters: Parameters) → AcceptableDegrees`** Return the polynomial degrees accepted by the selected QAOA variant. **パラメータ:** **parameters** ([*Parameters*](#amplify.QAOA.Parameters)) -- QAOA configuration from which the [`qaoa_type`](#amplify.QAOA.Parameters.qaoa_type) is read. **戻り値:** The degree constraints for the objective polynomial, determined by the chosen [`QAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) or custom implementation tuple. **戻り値の型:** [*AcceptableDegrees*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) **`static run( sampler: SamplerProtocol[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz], model: Model, parameters: Parameters, dry_run: Literal[False] = False, ) → Result[SamplingMeta_co]`** **`static run( sampler: SamplerProtocol[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz], model: Model, parameters: Parameters, dry_run: Literal[True], ) → None`** Run QAOA on the given optimization model. **パラメータ:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol)*[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz]*) -- Backend sampler that executes quantum circuits and returns measurement results. * **model** ([*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) -- The optimization model containing the objective function and constraints. * **parameters** ([*Parameters*](#amplify.QAOA.Parameters)) -- QAOA configuration (circuit depth, shots, optimizer, etc.). * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The QAOA result, or `None` if *dry_run* is `True`. **戻り値の型:** [*Result*](#amplify.QAOA.Result)[SamplingMeta_co] | *None* --- # QAOAType **`class QAOAType`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Selects the QAOA circuit construction strategy. Pass this as [`QAOA.Parameters.qaoa_type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.qaoa_type) to control which implementation is used when building the QAOA ansatz. **Attributes** | | | | --- | --- | | [`AUTO`](#amplify.QAOAType.AUTO) | Automatically choose the best implementation based on the problem structure. | | [`AUTO_QUADRATIC`](#amplify.QAOAType.AUTO_QUADRATIC) | Like [`AUTO`](#amplify.QAOAType.AUTO) but restricts the objective to quadratic form. | | [`ORIGINAL`](#amplify.QAOAType.ORIGINAL) | Standard QAOA for unconstrained Ising problems. | | [`ORIGINAL_QUADRATIC`](#amplify.QAOAType.ORIGINAL_QUADRATIC) | Like [`ORIGINAL`](#amplify.QAOAType.ORIGINAL) but restricts the objective to quadratic form. | | [`NHOT`](#amplify.QAOAType.NHOT) | QAOA that preserves equal to constraints throughout the circuit, keeping the quantum state in the feasible subspace. | | [`NHOT_QUADRATIC`](#amplify.QAOAType.NHOT_QUADRATIC) | Like [`NHOT`](#amplify.QAOAType.NHOT) but restricts the objective to quadratic form. | **`AUTO = (, )`** Automatically choose the best implementation based on the problem structure. Selects [`NHOT`](#amplify.QAOAType.NHOT) when the problem has disjoint equal to constraints, otherwise falls back to [`ORIGINAL`](#amplify.QAOAType.ORIGINAL). **`AUTO_QUADRATIC = (, )`** Like [`AUTO`](#amplify.QAOAType.AUTO) but restricts the objective to quadratic form. **`NHOT = (, )`** QAOA that preserves equal to constraints throughout the circuit, keeping the quantum state in the feasible subspace. **`NHOT_QUADRATIC = (, )`** Like [`NHOT`](#amplify.QAOAType.NHOT) but restricts the objective to quadratic form. **`ORIGINAL = (, )`** Standard QAOA for unconstrained Ising problems. **`ORIGINAL_QUADRATIC = (, )`** Like [`ORIGINAL`](#amplify.QAOAType.ORIGINAL) but restricts the objective to quadratic form. --- # QAOAResult **`class QAOAResult`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Raw result produced by a single QAOA run. Returned by `QAOA.run` and exposed through [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result). **Methods** | | | | --- | --- | | [`__init__`](#amplify.QAOAResult.__init__) | | **Attributes** | | | | --- | --- | | [`durations`](#amplify.QAOAResult.durations) | Total timing breakdown for the entire QAOA run. | | [`num_execution`](#amplify.QAOAResult.num_execution) | Number of objective function evaluations performed during classical optimization. | | [`optimized_cost`](#amplify.QAOAResult.optimized_cost) | Best (lowest) objective value found. | | [`optimized_parameters`](#amplify.QAOAResult.optimized_parameters) | Circuit parameter values that produced the best objective. | | [`optimized_counts`](#amplify.QAOAResult.optimized_counts) | Measurement results from the circuit evaluated at [`optimized_parameters`](#amplify.QAOAResult.optimized_parameters), as a list of `(spin_sequence, frequency)` pairs. | | [`qaoa_impl`](#amplify.QAOAResult.qaoa_impl) | QAOA implementation instance that was used. | | [`history`](#amplify.QAOAResult.history) | Per-evaluation records accumulated during classical optimization, in the order they were evaluated. | **`__eq__(other)`** Return self==value. **`__init__( durations: QAOADurations, num_execution: int, optimized_cost: float, optimized_parameters: tuple[float, ...], optimized_counts: IsingSeqFreqList, qaoa_impl: QAOAImplProtocol, history: Sequence[QAOAHistoryItem[SamplingMeta_co]], ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'durations': Field(name='durations',type='QAOADurations',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'history': Field(name='history',type='Sequence[QAOAHistoryItem[SamplingMeta_co]]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'num_execution': Field(name='num_execution',type='int',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'optimized_cost': Field(name='optimized_cost',type='float',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'optimized_counts': Field(name='optimized_counts',type='IsingSeqFreqList',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'optimized_parameters': Field(name='optimized_parameters',type='tuple[float, ...]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'qaoa_impl': Field(name='qaoa_impl',type='QAOAImplProtocol',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('durations', 'num_execution', 'optimized_cost', 'optimized_parameters', 'optimized_counts', 'qaoa_impl', 'history')`** **`durations: QAOADurations`** Total timing breakdown for the entire QAOA run. **`history: Sequence[QAOAHistoryItem[SamplingMeta_co]]`** Per-evaluation records accumulated during classical optimization, in the order they were evaluated. **`num_execution: int`** Number of objective function evaluations performed during classical optimization. **`optimized_cost: float`** Best (lowest) objective value found. **`optimized_counts: IsingSeqFreqList`** Measurement results from the circuit evaluated at [`optimized_parameters`](#amplify.QAOAResult.optimized_parameters), as a list of `(spin_sequence, frequency)` pairs. **`optimized_parameters: tuple[float, ...]`** Circuit parameter values that produced the best objective. **`qaoa_impl: QAOAImplProtocol`** QAOA implementation instance that was used. --- # QAOADurations **`class QAOADurations`** Total timing breakdown for a QAOA run. All durations accumulate over every circuit evaluation performed during the classical optimization loop. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QAOADurations.__init__) | | **Attributes** | | | | --- | --- | | [`classical_processing_time`](#amplify.QAOADurations.classical_processing_time) | Time spent in classical optimization, excluding quantum circuit execution (`total_time - total_response_time`). | | [`total_time`](#amplify.QAOADurations.total_time) | Total wall-clock time from the start to the end of the QAOA run, including both quantum execution and classical optimization overhead. | | [`total_response_time`](#amplify.QAOADurations.total_response_time) | Sum of response times across all quantum circuit evaluations, where response time is the round-trip time from circuit submission to result receipt. | | [`total_execution_time`](#amplify.QAOADurations.total_execution_time) | Sum of execution times across all quantum circuit evaluations, where execution time is the time the quantum hardware (or simulator) was actively running. | **`__eq__(other)`** Return self==value. **`__init__( total_time: ~datetime.timedelta = , total_response_time: ~datetime.timedelta = , total_execution_time: ~datetime.timedelta = , ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'total_execution_time': Field(name='total_execution_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'total_response_time': Field(name='total_response_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'total_time': Field(name='total_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('total_time', 'total_response_time', 'total_execution_time')`** **`property classical_processing_time: timedelta`** Time spent in classical optimization, excluding quantum circuit execution (`total_time - total_response_time`). **`total_execution_time: timedelta`** Sum of execution times across all quantum circuit evaluations, where execution time is the time the quantum hardware (or simulator) was actively running. **`total_response_time: timedelta`** Sum of response times across all quantum circuit evaluations, where response time is the round-trip time from circuit submission to result receipt. **`total_time: timedelta`** Total wall-clock time from the start to the end of the QAOA run, including both quantum execution and classical optimization overhead. --- # QAOAHistoryItem **`class QAOAHistoryItem`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Record of a single objective function evaluation during QAOA optimization. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QAOAHistoryItem.__init__) | | **Attributes** | | | | --- | --- | | [`timestamp`](#amplify.QAOAHistoryItem.timestamp) | Elapsed time from the start of optimization to when this evaluation completed. | | [`parameters`](#amplify.QAOAHistoryItem.parameters) | Circuit parameter values used in this evaluation. | | [`objective`](#amplify.QAOAHistoryItem.objective) | Objective value computed from the measurement results of this evaluation. | | [`counts`](#amplify.QAOAHistoryItem.counts) | Measurement results as a list of `(spin_sequence, frequency)` pairs. | | [`sampling_durations`](#amplify.QAOAHistoryItem.sampling_durations) | Per-call timing breakdown for the quantum circuit execution. | | [`sampling_meta`](#amplify.QAOAHistoryItem.sampling_meta) | Backend-specific metadata returned by the quantum job (e.g., job ID and circuit for Qiskit, or simulated circuit for Qulacs). | **`__eq__(other)`** Return self==value. **`__init__( timestamp: timedelta, parameters: Sequence[float], objective: float, counts: IsingSeqFreqList, sampling_durations: SamplingDurations, sampling_meta: SamplingMeta_co, ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'counts': Field(name='counts',type='IsingSeqFreqList',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'objective': Field(name='objective',type='float',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'parameters': Field(name='parameters',type='Sequence[float]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'sampling_durations': Field(name='sampling_durations',type='SamplingDurations',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'sampling_meta': Field(name='sampling_meta',type='SamplingMeta_co',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'timestamp': Field(name='timestamp',type='timedelta',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('timestamp', 'parameters', 'objective', 'counts', 'sampling_durations', 'sampling_meta')`** **`counts: IsingSeqFreqList`** Measurement results as a list of `(spin_sequence, frequency)` pairs. **`objective: float`** Objective value computed from the measurement results of this evaluation. **`parameters: Sequence[float]`** Circuit parameter values used in this evaluation. **`sampling_durations: SamplingDurations`** Per-call timing breakdown for the quantum circuit execution. **`sampling_meta: SamplingMeta_co`** Backend-specific metadata returned by the quantum job (e.g., job ID and circuit for Qiskit, or simulated circuit for Qulacs). **`timestamp: timedelta`** Elapsed time from the start of optimization to when this evaluation completed. --- # RQAOA **`class RQAOA`** Recursive Quantum Approximate Optimization Algorithm (RQAOA). A recursive variant of QAOA that iteratively reduces the problem size by eliminating variables based on correlation information obtained from QAOA solutions, until the problem is small enough to be solved directly. All constraints are converted to penalty terms in the objective. Pass this class to any [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient) subclass to run RQAOA on the corresponding backend. **Methods** | | | | --- | --- | | [`acceptable_degrees`](#amplify.RQAOA.acceptable_degrees) | Return the polynomial degrees accepted by the selected QAOA variant. | | [`run`](#amplify.RQAOA.run) | Run RQAOA on the given optimization model. | **`class Parameters`** Configuration parameters for an RQAOA run. **`__eq__(other)`** Return self==value. **`__init__(reps: int = 10, shots: int = 1024, alpha: float = 1.0, min_size: int = 2, max_degree: int | None = None, min_corr: float = 0, qaoa_type: RQAOAType | Literal[QAOAType.ORIGINAL, QAOAType.ORIGINAL_QUADRATIC] | tuple[type[QAOAImplProtocol], AcceptableDegrees] = RQAOAType.ORIGINAL, minimize: MinimizeProtocol = ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'alpha': Field(name='alpha',type='float',default=1.0,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'max_degree': Field(name='max_degree',type='int | None',default=None,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'min_corr': Field(name='min_corr',type='float',default=0,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'min_size': Field(name='min_size',type='int',default=2,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'minimize': Field(name='minimize',type='MinimizeProtocol',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'qaoa_type': Field(name='qaoa_type',type='RQAOAType | Literal[QAOAType.ORIGINAL, QAOAType.ORIGINAL_QUADRATIC] | tuple[type[QAOAImplProtocol], AcceptableDegrees]',default=, )>,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'reps': Field(name='reps',type='int',default=10,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'shots': Field(name='shots',type='int',default=1024,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('reps', 'shots', 'alpha', 'min_size', 'max_degree', 'min_corr', 'qaoa_type', 'minimize')`** **`alpha: float = 1.0`** The confidence level alpha for the objective function; that is, the fraction of the lowest-energy measurement outcomes to average. Must be in the range (0.0, 1.0]. A value of 1.0 corresponds to the standard expected value. **`max_degree: int | None = None`** Maximum polynomial degree to retain when reducing the problem. `None` means no degree limit is applied. Must be greater than or equal to 0. **`min_corr: float = 0`** Minimum absolute correlation threshold for selecting a term to eliminate. Only terms whose measured correlation exceeds this value are considered for elimination. When set to 0 (default), any non-zero correlation is accepted. Must be greater than or equal to 0. **`min_size: int = 2`** Minimum problem size at which recursion stops and the remaining sub-problem is solved by exhaustive enumeration. Must be greater than or equal to 0. **`minimize: MinimizeProtocol`** Classical optimizer used to tune the variational circuit parameters. Defaults to [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) with the COBYLA method. **`qaoa_type: RQAOAType | Literal[QAOAType.ORIGINAL, QAOAType.ORIGINAL_QUADRATIC] | tuple[type[QAOAImplProtocol], AcceptableDegrees] = (, )`** QAOA implementation to use within each iteration. Either a [`RQAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) value for the built-in strategies, or a custom `(impl_class, acceptable_degrees)` tuple. **`reps: int = 10`** Number of QAOA layers (circuit depth *p*) used in each RQAOA iteration. Increasing this value may improve solution quality at the cost of a deeper circuit. Must be greater than or equal to 0. **`shots: int = 1024`** Number of measurement shots per circuit evaluation. Must be greater than or equal to 0. **`class Result`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Result of an RQAOA run. **`__init__(result: RQAOAResult[SamplingMeta_co]) → None`** **`durations`** Total timing breakdown for the entire RQAOA run. **`history`** Per-iteration records accumulated during the RQAOA optimization process, in the order they were performed. **`num_execution`** Number of objective function evaluations performed during classical optimization. **`optimized_objective`** Best objective value found for the reduced problem. **`optimized_solution`** Best solution found, as a tuple of spin values. **`static acceptable_degrees(parameters: Parameters) → AcceptableDegrees`** Return the polynomial degrees accepted by the selected QAOA variant. **パラメータ:** **parameters** ([*Parameters*](#amplify.RQAOA.Parameters)) -- RQAOA configuration from which the [`qaoa_type`](#amplify.RQAOA.Parameters.qaoa_type) is read. **戻り値:** The degree constraints for the objective polynomial, determined by the chosen [`RQAOAType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) or custom implementation tuple. **戻り値の型:** [*AcceptableDegrees*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) **`static run( sampler: SamplerProtocol[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz], model: Model, parameters: Parameters, dry_run: Literal[False] = False, ) → Result[SamplingMeta_co]`** **`static run( sampler: SamplerProtocol[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz], model: Model, parameters: Parameters, dry_run: Literal[True], ) → None`** Run RQAOA on the given optimization model. **パラメータ:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol)*[SamplingMeta_co, SupportsAnsatz | SupportsCAnsatz]*) -- Backend sampler that executes quantum circuits and returns measurement results. * **model** ([*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) -- The optimization model containing the objective function and constraints. * **parameters** ([*Parameters*](#amplify.RQAOA.Parameters)) -- RQAOA configuration (circuit depth, shots, optimizer, etc.). * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The RQAOA result, or `None` if *dry_run* is `True`. **戻り値の型:** [*Result*](#amplify.RQAOA.Result)[SamplingMeta_co] | *None* --- # RQAOAType **`class RQAOAType`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) Selects the QAOA circuit construction strategy used within each RQAOA iteration. Pass this as [`RQAOA.Parameters.qaoa_type`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.qaoa_type) to control which QAOA implementation is used when solving the reduced sub-problems. **Attributes** | | | | --- | --- | | [`ORIGINAL`](#amplify.RQAOAType.ORIGINAL) | Standard QAOA for unconstrained Ising problems. | | [`ORIGINAL_QUADRATIC`](#amplify.RQAOAType.ORIGINAL_QUADRATIC) | Like [`ORIGINAL`](#amplify.RQAOAType.ORIGINAL) but restricts the objective to quadratic form. | **`ORIGINAL = (, )`** Standard QAOA for unconstrained Ising problems. **`ORIGINAL_QUADRATIC = (, )`** Like [`ORIGINAL`](#amplify.RQAOAType.ORIGINAL) but restricts the objective to quadratic form. --- # RQAOAResult **`class RQAOAResult`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Raw result produced by a single RQAOA run. Returned by `RQAOA.run` and exposed through [`Result`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result). **Methods** | | | | --- | --- | | [`__init__`](#amplify.RQAOAResult.__init__) | | **Attributes** | | | | --- | --- | | [`durations`](#amplify.RQAOAResult.durations) | Total timing breakdown for the entire RQAOA run. | | [`num_execution`](#amplify.RQAOAResult.num_execution) | Number of objective function evaluations performed during classical optimization. | | [`optimized_objective`](#amplify.RQAOAResult.optimized_objective) | Best objective value found. | | [`optimized_solution`](#amplify.RQAOAResult.optimized_solution) | Best solution found, as a tuple of spin values. | | [`history`](#amplify.RQAOAResult.history) | Per-iteration records accumulated during the RQAOA optimization process, in the order they were performed. | **`__eq__(other)`** Return self==value. **`__init__( durations: RQAOADurations, num_execution: int, optimized_objective: float, optimized_solution: RQAOASolType, history: Sequence[RQAOAHistoryItem[SamplingMeta_co]], ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'durations': Field(name='durations',type='RQAOADurations',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'history': Field(name='history',type='Sequence[RQAOAHistoryItem[SamplingMeta_co]]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'num_execution': Field(name='num_execution',type='int',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'optimized_objective': Field(name='optimized_objective',type='float',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'optimized_solution': Field(name='optimized_solution',type='RQAOASolType',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('durations', 'num_execution', 'optimized_objective', 'optimized_solution', 'history')`** **`durations: RQAOADurations`** Total timing breakdown for the entire RQAOA run. **`history: Sequence[RQAOAHistoryItem[SamplingMeta_co]]`** Per-iteration records accumulated during the RQAOA optimization process, in the order they were performed. **`num_execution: int`** Number of objective function evaluations performed during classical optimization. **`optimized_objective: float`** Best objective value found. **`optimized_solution: RQAOASolType`** Best solution found, as a tuple of spin values. --- # RQAOADurations **`class RQAOADurations`** Total timing breakdown for an RQAOA run. All durations accumulate over the full recursive optimization process. **Methods** | | | | --- | --- | | [`__init__`](#amplify.RQAOADurations.__init__) | | **Attributes** | | | | --- | --- | | [`classical_processing_time`](#amplify.RQAOADurations.classical_processing_time) | Time spent in classical optimization, excluding quantum circuit execution (`total_time - total_response_time`). | | [`total_time`](#amplify.RQAOADurations.total_time) | Total wall-clock time elapsed during the entire RQAOA optimization process, including both quantum and classical computations. | | [`total_response_time`](#amplify.RQAOADurations.total_response_time) | Sum of response times across all quantum circuit evaluations, where response time is the round-trip time from circuit submission to result receipt. | | [`total_execution_time`](#amplify.RQAOADurations.total_execution_time) | Sum of execution times across all quantum circuit evaluations, where execution time is the time the quantum hardware (or simulator) was actively running. | **`__eq__(other)`** Return self==value. **`__init__( total_time: ~datetime.timedelta = , total_response_time: ~datetime.timedelta = , total_execution_time: ~datetime.timedelta = , ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'total_execution_time': Field(name='total_execution_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'total_response_time': Field(name='total_response_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'total_time': Field(name='total_time',type='timedelta',default=,default_factory=>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('total_time', 'total_response_time', 'total_execution_time')`** **`property classical_processing_time: timedelta`** Time spent in classical optimization, excluding quantum circuit execution (`total_time - total_response_time`). **`total_execution_time: timedelta`** Sum of execution times across all quantum circuit evaluations, where execution time is the time the quantum hardware (or simulator) was actively running. **`total_response_time: timedelta`** Sum of response times across all quantum circuit evaluations, where response time is the round-trip time from circuit submission to result receipt. **`total_time: timedelta`** Total wall-clock time elapsed during the entire RQAOA optimization process, including both quantum and classical computations. --- # RQAOAHistoryItem **`class RQAOAHistoryItem`** ベースクラス: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`] Record of a single iteration during RQAOA optimization. **Methods** | | | | --- | --- | | [`__init__`](#amplify.RQAOAHistoryItem.__init__) | | **Attributes** | | | | --- | --- | | [`timestamp`](#amplify.RQAOAHistoryItem.timestamp) | Elapsed time from the start of optimization to when this iteration completed. | | [`model`](#amplify.RQAOAHistoryItem.model) | The objective function at this iteration. | | [`qaoa_result`](#amplify.RQAOAHistoryItem.qaoa_result) | The result of the QAOA evaluation performed at this iteration, if any. | | [`elimination_info`](#amplify.RQAOAHistoryItem.elimination_info) | Information about the variable elimination performed at this iteration, if any. | **`__eq__(other)`** Return self==value. **`__init__( timestamp: timedelta, model: Poly, qaoa_result: QAOAResult[SamplingMeta_co] | None, elimination_info: EliminationInfo | None, ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'elimination_info': Field(name='elimination_info',type='EliminationInfo | None',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'model': Field(name='model',type='Poly',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'qaoa_result': Field(name='qaoa_result',type='QAOAResult[SamplingMeta_co] | None',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'timestamp': Field(name='timestamp',type='timedelta',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('timestamp', 'model', 'qaoa_result', 'elimination_info')`** **`elimination_info: EliminationInfo | None`** Information about the variable elimination performed at this iteration, if any. **`model: Poly`** The objective function at this iteration. **`qaoa_result: QAOAResult[SamplingMeta_co] | None`** The result of the QAOA evaluation performed at this iteration, if any. **`timestamp: timedelta`** Elapsed time from the start of optimization to when this iteration completed. --- # NormalElimination **`class NormalElimination`** Record of a variable explicitly eliminated during an RQAOA iteration. **Methods** | | | | --- | --- | | [`__init__`](#amplify.NormalElimination.__init__) | | **Attributes** | | | | --- | --- | | [`index`](#amplify.NormalElimination.index) | The index of the variable selected for elimination. | | [`term`](#amplify.NormalElimination.term) | The term selected for elimination, represented as a tuple of variable indices. | | [`sign`](#amplify.NormalElimination.sign) | The sign of the selected term, either +1 or -1. | **`__eq__(other)`** Return self==value. **`__init__(index: int, term: tuple[int, ...], sign: Literal[1, -1]) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'index': Field(name='index',type='int',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'sign': Field(name='sign',type='Literal[1, -1]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'term': Field(name='term',type='tuple[int, ...]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('index', 'term', 'sign')`** **`index: int`** The index of the variable selected for elimination. **`sign: Literal[1, -1]`** The sign of the selected term, either +1 or -1. **`term: tuple[int, ...]`** The term selected for elimination, represented as a tuple of variable indices. --- # UnintentionalElimination **`class UnintentionalElimination`** Record of a variable eliminated as a side effect of another variable's elimination. **Methods** | | | | --- | --- | | [`__init__`](#amplify.UnintentionalElimination.__init__) | | **Attributes** | | | | --- | --- | | [`index`](#amplify.UnintentionalElimination.index) | The index of the variable that was unintentionally eliminated due to the elimination of another variable. | | [`sign`](#amplify.UnintentionalElimination.sign) | The sign of the term that caused the unintentional elimination, randomly chosen from either +1 or -1. | **`__eq__(other)`** Return self==value. **`__init__(index: int, sign: Literal[1, -1]) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'index': Field(name='index',type='int',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'sign': Field(name='sign',type='Literal[1, -1]',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)`** **`__hash__ = None`** **`__match_args__ = ('index', 'sign')`** **`index: int`** The index of the variable that was unintentionally eliminated due to the elimination of another variable. **`sign: Literal[1, -1]`** The sign of the term that caused the unintentional elimination, randomly chosen from either +1 or -1. --- # QuantumAlgoProtocol **`class QuantumAlgoProtocol`** ベースクラス: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol) Protocol for quantum optimization algorithms. Implement this protocol to define a custom algorithm compatible with any [`QuantumBaseClient`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient) subclass. A conforming class must declare [`acceptable_degrees`](#amplify.QuantumAlgoProtocol.acceptable_degrees), a [`Parameters`](#amplify.QuantumAlgoProtocol.Parameters) class, and a static [`run()`](#amplify.QuantumAlgoProtocol.run) method. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QuantumAlgoProtocol.__init__) | | | [`run`](#amplify.QuantumAlgoProtocol.run) | Run the algorithm on the given model. | **Attributes** | | | | --- | --- | | [`Parameters`](#amplify.QuantumAlgoProtocol.Parameters) | Configuration class for the algorithm. | | [`acceptable_degrees`](#amplify.QuantumAlgoProtocol.acceptable_degrees) | Polynomial degrees accepted by the algorithm's objective function. | **`__init__(*args, **kwargs)`** **`static run( sampler: SamplerProtocol[SamplingMeta_co, Any], model: Model, parameters: Any, dry_run: Literal[False], ) → CustomClientResultProtocol`** **`static run( sampler: SamplerProtocol[SamplingMeta_co, Any], model: Model, parameters: Any, dry_run: Literal[True], ) → None`** Run the algorithm on the given model. **パラメータ:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol)*[SamplingMeta_co, Any]*) -- Backend sampler that executes quantum circuits. * **model** ([*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) -- The optimization model to solve. * **parameters** (*Any*) -- Algorithm-specific configuration (e.g., [`QAOA.Parameters`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters)). * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without executing circuits and return `None`. **戻り値:** The algorithm result, or `None` if *dry_run* is `True`. **戻り値の型:** CustomClientResultProtocol | *None* **`Parameters: Final[type]`** Configuration class for the algorithm. Instances are passed to [`run()`](#amplify.QuantumAlgoProtocol.run) and to [`acceptable_degrees`](#amplify.QuantumAlgoProtocol.acceptable_degrees) when it is a callable. **`acceptable_degrees: Final[AcceptableDegrees | Callable[[Any], AcceptableDegrees]]`** Polynomial degrees accepted by the algorithm's objective function. Either a static [`AcceptableDegrees`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) value, or a callable that takes a [`Parameters`](#amplify.QuantumAlgoProtocol.Parameters) instance and returns one. --- # Minimize | | | | --- | --- | | [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) | Classical optimizer for QAOA circuit parameters using [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). | | [`ScipyMinimizeOptions`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md#amplify.ScipyMinimizeOptions) | Optional keyword arguments for [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). | | [`ScipyMinimizeResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md#amplify.ScipyMinimizeResult) | Result of a [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) optimization run. | | [`NoOpMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) | Classical optimizer that evaluates the objective at a fixed set of parameters. | | [`NoOpMinimizeResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md#amplify.NoOpMinimizeResult) | Result of a [`NoOpMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) run. | | [`MinimizeProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol) | Protocol for classical optimizers used to tune QAOA circuit parameters. | | [`MinimizeResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md#amplify.MinimizeResult) | Protocol for the result of a classical minimization run. | --- # ScipyMinimize **`class ScipyMinimize`** Classical optimizer for QAOA circuit parameters using [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). Wraps SciPy's minimization routines to tune the variational parameters of the QAOA ansatz circuit. Assign an instance of this class to [`minimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) to use it (it is also the default). **Methods** | | | | --- | --- | | [`__init__`](#amplify.ScipyMinimize.__init__) | Initialize a ScipyMinimize optimizer. | **Attributes** | | | | --- | --- | | [`method`](#amplify.ScipyMinimize.method) | Optimization method passed to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). | | [`tol`](#amplify.ScipyMinimize.tol) | Tolerance for termination, passed as the `tol` argument to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). | | [`x0`](#amplify.ScipyMinimize.x0) | Initial parameter values. | | [`options`](#amplify.ScipyMinimize.options) | Additional options forwarded as the `options` argument to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize) (e.g., `{"maxiter": 500}`). | **`__call__( func: Callable[[list[float]], float], num_parameters: int, *, dry_run: bool = False, ) → ScipyMinimizeResult | None`** Run the SciPy minimization. **パラメータ:** * **func** (*Callable[[*[*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*]],* [*float*](https://docs.python.org/3/library/functions.html#float)*]*) -- Objective function that maps a list of circuit parameters to a scalar cost. * **num_parameters** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of variational parameters to optimize. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without running the optimizer and return `None`. **戻り値:** The optimization result, or `None` if *dry_run* is `True`. **戻り値の型:** [*ScipyMinimizeResult*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md#amplify.ScipyMinimizeResult) | *None* **`__init__( method: str = 'COBYLA', tol: float | None = None, x0: list[float] | None = None, options: ScipyMinimizeOptions | None = None, ) → None`** Initialize a ScipyMinimize optimizer. **パラメータ:** * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) -- Optimization method. Defaults to "COBYLA". * **tol** ([*float*](https://docs.python.org/3/library/functions.html#float) *| None*) -- Tolerance for termination. If `None`, the optimizer's default is used. * **x0** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*] | None*) -- Initial parameter values. Must have at least as many elements as the number of circuit parameters. If `None`, values are drawn uniformly at random from `[0, 1)`. * **options** ([*ScipyMinimizeOptions*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md#amplify.ScipyMinimizeOptions) *| None*) -- Additional options forwarded as the `options` argument to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize) (e.g., `{"maxiter": 500}`). **`method: str`** Optimization method passed to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). Defaults to `"COBYLA"`, which is derivative-free and well-suited for noisy quantum circuits. See the SciPy documentation for available methods. **`options: ScipyMinimizeOptions | None`** Additional options forwarded as the `options` argument to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize) (e.g., `{"maxiter": 500}`). **`tol: float | None`** Tolerance for termination, passed as the `tol` argument to [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). If `None`, the optimizer's default is used. **`x0: list[float] | None`** Initial parameter values. Must have at least as many elements as the number of circuit parameters. If `None`, values are drawn uniformly at random from `[0, 1)`. --- # ScipyMinimizeOptions **`class ScipyMinimizeOptions`** ベースクラス: `TypedDict` Optional keyword arguments for [`scipy.optimize.minimize()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize). Passed as the `options` argument to the optimizer. All keys are optional. **Methods** | | | | --- | --- | | [`__init__`](#amplify.ScipyMinimizeOptions.__init__) | | | [`clear`](#amplify.ScipyMinimizeOptions.clear) | | | [`copy`](#amplify.ScipyMinimizeOptions.copy) | | | [`fromkeys`](#amplify.ScipyMinimizeOptions.fromkeys) | Create a new dictionary with keys from iterable and values set to value. | | [`get`](#amplify.ScipyMinimizeOptions.get) | Return the value for key if key is in the dictionary, else default. | | [`items`](#amplify.ScipyMinimizeOptions.items) | | | [`keys`](#amplify.ScipyMinimizeOptions.keys) | | | [`pop`](#amplify.ScipyMinimizeOptions.pop) | If the key is not found, return the default if given; otherwise, raise a KeyError. | | [`popitem`](#amplify.ScipyMinimizeOptions.popitem) | Remove and return a (key, value) pair as a 2-tuple. | | [`setdefault`](#amplify.ScipyMinimizeOptions.setdefault) | Insert key with a value of default if key is not in the dictionary. | | [`update`](#amplify.ScipyMinimizeOptions.update) | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] | | [`values`](#amplify.ScipyMinimizeOptions.values) | | **Attributes** | | | | --- | --- | | [`disp`](#amplify.ScipyMinimizeOptions.disp) | If `True`, print convergence messages. | | [`maxiter`](#amplify.ScipyMinimizeOptions.maxiter) | Maximum number of iterations allowed. | **`__contains__(key, /)`** True if the dictionary has the specified key, else False. **`__delitem__(key, /)`** Delete self[key]. **`__eq__(value, /)`** Return self==value. **`__ge__(value, /)`** Return self>=value. **`__getattribute__(name, /)`** Return getattr(self, name). **`__getitem__()`** x.__getitem__(y) <==> x[y] **`__gt__(value, /)`** Return self>value. **`__init__(*args, **kwargs)`** **`__ior__(value, /)`** Return self|=value. **`__iter__()`** Implement iter(self). **`__le__(value, /)`** Return self<=value. **`__len__()`** Return len(self). **`__lt__(value, /)`** Return self **`__ne__(value, /)`** Return self!=value. **`__or__(value, /)`** Return self|value. **`__repr__()`** Return repr(self). **`__reversed__()`** Return a reverse iterator over the dict keys. **`__ror__(value, /)`** Return value|self. **`__setitem__(key, value, /)`** Set self[key] to value. **`__sizeof__() → size of D in memory, in bytes`** **`clear() → None. Remove all items from D.`** **`copy() → a shallow copy of D`** **`fromkeys(value=None, /)`** Create a new dictionary with keys from iterable and values set to value. **`get(key, default=None, /)`** Return the value for key if key is in the dictionary, else default. **`items() → a set-like object providing a view on D's items`** **`keys() → a set-like object providing a view on D's keys`** **`pop(k[, d]) → v, remove specified key and return the corresponding value.`** If the key is not found, return the default if given; otherwise, raise a KeyError. **`popitem()`** Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. **`setdefault(key, default=None, /)`** Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. **`update([E, ]**F) → None. Update D from dict/iterable E and F.`** If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] **`values() → an object providing a view on D's values`** **`__closed__ = None`** **`__extra_items__ = typing.Any`** **`__hash__ = None`** **`__mutable_keys__ = frozenset({'disp', 'maxiter'})`** **`__optional_keys__ = frozenset({'disp', 'maxiter'})`** **`__readonly_keys__ = frozenset({})`** **`__required_keys__ = frozenset({})`** **`__total__ = False`** **`disp: bool`** If `True`, print convergence messages. **`maxiter: int`** Maximum number of iterations allowed. --- # ScipyMinimizeResult **`class ScipyMinimizeResult`** Result of a [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) optimization run. **Methods** | | | | --- | --- | | [`__init__`](#amplify.ScipyMinimizeResult.__init__) | | **Attributes** | | | | --- | --- | | [`best_objective`](#amplify.ScipyMinimizeResult.best_objective) | Best (lowest) objective value found by the optimizer. | | [`best_parameters`](#amplify.ScipyMinimizeResult.best_parameters) | Circuit parameter values corresponding to the best objective. | **`__init__(res: Any) → None`** **`property best_objective: float`** Best (lowest) objective value found by the optimizer. **`property best_parameters: tuple[float, ...]`** Circuit parameter values corresponding to the best objective. --- # NoOpMinimize **`class NoOpMinimize`** Classical optimizer that evaluates the objective at a fixed set of parameters. This optimizer does not search for better parameters. It evaluates the objective function exactly once at the parameter values provided via `parameters`. Useful for benchmarking or reproducing results with known parameters. Assign an instance to [`minimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) to use it. **Methods** | | | | --- | --- | | [`__init__`](#amplify.NoOpMinimize.__init__) | Initialize a NoOpMinimize optimizer. | **Attributes** | | | | --- | --- | | [`parameters`](#amplify.NoOpMinimize.parameters) | The fixed circuit parameter values to evaluate. | **`__call__(func: Callable[[list[float]], float], num_parameters: int, *, dry_run: bool = False) → NoOpMinimizeResult | None`** Evaluate the objective at the fixed parameters. **パラメータ:** * **func** (*Callable[[*[*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*]],* [*float*](https://docs.python.org/3/library/functions.html#float)*]*) -- Objective function that maps a list of circuit parameters to a scalar cost. * **num_parameters** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Expected number of variational parameters. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, skip evaluation and return `None`. **戻り値:** The evaluation result, or `None` if *dry_run* is `True`. **戻り値の型:** [*NoOpMinimizeResult*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md#amplify.NoOpMinimizeResult) | *None* **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If `parameters` is `None` or has wrong length. **`__init__(parameters: Sequence[float] | None = None) → None`** Initialize a NoOpMinimize optimizer. **パラメータ:** **parameters** (*Sequence[*[*float*](https://docs.python.org/3/library/functions.html#float)*] | None*) -- Fixed circuit parameter values to evaluate. Must be provided before calling the optimizer; passing `None` defers the error to call time. **`parameters`** The fixed circuit parameter values to evaluate. Must be provided before calling the optimizer; passing `None` defers the error to call time. --- # NoOpMinimizeResult **`class NoOpMinimizeResult`** Result of a [`NoOpMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) run. **Methods** | | | | --- | --- | | [`__init__`](#amplify.NoOpMinimizeResult.__init__) | | **Attributes** | | | | --- | --- | | [`best_objective`](#amplify.NoOpMinimizeResult.best_objective) | The objective value computed from the fixed parameters. | | [`best_parameters`](#amplify.NoOpMinimizeResult.best_parameters) | The fixed circuit parameter values used for evaluation. | **`__init__(val: float, param: tuple[float, ...]) → None`** **`best_objective`** The objective value computed from the fixed parameters. **`best_parameters`** The fixed circuit parameter values used for evaluation. --- # MinimizeProtocol **`class MinimizeProtocol`** ベースクラス: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol) Protocol for classical optimizers used to tune QAOA circuit parameters. Implement this protocol to provide a custom classical optimizer. Assign an instance to [`minimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) to replace the default [`ScipyMinimize`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize). **Methods** | | | | --- | --- | | [`__init__`](#amplify.MinimizeProtocol.__init__) | | **`abstract __call__(func: Callable[[list[float]], float], num_parameters: int, *, dry_run: bool = False) → MinimizeResult | None`** Run the classical optimization. **パラメータ:** * **func** (*Callable[[*[*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*float*](https://docs.python.org/3/library/functions.html#float)*]],* [*float*](https://docs.python.org/3/library/functions.html#float)*]*) -- Objective function that maps a list of circuit parameters to a scalar cost. * **num_parameters** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of variational parameters to optimize. * **dry_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- If `True`, validate inputs without running the optimizer and return `None`. **戻り値:** The optimization result, or `None` if *dry_run* is `True`. **戻り値の型:** [*MinimizeResult*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md#amplify.MinimizeResult) | *None* **`__init__(*args, **kwargs)`** --- # MinimizeResult **`class MinimizeResult`** ベースクラス: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol) Protocol for the result of a classical minimization run. Returned by [`MinimizeProtocol.__call__()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol.__call__) after the optimizer finishes. **Methods** | | | | --- | --- | | [`__init__`](#amplify.MinimizeResult.__init__) | | **Attributes** | | | | --- | --- | | [`best_objective`](#amplify.MinimizeResult.best_objective) | Best (lowest) objective value found by the optimizer. | | [`best_parameters`](#amplify.MinimizeResult.best_parameters) | Circuit parameter values corresponding to the best objective. | **`__init__(*args, **kwargs)`** **`abstract property best_objective: float`** Best (lowest) objective value found by the optimizer. **`abstract property best_parameters: tuple[float, ...]`** Circuit parameter values corresponding to the best objective. --- # Sampler | | | | --- | --- | | [`SamplerProtocol`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol) | Protocol for quantum circuit samplers. | | [`SamplingDurations`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md#amplify.SamplingDurations) | Timing breakdown for a single quantum circuit sampling call. | | [`AerDeviceType`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md#amplify.AerDeviceType) | [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)['CPU', 'GPU', 'Thrust'] の別名です。 | | [`QiskitJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta) | Metadata for a single Qiskit quantum job. | | [`QulacsJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta) | Metadata for a single Qulacs simulation run. | | [`BraketJobMeta`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta) | Metadata for a single Braket quantum job. | --- # SamplerProtocol **`class SamplerProtocol`** ベースクラス: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol), [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic)[`SamplingMeta_co`, `CircType_co`] Protocol for quantum circuit samplers. Implement this protocol to add support for a new quantum backend. A conforming class must implement [`get_circuit_class()`](#amplify.SamplerProtocol.get_circuit_class) and [`sampling()`](#amplify.SamplerProtocol.sampling). **Methods** | | | | --- | --- | | [`__init__`](#amplify.SamplerProtocol.__init__) | | | [`get_circuit_class`](#amplify.SamplerProtocol.get_circuit_class) | Return the circuit class this sampler operates on. | | [`sampling`](#amplify.SamplerProtocol.sampling) | Execute the given quantum circuit and return measurement results. | **`__init__(*args, **kwargs)`** **`abstract classmethod get_circuit_class() → type[CircType_co]`** Return the circuit class this sampler operates on. **`abstract sampling( qc: Any, shots: int, ) → tuple[list[tuple[list[int], int]], SamplingDurations, SamplingMeta_co]`** Execute the given quantum circuit and return measurement results. Measures all qubits. The circuit does not need to include explicit measurement gates. Results are listed in ascending qubit-index order. **パラメータ:** * **qc** (*Any*) -- The circuit to execute. Must be an instance of the type returned by [`get_circuit_class()`](#amplify.SamplerProtocol.get_circuit_class). * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of times to execute the circuit. **戻り値:** A tuple of `(counts, durations, meta)` where *counts* is a list of `(spin_sequence, frequency)` pairs, *durations* is the timing breakdown, and *meta* is backend-specific metadata. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[IsingSeqFreqList, [*SamplingDurations*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md#amplify.SamplingDurations), SamplingMeta_co] --- # SamplingDurations **`class SamplingDurations`** Timing breakdown for a single quantum circuit sampling call. Recorded for each call to [`SamplerProtocol.sampling()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol.sampling). **Methods** | | | | --- | --- | | [`__init__`](#amplify.SamplingDurations.__init__) | | **Attributes** | | | | --- | --- | | [`total_time`](#amplify.SamplingDurations.total_time) | Total wall-clock time for this sampling call, including local overhead such as circuit transpilation and result decoding. | | [`response_time`](#amplify.SamplingDurations.response_time) | Time from circuit submission to result receipt (round-trip latency). | | [`execution_time`](#amplify.SamplingDurations.execution_time) | Actual quantum hardware (or simulator) execution time. | **`__eq__(other)`** Return self==value. **`__hash__()`** Return hash(self). **`__init__(total_time: timedelta, response_time: timedelta, execution_time: timedelta) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'execution_time': Field(name='execution_time',type='timedelta',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'response_time': Field(name='response_time',type='timedelta',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'total_time': Field(name='total_time',type='timedelta',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)`** **`__match_args__ = ('total_time', 'response_time', 'execution_time')`** **`execution_time: timedelta`** Actual quantum hardware (or simulator) execution time. For simulators this is typically equal to [`response_time`](#amplify.SamplingDurations.response_time). **`response_time: timedelta`** Time from circuit submission to result receipt (round-trip latency). **`total_time: timedelta`** Total wall-clock time for this sampling call, including local overhead such as circuit transpilation and result decoding. --- # AerDeviceType **`AerDeviceType`** [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)['CPU', 'GPU', 'Thrust'] の別名です。 --- # QiskitJobMeta **`class QiskitJobMeta`** Metadata for a single Qiskit quantum job. Attached to each circuit evaluation result when using a Qiskit-based sampler. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QiskitJobMeta.__init__) | | **Attributes** | | | | --- | --- | | [`circuit`](#amplify.QiskitJobMeta.circuit) | Original (untranspiled) quantum circuit submitted to the sampler. | | [`transpiled_circuit`](#amplify.QiskitJobMeta.transpiled_circuit) | Transpiled circuit that was actually sent to the backend, or `None` if no transpilation pass manager was applied. | | [`job_id`](#amplify.QiskitJobMeta.job_id) | IBM Quantum job identifier, useful for tracking jobs on the IBM Quantum platform. | | [`metadata`](#amplify.QiskitJobMeta.metadata) | Raw metadata from the job result object, if available. | | [`metrics`](#amplify.QiskitJobMeta.metrics) | Performance metrics reported by the job, if available (e.g., circuit duration on real hardware). | **`__eq__(other)`** Return self==value. **`__hash__()`** Return hash(self). **`__init__( circuit: QuantumCircuit, transpiled_circuit: QuantumCircuit | None, job_id: str, metadata: dict | None = None, metrics: dict | None = None, ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'circuit': Field(name='circuit',type='QiskitCircuit.T_circuit',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'job_id': Field(name='job_id',type='str',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'metadata': Field(name='metadata',type='dict | None',default=None,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'metrics': Field(name='metrics',type='dict | None',default=None,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'transpiled_circuit': Field(name='transpiled_circuit',type='QiskitCircuit.T_circuit | None',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)`** **`__match_args__ = ('circuit', 'transpiled_circuit', 'job_id', 'metadata', 'metrics')`** **`circuit: QuantumCircuit`** Original (untranspiled) quantum circuit submitted to the sampler. **`job_id: str`** IBM Quantum job identifier, useful for tracking jobs on the IBM Quantum platform. **`metadata: dict | None`** Raw metadata from the job result object, if available. **`metrics: dict | None`** Performance metrics reported by the job, if available (e.g., circuit duration on real hardware). **`transpiled_circuit: QuantumCircuit | None`** Transpiled circuit that was actually sent to the backend, or `None` if no transpilation pass manager was applied. --- # QulacsJobMeta **`class QulacsJobMeta`** Metadata for a single Qulacs simulation run. Attached to each circuit evaluation result when using the Qulacs sampler. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QulacsJobMeta.__init__) | | **Attributes** | | | | --- | --- | | [`circuit`](#amplify.QulacsJobMeta.circuit) | Quantum circuit that was simulated. | **`__eq__(other)`** Return self==value. **`__hash__()`** Return hash(self). **`__init__(circuit: QuantumCircuit) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'circuit': Field(name='circuit',type='QulacsCircuit.T_circuit',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)`** **`__match_args__ = ('circuit',)`** **`circuit: QuantumCircuit`** Quantum circuit that was simulated. --- # BraketJobMeta **`class BraketJobMeta`** Metadata for a single Braket quantum job. Attached to each circuit evaluation result when using a Braket-based sampler. **Methods** | | | | --- | --- | | [`__init__`](#amplify.BraketJobMeta.__init__) | | **Attributes** | | | | --- | --- | | [`circuit`](#amplify.BraketJobMeta.circuit) | Original quantum circuit submitted to the sampler. | | [`transpiled_circuit`](#amplify.BraketJobMeta.transpiled_circuit) | Transpiled circuit that was actually sent to the backend. | | [`metadata`](#amplify.BraketJobMeta.metadata) | Task metadata from the Braket service, or `None` if unavailable. | **`__eq__(other)`** Return self==value. **`__hash__()`** Return hash(self). **`__init__( circuit: QuantumCircuit, transpiled_circuit: QuantumCircuit | None, metadata: AmazonBraketTaskMetadata | None, ) → None`** **`__repr__()`** Return repr(self). **`__dataclass_fields__ = {'circuit': Field(name='circuit',type='QiskitCircuit.T_circuit',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'metadata': Field(name='metadata',type='AmazonBraketTaskMetadata | None',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'transpiled_circuit': Field(name='transpiled_circuit',type='QiskitCircuit.T_circuit | None',default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}`** **`__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)`** **`__match_args__ = ('circuit', 'transpiled_circuit', 'metadata')`** **`circuit: QuantumCircuit`** Original quantum circuit submitted to the sampler. **`metadata: AmazonBraketTaskMetadata | None`** Task metadata from the Braket service, or `None` if unavailable. **`transpiled_circuit: QuantumCircuit | None`** Transpiled circuit that was actually sent to the backend. --- # Circuit | | | | --- | --- | | [`QiskitCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit) | Qiskit-based quantum circuit implementation. | | [`QulacsCircuit`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md#amplify.QulacsCircuit) | Qulacs-based quantum circuit implementation. | --- # QiskitCircuit **`class QiskitCircuit`** Qiskit-based quantum circuit implementation. Wraps `QuantumCircuit` and `SparsePauliOp` to satisfy the circuit protocol interface required by QAOA circuit construction. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QiskitCircuit.__init__) | | | [`add_cnot_gate`](#amplify.QiskitCircuit.add_cnot_gate) | Apply a CNOT gate with control qubit *i* and target qubit *j*. | | [`add_h_gate`](#amplify.QiskitCircuit.add_h_gate) | Apply a Hadamard gate to qubit *i*. | | [`add_observable_rotation_gate`](#amplify.QiskitCircuit.add_observable_rotation_gate) | Apply a Hamiltonian evolution gate `exp(-i * value * H)`. | | [`add_rx_gate`](#amplify.QiskitCircuit.add_rx_gate) | Apply an Rx rotation gate to qubit *i*. | | [`add_ry_gate`](#amplify.QiskitCircuit.add_ry_gate) | Apply an Ry rotation gate to qubit *i*. | | [`add_x_gate`](#amplify.QiskitCircuit.add_x_gate) | Apply a Pauli-X gate to qubit *i*. | | [`construct_quantum_circuit`](#amplify.QiskitCircuit.construct_quantum_circuit) | Create a new `QuantumCircuit` with *num_qubits* qubits. | | [`get_observable_class`](#amplify.QiskitCircuit.get_observable_class) | Return the observable implementation class used by this circuit. | **Attributes** | | | | --- | --- | | [`circuit`](#amplify.QiskitCircuit.circuit) | Underlying `QuantumCircuit` object. | | [`num_qubits`](#amplify.QiskitCircuit.num_qubits) | Number of qubits in the circuit. | **`class ObservableImpl`** Observable builder backed by `SparsePauliOp`. Accumulates Pauli-X and Pauli-Z terms to construct a Hamiltonian used as the generator of a unitary rotation gate. **`__init__( num_qubits: int, _obs: SparsePauliOp | None = None, ) → None`** **`add_pauli_x(num_qubits: int, bit_index: int, value: float) → Self`** **`add_pauli_x(num_qubits: int, bit_index: Iterable[int], value: float) → Self`** Add a weighted Pauli-X term acting on the specified qubit(s). **パラメータ:** * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Total number of qubits in the operator. * **bit_index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| Iterable[*[*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Qubit index or indices for the X operator. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Coefficient of the term. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_pauli_z(num_qubits: int, bit_index: int, value: float) → Self`** **`add_pauli_z(num_qubits: int, bit_index: Iterable[int], value: float) → Self`** Add a weighted Pauli-Z term acting on the specified qubit(s). **パラメータ:** * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Total number of qubits in the operator. * **bit_index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| Iterable[*[*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Qubit index or indices for the Z operator. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Coefficient of the term. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`static construct_observable( num_qubits: int, ) → SparsePauliOp`** Return a zero-initialized `SparsePauliOp`. **パラメータ:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits in the observable. **戻り値:** Zero operator over *num_qubits* qubits. **戻り値の型:** SparsePauliOp **`get_raw() → SparsePauliOp`** Return the underlying [`SparsePauliOp`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp). **`T_circuit`** [`QuantumCircuit`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit) の別名です。 **`T_obs`** [`SparsePauliOp`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp) の別名です。 **`__init__(num_qubits: int) → None`** **`add_cnot_gate(i: int, j: int) → Self`** Apply a CNOT gate with control qubit *i* and target qubit *j*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Control qubit index. * **j** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_h_gate(i: int) → Self`** Apply a Hadamard gate to qubit *i*. **パラメータ:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_observable_rotation_gate(op_f: SupportsHam[QiskitCircuit.T_obs], value: float, num_qubits: int) → Self`** Apply a Hamiltonian evolution gate `exp(-i * value * H)`. Appends a [`PauliEvolutionGate`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.library.PauliEvolutionGate) generated from *op_f* to the circuit. **パラメータ:** * **op_f** (*SupportsHam[SparsePauliOp]*) -- Observable whose raw `SparsePauliOp` is used as the Hamiltonian *H*. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Evolution time (rotation angle). * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits the gate acts on. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_rx_gate(i: int, value: float) → Self`** Apply an Rx rotation gate to qubit *i*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Rotation angle in radians. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_ry_gate(i: int, value: float) → Self`** Apply an Ry rotation gate to qubit *i*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Rotation angle in radians. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_x_gate(i: int) → Self`** Apply a Pauli-X gate to qubit *i*. **パラメータ:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`static construct_quantum_circuit(num_qubits: int) → QuantumCircuit`** Create a new `QuantumCircuit` with *num_qubits* qubits. **パラメータ:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits. **戻り値:** An empty circuit with a single quantum register. **戻り値の型:** QuantumCircuit **`classmethod get_observable_class() → type[ObservableImpl]`** Return the observable implementation class used by this circuit. **`property circuit: QuantumCircuit`** Underlying `QuantumCircuit` object. **`property num_qubits: int`** Number of qubits in the circuit. --- # QulacsCircuit **`class QulacsCircuit`** Qulacs-based quantum circuit implementation. Wraps `QuantumCircuit` and `Observable` from Qulacs to satisfy the circuit protocol interface required by QAOA circuit construction. **Methods** | | | | --- | --- | | [`__init__`](#amplify.QulacsCircuit.__init__) | | | [`add_cnot_gate`](#amplify.QulacsCircuit.add_cnot_gate) | Apply a CNOT gate with control qubit *i* and target qubit *j*. | | [`add_h_gate`](#amplify.QulacsCircuit.add_h_gate) | Apply a Hadamard gate to qubit *i*. | | [`add_observable_rotation_gate`](#amplify.QulacsCircuit.add_observable_rotation_gate) | Apply a Hamiltonian evolution gate `exp(-i * value * H)`. | | [`add_rx_gate`](#amplify.QulacsCircuit.add_rx_gate) | Apply an Rx rotation gate to qubit *i*. | | [`add_ry_gate`](#amplify.QulacsCircuit.add_ry_gate) | Apply an Ry rotation gate to qubit *i*. | | [`add_x_gate`](#amplify.QulacsCircuit.add_x_gate) | Apply a Pauli-X gate to qubit *i*. | | [`construct_quantum_circuit`](#amplify.QulacsCircuit.construct_quantum_circuit) | Create a new Qulacs `QuantumCircuit` with *num_qubits* qubits. | | [`get_observable_class`](#amplify.QulacsCircuit.get_observable_class) | Return the observable implementation class used by this circuit. | **Attributes** | | | | --- | --- | | [`circuit`](#amplify.QulacsCircuit.circuit) | Underlying Qulacs `QuantumCircuit` object. | | [`num_qubits`](#amplify.QulacsCircuit.num_qubits) | Number of qubits in the circuit. | **`class ObservableImpl`** Observable builder backed by `Observable` from Qulacs. Accumulates Pauli-X and Pauli-Z terms to construct a Hamiltonian used as the generator of a unitary rotation gate. **`__init__(num_qubits: int, _obs: Observable | None = None) → None`** **`add_pauli_x(num_qubits: int, bit_index: int, value: float) → Self`** **`add_pauli_x(num_qubits: int, bit_index: Iterable[int], value: float) → Self`** Add a weighted Pauli-X term acting on the specified qubit(s). **パラメータ:** * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Total number of qubits in the operator (unused for Qulacs). * **bit_index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| Iterable[*[*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Qubit index or indices for the X operator. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Coefficient of the term. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_pauli_z(num_qubits: int, bit_index: int, value: float) → Self`** **`add_pauli_z(num_qubits: int, bit_index: Iterable[int], value: float) → Self`** Add a weighted Pauli-Z term acting on the specified qubit(s). **パラメータ:** * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Total number of qubits in the operator (unused for Qulacs). * **bit_index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| Iterable[*[*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Qubit index or indices for the Z operator. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Coefficient of the term. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`static construct_observable(num_qubits: int) → Observable`** Return an empty `Observable` over *num_qubits* qubits. **パラメータ:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits in the observable. **戻り値:** An empty Qulacs `Observable` over *num_qubits* qubits. **戻り値の型:** Observable **`get_raw() → Observable`** Return the underlying Qulacs `Observable`. **`T_circuit`** `QuantumCircuit` の別名です。 **`T_obs`** `Observable` の別名です。 **`__init__(num_qubits: int) → None`** **`add_cnot_gate(i: int, j: int) → Self`** Apply a CNOT gate with control qubit *i* and target qubit *j*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Control qubit index. * **j** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_h_gate(i: int) → Self`** Apply a Hadamard gate to qubit *i*. **パラメータ:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_observable_rotation_gate(op_f: SupportsHam[QulacsCircuit.T_obs], value: float, num_qubits: int) → Self`** Apply a Hamiltonian evolution gate `exp(-i * value * H)`. **パラメータ:** * **op_f** (*SupportsHam[Observable]*) -- Observable whose raw `Observable` is used as the Hamiltonian *H*. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Evolution time (rotation angle). * **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits the gate acts on (unused for Qulacs). **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_rx_gate(i: int, value: float) → Self`** Apply an Rx rotation gate to qubit *i*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Rotation angle in radians. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_ry_gate(i: int, value: float) → Self`** Apply an Ry rotation gate to qubit *i*. **パラメータ:** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Rotation angle in radians. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`add_x_gate(i: int) → Self`** Apply a Pauli-X gate to qubit *i*. **パラメータ:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Target qubit index. **戻り値:** This instance, for chaining. **戻り値の型:** Self **`static construct_quantum_circuit(num_qubits: int) → QuantumCircuit`** Create a new Qulacs `QuantumCircuit` with *num_qubits* qubits. **パラメータ:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- Number of qubits. **戻り値:** An empty Qulacs `QuantumCircuit` over *num_qubits* qubits. **戻り値の型:** QuantumCircuit **`classmethod get_observable_class() → type[ObservableImpl]`** Return the observable implementation class used by this circuit. **`property circuit: QuantumCircuit`** Underlying Qulacs `QuantumCircuit` object. **`property num_qubits: int`** Number of qubits in the circuit. --- # Misc. | | | | --- | --- | | [`IsingSeqFreqList`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md#amplify.IsingSeqFreqList) | [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`int`](https://docs.python.org/3/library/functions.html#int)], [`int`](https://docs.python.org/3/library/functions.html#int)]] の別名です。 | --- # IsingSeqFreqList **`IsingSeqFreqList`** [`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/library/stdtypes.html#list)[[`int`](https://docs.python.org/3/library/functions.html#int)], [`int`](https://docs.python.org/3/library/functions.html#int)]] の別名です。 --- # Deprecated ## Deprecated classes and functions ### Class | | | | --- | --- | | [`amplify.BinaryPoly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md#amplify.BinaryPoly) | alias of [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | | [`amplify.IsingPoly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPoly.md#amplify.IsingPoly) | alias of [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | | [`amplify.BinaryPolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md#amplify.BinaryPolyArray) | | | [`amplify.IsingPolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md#amplify.IsingPolyArray) | | | [`amplify.BinarySymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator) | | | [`amplify.IsingSymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | | | [`amplify.IsingSymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | | | [`amplify.BinaryMatrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md#amplify.BinaryMatrix) | | | [`amplify.IsingMatrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md#amplify.IsingMatrix) | | | [`amplify.QuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md#amplify.QuadraticModel) | | | [`amplify.BinaryQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) | | | [`amplify.IsingQuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) | | | [`amplify.Solver`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) | | | [`amplify.SolverResult`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverResult.md#amplify.SolverResult) | | | [`amplify.SolverSolution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SolverSolution.md#amplify.SolverSolution) | | ### Function | | | | --- | --- | | [`amplify.SymbolGenerator`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md#amplify.SymbolGenerator) | | | [`amplify.sum_poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.sum_poly.md#amplify.sum_poly) | | | [`amplify.decode_solution`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.decode_solution.md#amplify.decode_solution) | | | [`amplify.constraint.penalty`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.constraint.penalty.md#amplify.constraint.penalty) | alias of constructor of [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) | ### Enum | | | | --- | --- | | [`amplify.InequalityFormulation`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.InequalityFormulation.md#amplify.InequalityFormulation) | An enumeration. | --- # BinaryPoly **`class BinaryPoly`** ベースクラス: [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) alias of [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **Methods** | | | | --- | --- | | [`__init__`](#amplify.BinaryPoly.__init__) | __init__ | | [`as_dict`](#amplify.BinaryPoly.as_dict) | Return the dictionary representation of the polynomial. | | [`as_variable`](#amplify.BinaryPoly.as_variable) | Return the variable representation of the polynomial. | | [`asdict`](#amplify.BinaryPoly.asdict) | alias of [`as_dict()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) | | [`decode`](#amplify.BinaryPoly.decode) | Equivalent to [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate). | | [`degree`](#amplify.BinaryPoly.degree) | Return the degree of the polynomial. | | [`evaluate`](#amplify.BinaryPoly.evaluate) | Evaluate the polynomial by substituting variables using the given values. | | [`is_linear`](#amplify.BinaryPoly.is_linear) | Return `True` if the polynomial is linear. | | [`is_number`](#amplify.BinaryPoly.is_number) | Return `True` if the polynomial is a constant polynomial. | | [`is_quadratic`](#amplify.BinaryPoly.is_quadratic) | Return `True` if the polynomial is quadratic. | | [`is_variable`](#amplify.BinaryPoly.is_variable) | Return `True` if the polynomial represents a single variable. | | [`substitute`](#amplify.BinaryPoly.substitute) | Assign numbers or other polynomials to variables in the polynomial. | **Attributes** | | | | --- | --- | | [`id`](#amplify.BinaryPoly.id) | Variable ID. | | [`lower_bound`](#amplify.BinaryPoly.lower_bound) | Lower bound of the variable. | | [`name`](#amplify.BinaryPoly.name) | Variable name. | | [`type`](#amplify.BinaryPoly.type) | Variable type. | | [`upper_bound`](#amplify.BinaryPoly.upper_bound) | Upper bound of the variable. | | [`variables`](#amplify.BinaryPoly.variables) | List of all variables in the polynomial. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__next__(self) → tuple[tuple[Poly, ...], float]`** **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`__add__(self, arg: Poly | float, /) → Poly`** **`__add__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** __add__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__and__(self, arg: Poly | bool, /) → Poly`** **`__and__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical AND of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 & q_1` is equivalent to `q_0 * q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__bool__(self) → bool`** Cast a polynomial to a boolean value. Only valid for constant polynomials that take values 0 or 1. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__float__(self) → float`** Cast a polynomial to a float value. Only valid for constant polynomials. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__imul__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__index__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self) → None`** **`__init__(self, arg: float, /) → None`** **`__init__(self, arg: Variable, /) → None`** __init__ > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (float) > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Variable) **`__int__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → Poly`** Logical NOT of a polynomial. This is meaningful only for polynomials that take values 0 or 1. `~q_0` is equivalent to `1 - q_0`. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ipow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__isub__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iter__(self) → Iterator`** Iterate over the terms in the polynomial. Each term is represented as a tuple of a tuple of variables and a coefficient. For example, the polynomial `3 * x_0 * x_1 - 2 * x_0 + 5` is iterated as `((Poly(x_0), Poly(x_1)), 3.0)`, `((Poly(x_0),), -2.0)`, and `((), 5.0)`. **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) → Poly`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__len__(self) → int`** Return the number of terms in the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__mul__(self, arg: Poly | float, /) → Poly`** **`__mul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __mul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__or__(self, arg: Poly | bool, /) → Poly`** **`__or__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical OR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 | q_1` is equivalent to `-q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__pos__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__pow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__radd__(self, arg: float, /) → Poly`** **`__radd__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__rand__(self, arg: bool, /) → Poly`** **`__rand__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) → Poly`** **`__rmul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: bool, /) → Poly`** **`__ror__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: float, /) → Poly`** **`__rsub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: bool, /) → Poly`** **`__rxor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float, /) → Poly`** **`__sub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __sub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__truediv__(self, arg: float, /) → Poly`** **`__truediv__(self, arg: ndarray[], /) → PolyArray[Dim]`** __truediv__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → Poly`** **`__xor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical XOR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 ^ q_1` is equivalent to `-2 * q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`as_dict(self) → dict[tuple[int, ...], float]`** Return the dictionary representation of the polynomial. The polynomial is represented as a dictionary where keys are tuples of variable indices and values are coefficients. For example, the polynomial `3 * x_0 - 2 * x_0 * x_1 + 5` will be represented as `{(): 5, (0,): 3, (0, 1): -2}`. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`as_variable(self) → Variable`** Return the variable representation of the polynomial. Only valid for polynomials that represent a single variable. **戻り値の型:** [*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) → dict[tuple[int, ...], float]`** alias of [`as_dict()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`decode(self, values: Values) → float`** **`decode(self, values: Values, default: float) → float`** **`decode(self, values: Values, default: None) → Poly`** Equivalent to [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. Please see the migration guide for details: > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values) > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values) > * default (float) > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values) > * default (None) > > **Returns:** > > amplify.Poly: **`degree(self) → int`** Return the degree of the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** **`evaluate(self, values: Values, default: None) → Poly`** Evaluate the polynomial by substituting variables using the given values. This method is usually used to obtain optimization results in array form. If the keyword argument `default` is not specified, variables that are not specified in `values` will be substituted by a reasonable default value. If the keyword argument `default` is specified with a float value, variables that are not specified in `values` will be substituted by that value. If the keyword argument `default` is specified with `None`, variables that are not specified in `values` will remain as symbolic variables without substitution. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values that can be obtained from optimization results, e.g. `result.best.values`. > * default (float): The default value for variables not specified in `values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > * default (None): Set to `None` to keep variables not specified in `values` symbolic. > > **Returns:** > > amplify.Poly: **`is_linear(self) → bool`** Return `True` if the polynomial is linear. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) → bool`** Return `True` if the polynomial is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) → bool`** Return `True` if the polynomial is quadratic. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) → bool`** Return `True` if the polynomial represents a single variable. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → Poly`** Assign numbers or other polynomials to variables in the polynomial. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Key-value pairs of variables and replacement values. Each value can be a number or another polynomial. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__deprecated__ = 'BinaryPoly is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Poly instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property id`** Variable ID. Only valid for polynomials that represent a single variable. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property lower_bound`** Lower bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **戻り値の型:** [*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) **`property upper_bound`** Upper bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # IsingPoly **`class IsingPoly`** ベースクラス: [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) alias of [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **Methods** | | | | --- | --- | | [`__init__`](#amplify.IsingPoly.__init__) | __init__ | | [`as_dict`](#amplify.IsingPoly.as_dict) | Return the dictionary representation of the polynomial. | | [`as_variable`](#amplify.IsingPoly.as_variable) | Return the variable representation of the polynomial. | | [`asdict`](#amplify.IsingPoly.asdict) | alias of [`as_dict()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) | | [`decode`](#amplify.IsingPoly.decode) | Equivalent to [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate). | | [`degree`](#amplify.IsingPoly.degree) | Return the degree of the polynomial. | | [`evaluate`](#amplify.IsingPoly.evaluate) | Evaluate the polynomial by substituting variables using the given values. | | [`is_linear`](#amplify.IsingPoly.is_linear) | Return `True` if the polynomial is linear. | | [`is_number`](#amplify.IsingPoly.is_number) | Return `True` if the polynomial is a constant polynomial. | | [`is_quadratic`](#amplify.IsingPoly.is_quadratic) | Return `True` if the polynomial is quadratic. | | [`is_variable`](#amplify.IsingPoly.is_variable) | Return `True` if the polynomial represents a single variable. | | [`substitute`](#amplify.IsingPoly.substitute) | Assign numbers or other polynomials to variables in the polynomial. | **Attributes** | | | | --- | --- | | [`id`](#amplify.IsingPoly.id) | Variable ID. | | [`lower_bound`](#amplify.IsingPoly.lower_bound) | Lower bound of the variable. | | [`name`](#amplify.IsingPoly.name) | Variable name. | | [`type`](#amplify.IsingPoly.type) | Variable type. | | [`upper_bound`](#amplify.IsingPoly.upper_bound) | Upper bound of the variable. | | [`variables`](#amplify.IsingPoly.variables) | List of all variables in the polynomial. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → Iterator`** **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__next__(self) → tuple[tuple[Poly, ...], float]`** **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`__add__(self, arg: Poly | float, /) → Poly`** **`__add__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** __add__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__and__(self, arg: Poly | bool, /) → Poly`** **`__and__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical AND of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 & q_1` is equivalent to `q_0 * q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__bool__(self) → bool`** Cast a polynomial to a boolean value. Only valid for constant polynomials that take values 0 or 1. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__float__(self) → float`** Cast a polynomial to a float value. Only valid for constant polynomials. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__imul__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__index__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self) → None`** **`__init__(self, arg: float, /) → None`** **`__init__(self, arg: Variable, /) → None`** __init__ > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (float) > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Variable) **`__int__(self) → int`** Cast a polynomial to an integer. Only valid for constant polynomials. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → Poly`** Logical NOT of a polynomial. This is meaningful only for polynomials that take values 0 or 1. `~q_0` is equivalent to `1 - q_0`. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ipow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__isub__(self, arg: Poly | float, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iter__(self) → Iterator`** Iterate over the terms in the polynomial. Each term is represented as a tuple of a tuple of variables and a coefficient. For example, the polynomial `3 * x_0 * x_1 - 2 * x_0 + 5` is iterated as `((Poly(x_0), Poly(x_1)), 3.0)`, `((Poly(x_0),), -2.0)`, and `((), 5.0)`. **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) → Poly`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) → Poly`** **パラメータ:** **arg** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__len__(self) → int`** Return the number of terms in the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__mul__(self, arg: Poly | float, /) → Poly`** **`__mul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __mul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__or__(self, arg: Poly | bool, /) → Poly`** **`__or__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical OR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 | q_1` is equivalent to `-q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__pos__(self) → Poly`** **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__pow__(self, arg: int, /) → Poly`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__radd__(self, arg: float, /) → Poly`** **`__radd__(self, arg: ndarray[], /) → PolyArray[Dim]`** **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.Constraint | amplify.ConstraintList) > > **Returns:** > > amplify.Model: **`__rand__(self, arg: bool, /) → Poly`** **`__rand__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) → Poly`** **`__rmul__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: bool, /) → Poly`** **`__ror__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: float, /) → Poly`** **`__rsub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: bool, /) → Poly`** **`__rxor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float, /) → Poly`** **`__sub__(self, arg: ndarray[], /) → PolyArray[Dim]`** __sub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__truediv__(self, arg: float, /) → Poly`** **`__truediv__(self, arg: ndarray[], /) → PolyArray[Dim]`** __truediv__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → Poly`** **`__xor__(self, arg: ndarray[dtype=bool], /) → PolyArray[Dim]`** Logical XOR of two polynomials. This is meaningful only for polynomials that take values 0 or 1. `q_0 ^ q_1` is equivalent to `-2 * q_0 * q_1 + q_0 + q_1`. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`as_dict(self) → dict[tuple[int, ...], float]`** Return the dictionary representation of the polynomial. The polynomial is represented as a dictionary where keys are tuples of variable indices and values are coefficients. For example, the polynomial `3 * x_0 - 2 * x_0 * x_1 + 5` will be represented as `{(): 5, (0,): 3, (0, 1): -2}`. **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`as_variable(self) → Variable`** Return the variable representation of the polynomial. Only valid for polynomials that represent a single variable. **戻り値の型:** [*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) → dict[tuple[int, ...], float]`** alias of [`as_dict()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) **戻り値の型:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...], [*float*](https://docs.python.org/3/library/functions.html#float)] **`decode(self, values: Values) → float`** **`decode(self, values: Values, default: float) → float`** **`decode(self, values: Values, default: None) → Poly`** Equivalent to [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. Please see the migration guide for details: > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values) > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values) > * default (float) > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values) > * default (None) > > **Returns:** > > amplify.Poly: **`degree(self) → int`** Return the degree of the polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** **`evaluate(self, values: Values, default: None) → Poly`** Evaluate the polynomial by substituting variables using the given values. This method is usually used to obtain optimization results in array form. If the keyword argument `default` is not specified, variables that are not specified in `values` will be substituted by a reasonable default value. If the keyword argument `default` is specified with a float value, variables that are not specified in `values` will be substituted by that value. If the keyword argument `default` is specified with `None`, variables that are not specified in `values` will remain as symbolic variables without substitution. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values that can be obtained from optimization results, e.g. `result.best.values`. > * default (float): The default value for variables not specified in `values`. > > **Returns:** > > float: > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values obtained from optimization results, e.g. `result.best.values`. > * default (None): Set to `None` to keep variables not specified in `values` symbolic. > > **Returns:** > > amplify.Poly: **`is_linear(self) → bool`** Return `True` if the polynomial is linear. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) → bool`** Return `True` if the polynomial is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) → bool`** Return `True` if the polynomial is quadratic. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) → bool`** Return `True` if the polynomial represents a single variable. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → Poly`** Assign numbers or other polynomials to variables in the polynomial. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- Key-value pairs of variables and replacement values. Each value can be a number or another polynomial. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__deprecated__ = 'IsingPoly is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Poly instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property id`** Variable ID. Only valid for polynomials that represent a single variable. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property lower_bound`** Lower bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **戻り値の型:** [*VariableType*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) **`property upper_bound`** Upper bound of the variable. Only valid for polynomials that represent a single variable. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **戻り値の型:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # BinaryPolyArray **`class BinaryPolyArray`** ベースクラス: [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) **Methods** | | | | --- | --- | | [`__init__`](#amplify.BinaryPolyArray.__init__) | | | [`copy`](#amplify.BinaryPolyArray.copy) | Return a copy of the array. | | [`decode`](#amplify.BinaryPolyArray.decode) | Deprecated alias of [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate). | | [`diagonal`](#amplify.BinaryPolyArray.diagonal) | Return a diagonal extracted from the array. | | [`evaluate`](#amplify.BinaryPolyArray.evaluate) | Evaluate each element by substituting variable values. | | [`fill`](#amplify.BinaryPolyArray.fill) | Fill all elements with a single polynomial or scalar value. | | [`flatten`](#amplify.BinaryPolyArray.flatten) | Return a flattened 1D copy of the array. | | [`nonzero`](#amplify.BinaryPolyArray.nonzero) | Return the indices of non-zero elements. | | [`ravel`](#amplify.BinaryPolyArray.ravel) | Return a flattened 1D view when possible. | | [`repeat`](#amplify.BinaryPolyArray.repeat) | Repeat elements of the array. | | [`reshape`](#amplify.BinaryPolyArray.reshape) | Return a reshaped view of the array. | | [`roll`](#amplify.BinaryPolyArray.roll) | Roll array elements along an axis. | | [`substitute`](#amplify.BinaryPolyArray.substitute) | Substitute variables in all elements of the array. | | [`sum`](#amplify.BinaryPolyArray.sum) | Sum array elements over the specified axis or axes. | | [`swapaxes`](#amplify.BinaryPolyArray.swapaxes) | Return a view with two axes swapped. | | [`take`](#amplify.BinaryPolyArray.take) | Take elements from the array along an axis. | | [`to_list`](#amplify.BinaryPolyArray.to_list) | Convert the polynomial array to nested Python lists. | | [`to_numpy`](#amplify.BinaryPolyArray.to_numpy) | Convert the polynomial array to a NumPy `float64` ndarray. | | [`tolist`](#amplify.BinaryPolyArray.tolist) | Alias of [`to_list()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). | | [`tonumpy`](#amplify.BinaryPolyArray.tonumpy) | Alias of [`to_numpy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). | | [`transpose`](#amplify.BinaryPolyArray.transpose) | Permute axes and return a transposed view. | | [`view`](#amplify.BinaryPolyArray.view) | Return a view of the same underlying data. | **Attributes** | | | | --- | --- | | [`T`](#amplify.BinaryPolyArray.T) | A transposed view of the array. | | [`flat`](#amplify.BinaryPolyArray.flat) | A 1D view of the array. | | [`ndim`](#amplify.BinaryPolyArray.ndim) | The number of dimensions of the array. | | [`shape`](#amplify.BinaryPolyArray.shape) | The shape of the array. | | [`size`](#amplify.BinaryPolyArray.size) | The total number of elements in the array. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → typing_extensions.Self`** **戻り値の型:** typing_extensions.Self **`__next__(self: Iterator[Dim1]) → Poly`** **`__next__(self: Iterator[Dim2]) → PolyArray[Dim1]`** **`__next__(self: Iterator[Dim3]) → PolyArray[Dim2]`** **`__next__(self: Iterator[Dim4]) → PolyArray[Dim3]`** **`__next__(self) → Poly | PolyArray[Dim]`** __next__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim1]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim2]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim3]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim4]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 5.** > > **Returns:** > > Poly | PolyArray[Dim]: **`__nb_signature__ = 'class Iterator(typing.Generic[__Dim])'`** **`__add__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__add__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__add__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__and__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__and__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__and__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__and__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __and__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__bool__(self) → bool`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__copy__(self) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__deepcopy__(self, arg: dict, /) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **パラメータ:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__eq__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__eq__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__float__(self) → float`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__getitem__(self: PolyArray[Dim0], arg: tuple[()]) → Poly`** **`__getitem__(self: PolyArray[Dim0], arg: EllipsisType) → PolyArray[Dim0]`** **`__getitem__(self: PolyArray[Dim1], arg: tuple[int] | int) → Poly`** **`__getitem__( self: PolyArray[Dim1], arg: EllipsisType | tuple[()] | slice | tuple[slice], ) → PolyArray[Dim1]`** **`__getitem__(self: PolyArray[Dim2], arg: tuple[int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim2], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim2], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice], ) → PolyArray[Dim2]`** **`__getitem__(self: PolyArray[Dim3], arg: tuple[int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim3], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim3], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim3], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__(self: PolyArray[Dim4], arg: tuple[int, int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim4], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__( self: PolyArray[Dim4], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice], ) → PolyArray[Dim4]`** **`__getitem__(self: PolyArray[Dim], arg: tuple | slice | EllipsisType | int | None) → PolyArray[Dim]`** Return a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]): self > * arg (tuple[()]): An index specified as an integer, slice, ellipsis, or newaxis. > > **Returns:** > > amplify.Poly: Selected element or slice, depending on the index. > > **Raises:** > > IndexError: If any index is out of bounds. > TypeError: If index type is invalid. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (types.EllipsisType) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (tuple[int] | int) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (tuple[int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 14.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 15.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 16.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim4]: > [!NOTE] > > **Overload 17.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (tuple | slice | types.EllipsisType | int | None) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **サンプル** > > ```python > from amplify import VariableGenerator, newaxis > > q = VariableGenerator().array("Binary", (3, 4)) > print(q[1, 2]) # Output: Poly(q_{1,2}) > print(q[0]) # Output: PolyArray([q_{0,0}, q_{0,1}, q_{0,2}, q_{0,3}]) > print(q[:, 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[..., 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[1, newaxis]) # Output: PolyArray([[q_{1,0}, q_{1,1}, q_{1,2}, q_{1,3}]]) > ``` **`__iadd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__iadd__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__iadd__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__iadd__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__iadd__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__iadd__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__iadd__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__iadd__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __iadd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__iand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__iand__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__iand__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __iand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__imul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__imul__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__imul__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__imul__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__imul__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__imul__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__imul__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__imul__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __imul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__index__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) → None`** **パラメータ:** **object** (*ndarray*) **`__int__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__ior__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ior__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ior__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ior__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ior__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ipow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__isub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__isub__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__isub__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__isub__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__isub__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__isub__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__isub__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__isub__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __isub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iter__(self) → Iterator[_Dim]`** Iterate over the first axis of the polynomial array. If the array has one or fewer dimensions, each yielded item is a polynomial. If the array has two or more dimensions, each yielded item is a subarray with one fewer dimension. **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__ixor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ixor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ixor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ixor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ixor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__len__(self) → int`** Return the number of elements along the first axis. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__matmul__(self, arg: amplify.PolyArray | ndarray[], /) → Poly | PolyArray[_Dim]`** Perform matrix multiplication on two polynomial arrays. For arrays with three or more dimensions, the last two dimensions are treated as matrices and the remaining dimensions as batch dimensions. Broadcasting is applied to the batch dimensions. **パラメータ:** **arg** ([*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) *| ndarray*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__mul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__mul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__mul__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__mul__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ne__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__ne__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__neg__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__or__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__or__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__or__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__or__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __or__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__pos__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__radd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__radd__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) → Poly | PolyArray[__Dim]`** **パラメータ:** **arg** (*NDArray |* [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)*[__Dim]*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[__Dim] **`__rmul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rmul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ror__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rsub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rxor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__setitem__( self, arg: tuple | slice | types.EllipsisType | int | None, value: amplify.Poly | float | int | list | ndarray[] | amplify.PolyArray, ) → None`** Assign a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. **パラメータ:** * **arg** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple) *|* [*slice*](https://docs.python.org/3/library/functions.html#slice) *|* [*EllipsisType*](https://docs.python.org/3/library/types.html#types.EllipsisType) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- An index specified as an integer, slice, ellipsis, or newaxis. * **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) -- Value to assign, compatible with the indexed shape. **例外:** * [**IndexError**](https://docs.python.org/3/library/exceptions.html#IndexError) -- If any index is out of bounds. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) -- If index type is invalid or value shape is incompatible. **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__sub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__sub__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__sub__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__truediv__(self, arg: float | int, /) → PolyArray[_Dim]`** **`__truediv__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__xor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__xor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__xor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __xor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`copy(self) → PolyArray[_Dim]`** Return a copy of the array. Each polynomial in the array is copied as well. **戻り値:** Copy of the array. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`decode(self, values: Values) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: None) → PolyArray[_Dim]`** Deprecated alias of [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`diagonal(self: PolyArray[Dim], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim]`** **`diagonal(self: PolyArray[Dim2], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim1]`** **`diagonal(self: PolyArray[Dim3], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim2]`** **`diagonal(self: PolyArray[Dim4], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim3]`** Return a diagonal extracted from the array. Take the diagonal along `axis1` and `axis2` with optional `offset`. Unlike NumPy, return a copy. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim1]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim2]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim3]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. **`evaluate(self, values: Values) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: None) → PolyArray[_Dim]`** Evaluate each element by substituting variable values. Pass optimization result values to get a NumPy array with the same shape. The behavior for unassigned variables can be controlled by `default`. When `default=None`, keep variables not present in `values` symbolic and return a [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray). > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`fill(self, value: Poly | float | int) → None`** Fill all elements with a single polynomial or scalar value. **パラメータ:** **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)) -- The value to assign to all elements. **`flatten(self) → PolyArray[Dim1]`** Return a flattened 1D copy of the array. **戻り値:** Flattened copy. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) → tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **戻り値:** Tuple of index arrays, one for each dimension. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)[dtype=uint64], ...] **`ravel(self) → PolyArray[Dim1]`** Return a flattened 1D view when possible. **戻り値:** Flattened view when possible. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`repeat(self, repeats: int | list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`repeat(self, repeats: int | list[int], axis: int) → PolyArray[_Dim]`** Repeat elements of the array. When `axis` is `None`, repetitions are applied to the flattened array, and a 1D array is returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (typing.Literal[None]): Axis along which to repeat. If `None`, the array is repeated as a flattened array. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (int): Axis along which to repeat. If `None`, the array is repeated as a flattened array. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. **`reshape(self, shape: int | tuple[int]) → PolyArray[Dim1]`** **`reshape(self, shape: tuple[int, int]) → PolyArray[Dim2]`** **`reshape(self, shape: tuple[int, int, int]) → PolyArray[Dim3]`** **`reshape(self, shape: tuple[int, int, int, int]) → PolyArray[Dim4]`** **`reshape(self, arg0: int, arg1: int) → PolyArray[Dim2]`** **`reshape(self, arg0: int, arg1: int, arg2: int) → PolyArray[Dim3]`** **`reshape(self, arg0: int, arg1: int, arg2: int, arg3: int) → PolyArray[Dim4]`** **`reshape(self, shape: tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]) → PolyArray[Dim]`** **`reshape(self, *shape: int) → PolyArray[Dim]`** Return a reshaped view of the array. The new shape must be compatible with the current size. At most one `-1` is allowed to infer an unknown dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * shape (int | tuple[int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim1]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * shape (tuple[int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * shape (tuple[int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * shape (tuple[int, int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > * arg3 (int): Fourth dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * shape (tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * \*shape (int): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. **`roll(self, shift: int, axis: int | None = None) → PolyArray[_Dim]`** Roll array elements along an axis. If `axis` is `None`, the array is rolled in flattened order. Unlike NumPy, `roll` is provided as a method, and cannot roll multiple axes simultaneously. **パラメータ:** * **shift** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The shift amount. * **axis** ([*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- Axis to roll. If `None`, the array is rolled as a flattened array. Defaults to `None`. **戻り値:** Array with rolled elements. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If axis is out of bounds. **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → PolyArray[_Dim]`** Substitute variables in all elements of the array. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- A mapping from variables to numeric values or polynomials. **戻り値:** Array after substitution. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`sum(self, axis: Literal[None] = None) → Poly`** **`sum(self: PolyArray[Dim1], axis: int | tuple[int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: tuple[int, int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: int | tuple[int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int, int]) → Poly`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: int | tuple[int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int, int]) → Poly`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: int | tuple[int]) → PolyArray[Dim3]`** **`sum(self: PolyArray[_Dim], axis: tuple[()]) → PolyArray[_Dim]`** **`sum(self: PolyArray[Dim], axis: int | tuple[int, ...]) → Poly | PolyArray[Dim]`** Sum array elements over the specified axis or axes. Without `axis`, all elements are summed into a single polynomial. With `axis`, the output type depends on the reduced dimensions. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axis (typing.Literal[None]): The axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim3]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[_Dim]): self > * axis (tuple[()]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[_Dim]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * axis (int | tuple[int, ...]): The axis or axes to reduce. > > **Returns:** > > Poly | PolyArray[Dim]: Summation result. Shape depends on `axis`. **`swapaxes(self, axis1: int, axis2: int) → PolyArray[_Dim]`** Return a view with two axes swapped. **パラメータ:** * **axis1** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The first axis. * **axis2** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The second axis. **戻り値:** Array with the two axes swapped. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If either axis is out of bounds. **`take(self, indices: int, axis: Literal[None] = None) → Poly`** **`take(self, indices: list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim], indices: int | list[int], axis: int | None = None) → PolyArray[Dim]`** **`take(self: PolyArray[Dim2], indices: int, axis: int) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim2], indices: list[int], axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: int, axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: list[int], axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: int, axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: list[int], axis: int) → PolyArray[Dim4]`** Take elements from the array along an axis. If `axis` is `None`, indices are interpreted on the flattened array. Elements are always copied, even when a view could be returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * indices (int): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.Poly: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * indices (list[int]): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * indices (int | list[int]): A single index or a list of indices. > * axis (int | None): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim4]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. **`to_list(self: PolyArray[Dim0]) → Poly`** **`to_list(self: PolyArray[Dim1]) → list[Poly]`** **`to_list(self: PolyArray[Dim2]) → list[list[Poly]]`** **`to_list(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`to_list(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`to_list(self: PolyArray[Dim]) → list`** Convert the polynomial array to nested Python lists. For 0D arrays, return the scalar polynomial itself. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`to_numpy(self) → numpy.ndarray[dtype=float64]`** Convert the polynomial array to a NumPy `float64` ndarray. **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`tolist(self: PolyArray[Dim0]) → Poly`** **`tolist(self: PolyArray[Dim1]) → list[Poly]`** **`tolist(self: PolyArray[Dim2]) → list[list[Poly]]`** **`tolist(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`tolist(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`tolist(self: PolyArray[Dim]) → list`** Alias of [`to_list()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`tonumpy(self) → numpy.ndarray[dtype=float64]`** Alias of [`to_numpy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`transpose(self, axes: tuple[int, ...] | None = None) → PolyArray[_Dim]`** **`transpose(self, *axes: int) → PolyArray[_Dim]`** Permute axes and return a transposed view. If `axes` is not specified, the axis order is reversed. Negative axes are supported and are normalized using the array dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axes (tuple[int, ...] | None): Axis permutation. If `None`, the axis order is reversed. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * \*axes (int): Axis permutation specified as positional arguments. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. **`view(self) → PolyArray[_Dim]`** Return a view of the same underlying data. **戻り値:** View of the same underlying data. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`property T`** A transposed view of the array. Equivalent to [`transpose()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) with default axis order. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__deprecated__ = 'BinaryPolyArray is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse PolyArray instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`__nb_signature__ = 'class PolyArray(typing.Generic[_Dim])'`** **`property flat`** A 1D view of the array. Unlike [`flatten()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.flatten), this property is a view. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property shape`** The shape of the array. Read this property to get the current shape as a tuple. Set this property to reshape the array in-place if the requested shape is compatible with the current size. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...] **`property size`** The total number of elements in the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) --- # IsingPolyArray **`class IsingPolyArray`** ベースクラス: [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) **Methods** | | | | --- | --- | | [`__init__`](#amplify.IsingPolyArray.__init__) | | | [`copy`](#amplify.IsingPolyArray.copy) | Return a copy of the array. | | [`decode`](#amplify.IsingPolyArray.decode) | Deprecated alias of [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate). | | [`diagonal`](#amplify.IsingPolyArray.diagonal) | Return a diagonal extracted from the array. | | [`evaluate`](#amplify.IsingPolyArray.evaluate) | Evaluate each element by substituting variable values. | | [`fill`](#amplify.IsingPolyArray.fill) | Fill all elements with a single polynomial or scalar value. | | [`flatten`](#amplify.IsingPolyArray.flatten) | Return a flattened 1D copy of the array. | | [`nonzero`](#amplify.IsingPolyArray.nonzero) | Return the indices of non-zero elements. | | [`ravel`](#amplify.IsingPolyArray.ravel) | Return a flattened 1D view when possible. | | [`repeat`](#amplify.IsingPolyArray.repeat) | Repeat elements of the array. | | [`reshape`](#amplify.IsingPolyArray.reshape) | Return a reshaped view of the array. | | [`roll`](#amplify.IsingPolyArray.roll) | Roll array elements along an axis. | | [`substitute`](#amplify.IsingPolyArray.substitute) | Substitute variables in all elements of the array. | | [`sum`](#amplify.IsingPolyArray.sum) | Sum array elements over the specified axis or axes. | | [`swapaxes`](#amplify.IsingPolyArray.swapaxes) | Return a view with two axes swapped. | | [`take`](#amplify.IsingPolyArray.take) | Take elements from the array along an axis. | | [`to_list`](#amplify.IsingPolyArray.to_list) | Convert the polynomial array to nested Python lists. | | [`to_numpy`](#amplify.IsingPolyArray.to_numpy) | Convert the polynomial array to a NumPy `float64` ndarray. | | [`tolist`](#amplify.IsingPolyArray.tolist) | Alias of [`to_list()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). | | [`tonumpy`](#amplify.IsingPolyArray.tonumpy) | Alias of [`to_numpy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). | | [`transpose`](#amplify.IsingPolyArray.transpose) | Permute axes and return a transposed view. | | [`view`](#amplify.IsingPolyArray.view) | Return a view of the same underlying data. | **Attributes** | | | | --- | --- | | [`T`](#amplify.IsingPolyArray.T) | A transposed view of the array. | | [`flat`](#amplify.IsingPolyArray.flat) | A 1D view of the array. | | [`ndim`](#amplify.IsingPolyArray.ndim) | The number of dimensions of the array. | | [`shape`](#amplify.IsingPolyArray.shape) | The shape of the array. | | [`size`](#amplify.IsingPolyArray.size) | The total number of elements in the array. | **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) → typing_extensions.Self`** **戻り値の型:** typing_extensions.Self **`__next__(self: Iterator[Dim1]) → Poly`** **`__next__(self: Iterator[Dim2]) → PolyArray[Dim1]`** **`__next__(self: Iterator[Dim3]) → PolyArray[Dim2]`** **`__next__(self: Iterator[Dim4]) → PolyArray[Dim3]`** **`__next__(self) → Poly | PolyArray[Dim]`** __next__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim1]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim2]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim3]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray.Iterator[Dim4]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 5.** > > **Returns:** > > Poly | PolyArray[Dim]: **`__nb_signature__ = 'class Iterator(typing.Generic[__Dim])'`** **`__add__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__add__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__add__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__add__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__add__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__add__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__and__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__and__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__and__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__and__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__and__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__and__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __and__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__bool__(self) → bool`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__copy__(self) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__deepcopy__(self, arg: dict, /) → PolyArray[_Dim]`** Copy the array. Each polynomial in the array is copied as well. Equivalent to [`copy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **パラメータ:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__eq__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__eq__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__float__(self) → float`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__getitem__(self: PolyArray[Dim0], arg: tuple[()]) → Poly`** **`__getitem__(self: PolyArray[Dim0], arg: EllipsisType) → PolyArray[Dim0]`** **`__getitem__(self: PolyArray[Dim1], arg: tuple[int] | int) → Poly`** **`__getitem__( self: PolyArray[Dim1], arg: EllipsisType | tuple[()] | slice | tuple[slice], ) → PolyArray[Dim1]`** **`__getitem__(self: PolyArray[Dim2], arg: tuple[int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim2], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim2], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice], ) → PolyArray[Dim2]`** **`__getitem__(self: PolyArray[Dim3], arg: tuple[int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim3], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim3], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim3], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__(self: PolyArray[Dim4], arg: tuple[int, int, int, int]) → Poly`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice], ) → PolyArray[Dim1]`** **`__getitem__( self: PolyArray[Dim4], arg: tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice], ) → PolyArray[Dim2]`** **`__getitem__( self: PolyArray[Dim4], arg: int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice], ) → PolyArray[Dim3]`** **`__getitem__( self: PolyArray[Dim4], arg: EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice], ) → PolyArray[Dim4]`** **`__getitem__(self: PolyArray[Dim], arg: tuple | slice | EllipsisType | int | None) → PolyArray[Dim]`** Return a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]): self > * arg (tuple[()]): An index specified as an integer, slice, ellipsis, or newaxis. > > **Returns:** > > amplify.Poly: Selected element or slice, depending on the index. > > **Raises:** > > IndexError: If any index is out of bounds. > TypeError: If index type is invalid. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (types.EllipsisType) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (tuple[int] | int) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (tuple[int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[slice, int, slice] | tuple[int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int, int]) > > **Returns:** > > amplify.Poly: > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int, int] | tuple[slice, int, int, int] | tuple[int, slice, int, int] | tuple[int, int, slice, int] | tuple[int, int, int, slice]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 14.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (tuple[int, int] | tuple[slice, int, int] | tuple[int, slice, int] | tuple[int, int, slice] | tuple[slice, slice, int, int] | tuple[slice, int, slice, int] | tuple[slice, int, int, slice] | tuple[int, slice, slice, int] | tuple[int, slice, int, slice] | tuple[int, int, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 15.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (int | tuple[int] | tuple[slice, int] | tuple[int, slice] | tuple[slice, slice, int] | tuple[int, slice, slice] | tuple[slice, int, slice] | tuple[slice, slice, slice, int] | tuple[slice, slice, int, slice] | tuple[slice, int, slice, slice] | tuple[int, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 16.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (types.EllipsisType | tuple[()] | slice | tuple[slice] | tuple[slice, slice] | tuple[slice, slice, slice] | tuple[slice, slice, slice, slice]) > > **Returns:** > > amplify.PolyArray[Dim4]: > [!NOTE] > > **Overload 17.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (tuple | slice | types.EllipsisType | int | None) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **サンプル** > > ```python > from amplify import VariableGenerator, newaxis > > q = VariableGenerator().array("Binary", (3, 4)) > print(q[1, 2]) # Output: Poly(q_{1,2}) > print(q[0]) # Output: PolyArray([q_{0,0}, q_{0,1}, q_{0,2}, q_{0,3}]) > print(q[:, 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[..., 0]) # Output: PolyArray([q_{0,0}, q_{1,0}, q_{2,0}]) > print(q[1, newaxis]) # Output: PolyArray([[q_{1,0}, q_{1,1}, q_{1,2}, q_{1,3}]]) > ``` **`__iadd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__iadd__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__iadd__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__iadd__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__iadd__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__iadd__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__iadd__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__iadd__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __iadd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__iand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__iand__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__iand__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__iand__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__iand__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __iand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__imul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__imul__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__imul__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__imul__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__imul__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__imul__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__imul__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__imul__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __imul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__index__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) → None`** **パラメータ:** **object** (*ndarray*) **`__int__(self) → int`** Cast a polynomial array to a number. This is valid only when the array has exactly one element and that element is a constant polynomial. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__ior__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ior__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ior__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ior__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ior__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ior__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ior__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ipow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__isub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__isub__(self, arg: list | ndarray[], /) → PolyArray[_Dim]`** **`__isub__(self: PolyArray[Dim], arg: PolyArray[__Dim]) → PolyArray[Dim]`** **`__isub__(self: PolyArray[Dim0], arg: PolyArray[Dim0]) → PolyArray[Dim0]`** **`__isub__(self: PolyArray[Dim1], arg: PolyArray[Dim0 | Dim1]) → PolyArray[Dim1]`** **`__isub__(self: PolyArray[Dim2], arg: PolyArray[Dim0 | Dim1 | Dim2]) → PolyArray[Dim2]`** **`__isub__(self: PolyArray[Dim3], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) → PolyArray[Dim3]`** **`__isub__(self: PolyArray[Dim4], arg: PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) → PolyArray[Dim4]`** __isub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[Dim0]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (PolyArray[Dim0 | Dim1]) > > **Returns:** > > amplify.PolyArray[Dim1]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (PolyArray[Dim0 | Dim1 | Dim2]) > > **Returns:** > > amplify.PolyArray[Dim2]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3]) > > **Returns:** > > amplify.PolyArray[Dim3]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (PolyArray[Dim0 | Dim1 | Dim2 | Dim3 | Dim4]) > > **Returns:** > > amplify.PolyArray[Dim4]: **`__iter__(self) → Iterator[_Dim]`** Iterate over the first axis of the polynomial array. If the array has one or fewer dimensions, each yielded item is a polynomial. If the array has two or more dimensions, each yielded item is a subarray with one fewer dimension. **戻り値の型:** [*Iterator*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__ixor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ixor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__ixor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__ixor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__ixor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__ixor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __ixor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__len__(self) → int`** Return the number of elements along the first axis. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__matmul__(self, arg: amplify.PolyArray | ndarray[], /) → Poly | PolyArray[_Dim]`** Perform matrix multiplication on two polynomial arrays. For arrays with three or more dimensions, the last two dimensions are treated as matrices and the remaining dimensions as batch dimensions. Broadcasting is applied to the batch dimensions. **パラメータ:** **arg** ([*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) *| ndarray*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__mul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__mul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__mul__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__mul__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__mul__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__mul__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__ne__(self, arg: amplify.PolyArray | amplify.Poly | float | int | list | ndarray[], /) → numpy.ndarray[dtype=bool]`** **`__ne__(self, arg: object, /) → bool`** Perform element-wise comparisons between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.PolyArray | amplify.Poly | float | int | list | ndarray) > > **Returns:** > > numpy.ndarray: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (object) > > **Returns:** > > bool: **`__neg__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__or__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__or__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__or__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__or__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__or__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__or__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __or__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__pos__(self) → PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) → PolyArray[_Dim]`** **パラメータ:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__radd__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__radd__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __radd__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rand__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rand__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rand__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__repr__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) → Poly | PolyArray[__Dim]`** **パラメータ:** **arg** (*NDArray |* [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)*[__Dim]*) **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[__Dim] **`__rmul__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rmul__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rmul__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__ror__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__ror__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __ror__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rsub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__rsub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** __rsub__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__rxor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__rxor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** __rxor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__setitem__( self, arg: tuple | slice | types.EllipsisType | int | None, value: amplify.Poly | float | int | list | ndarray[] | amplify.PolyArray, ) → None`** Assign a polynomial or a polynomial subarray. Supports indexing with integers, slices, ellipsis, and newaxis. Advanced indexing with arrays of indices is not supported. **パラメータ:** * **arg** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple) *|* [*slice*](https://docs.python.org/3/library/functions.html#slice) *|* [*EllipsisType*](https://docs.python.org/3/library/types.html#types.EllipsisType) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- An index specified as an integer, slice, ellipsis, or newaxis. * **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int) *|* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *| ndarray*) -- Value to assign, compatible with the indexed shape. **例外:** * [**IndexError**](https://docs.python.org/3/library/exceptions.html#IndexError) -- If any index is out of bounds. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) -- If index type is invalid or value shape is incompatible. **`__str__(self) → str`** **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly | float | int, /) → PolyArray[_Dim]`** **`__sub__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** **`__sub__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__sub__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__sub__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__sub__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`__truediv__(self, arg: float | int, /) → PolyArray[_Dim]`** **`__truediv__(self, arg: list | ndarray[], /) → PolyArray[Dim]`** Perform element-wise arithmetic between two polynomial arrays, or between a polynomial array and a scalar, using broadcasting rules. > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (float | int) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: **`__xor__(self, arg: Poly | bool, /) → PolyArray[_Dim]`** **`__xor__(self, arg: list | ndarray[dtype=bool], /) → PolyArray[Dim]`** **`__xor__(self, arg: PolyArray[Dim]) → PolyArray[Dim]`** **`__xor__(self: PolyArray[Dim0], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim0]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim1], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim1]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim2], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim2]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim3], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim3]) → PolyArray[_Dim]`** **`__xor__(self: PolyArray[Dim4], arg: PolyArray[__Dim]) → PolyArray[__Dim]`** **`__xor__(self, arg: PolyArray[Dim4]) → PolyArray[_Dim]`** __xor__ > [!NOTE] > > **Overload 1.** > > **Args:** > > * arg (amplify.Poly | bool) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 2.** > > **Args:** > > * arg (list | ndarray) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 3.** > > **Args:** > > * arg (amplify.PolyArray[Dim]) > > **Returns:** > > amplify.PolyArray[Dim]: > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg (amplify.PolyArray[Dim1]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 9.** > > **Args:** > > * arg (amplify.PolyArray[Dim2]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 11.** > > **Args:** > > * arg (amplify.PolyArray[Dim3]) > > **Returns:** > > amplify.PolyArray[_Dim]: > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > * arg (amplify.PolyArray[__Dim]) > > **Returns:** > > amplify.PolyArray[__Dim]: > [!NOTE] > > **Overload 13.** > > **Args:** > > * arg (amplify.PolyArray[Dim4]) > > **Returns:** > > amplify.PolyArray[_Dim]: **`copy(self) → PolyArray[_Dim]`** Return a copy of the array. Each polynomial in the array is copied as well. **戻り値:** Copy of the array. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`decode(self, values: Values) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`decode(self, values: Values, default: None) → PolyArray[_Dim]`** Deprecated alias of [`evaluate()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate). This method is deprecated since Amplify v1.0.0 and will be removed in a future version. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`diagonal(self: PolyArray[Dim], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim]`** **`diagonal(self: PolyArray[Dim2], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim1]`** **`diagonal(self: PolyArray[Dim3], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim2]`** **`diagonal(self: PolyArray[Dim4], offset: int = 0, axis1: int = 0, axis2: int = 1) → PolyArray[Dim3]`** Return a diagonal extracted from the array. Take the diagonal along `axis1` and `axis2` with optional `offset`. Unlike NumPy, return a copy. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim1]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim2]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * offset (int): Offset of the diagonal. Defaults to `0`. Defaults to `0`. > * axis1 (int): First axis. Defaults to `0`. Defaults to `0`. > * axis2 (int): Second axis. Defaults to `1`. Defaults to `1`. > > **Returns:** > > amplify.PolyArray[Dim3]: Diagonal extracted along the specified axes. > > **Raises:** > > ValueError: If axes are out of bounds or identical. **`evaluate(self, values: Values) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: float) → numpy.ndarray[dtype=float64]`** **`evaluate(self, values: Values, default: None) → PolyArray[_Dim]`** Evaluate each element by substituting variable values. Pass optimization result values to get a NumPy array with the same shape. The behavior for unassigned variables can be controlled by `default`. When `default=None`, keep variables not present in `values` symbolic and return a [`PolyArray`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray). > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (float): The default numeric value used for variables not present in `values`. > > **Returns:** > > numpy.ndarray: Evaluated numeric values with the same shape. > [!NOTE] > > **Overload 3.** > > **Args:** > > * values (amplify.Values): Values from optimization results, such as `result.best.values`. > * default (None): Set to `None` to keep unassigned variables symbolic. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with substitutions applied. **`fill(self, value: Poly | float | int) → None`** Fill all elements with a single polynomial or scalar value. **パラメータ:** **value** ([*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)) -- The value to assign to all elements. **`flatten(self) → PolyArray[Dim1]`** Return a flattened 1D copy of the array. **戻り値:** Flattened copy. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) → tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **戻り値:** Tuple of index arrays, one for each dimension. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)[dtype=uint64], ...] **`ravel(self) → PolyArray[Dim1]`** Return a flattened 1D view when possible. **戻り値:** Flattened view when possible. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`repeat(self, repeats: int | list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`repeat(self, repeats: int | list[int], axis: int) → PolyArray[_Dim]`** Repeat elements of the array. When `axis` is `None`, repetitions are applied to the flattened array, and a 1D array is returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (typing.Literal[None]): Axis along which to repeat. If `None`, the array is repeated as a flattened array. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * repeats (int | list[int]): The number of repetitions for each element, or a list of repetitions. > * axis (int): Axis along which to repeat. If `None`, the array is repeated as a flattened array. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with repeated elements. > > **Raises:** > > ValueError: If repeats contains negative values, axis is out of bounds, or shapes are incompatible. > TypeError: If repeats is not an integer or list of integers. **`reshape(self, shape: int | tuple[int]) → PolyArray[Dim1]`** **`reshape(self, shape: tuple[int, int]) → PolyArray[Dim2]`** **`reshape(self, shape: tuple[int, int, int]) → PolyArray[Dim3]`** **`reshape(self, shape: tuple[int, int, int, int]) → PolyArray[Dim4]`** **`reshape(self, arg0: int, arg1: int) → PolyArray[Dim2]`** **`reshape(self, arg0: int, arg1: int, arg2: int) → PolyArray[Dim3]`** **`reshape(self, arg0: int, arg1: int, arg2: int, arg3: int) → PolyArray[Dim4]`** **`reshape(self, shape: tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]) → PolyArray[Dim]`** **`reshape(self, *shape: int) → PolyArray[Dim]`** Return a reshaped view of the array. The new shape must be compatible with the current size. At most one `-1` is allowed to infer an unknown dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * shape (int | tuple[int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim1]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * shape (tuple[int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * shape (tuple[int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * shape (tuple[int, int, int, int]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim2]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim3]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * arg0 (int): First dimension of the new shape. > * arg1 (int): Second dimension of the new shape. > * arg2 (int): Third dimension of the new shape. > * arg3 (int): Fourth dimension of the new shape. > > **Returns:** > > amplify.PolyArray[Dim4]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * shape (tuple[int, int, int, int, int, typing_extensions.Unpack[tuple[int, ...]]]): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * \*shape (int): The new shape specified as a tuple. > > **Returns:** > > amplify.PolyArray[Dim]: Reshaped array. > > **Raises:** > > ValueError: If shape is incompatible with current size. > TypeError: If shape is not int/tuple of ints. **`roll(self, shift: int, axis: int | None = None) → PolyArray[_Dim]`** Roll array elements along an axis. If `axis` is `None`, the array is rolled in flattened order. Unlike NumPy, `roll` is provided as a method, and cannot roll multiple axes simultaneously. **パラメータ:** * **shift** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The shift amount. * **axis** ([*int*](https://docs.python.org/3/library/functions.html#int) *| None*) -- Axis to roll. If `None`, the array is rolled as a flattened array. Defaults to `None`. **戻り値:** Array with rolled elements. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If axis is out of bounds. **`substitute( self, mapping: Mapping[Poly, Poly | float | int] | Mapping[Variable, Poly | float | int], ) → PolyArray[_Dim]`** Substitute variables in all elements of the array. **パラメータ:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*] |* [*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Variable*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float) *|* [*int*](https://docs.python.org/3/library/functions.html#int)*]*) -- A mapping from variables to numeric values or polynomials. **戻り値:** Array after substitution. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`sum(self, axis: Literal[None] = None) → Poly`** **`sum(self: PolyArray[Dim1], axis: int | tuple[int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: tuple[int, int]) → Poly`** **`sum(self: PolyArray[Dim2], axis: int | tuple[int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int, int]) → Poly`** **`sum(self: PolyArray[Dim3], axis: tuple[int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim3], axis: int | tuple[int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int, int]) → Poly`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int, int]) → PolyArray[Dim1]`** **`sum(self: PolyArray[Dim4], axis: tuple[int, int]) → PolyArray[Dim2]`** **`sum(self: PolyArray[Dim4], axis: int | tuple[int]) → PolyArray[Dim3]`** **`sum(self: PolyArray[_Dim], axis: tuple[()]) → PolyArray[_Dim]`** **`sum(self: PolyArray[Dim], axis: int | tuple[int, ...]) → Poly | PolyArray[Dim]`** Sum array elements over the specified axis or axes. Without `axis`, all elements are summed into a single polynomial. With `axis`, the output type depends on the reduced dimensions. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axis (typing.Literal[None]): The axis or axes to reduce. Defaults to `None`. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.Poly: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim1]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 10.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (tuple[int, int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim2]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 11.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * axis (int | tuple[int]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[Dim3]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 12.** > > **Args:** > > * self (amplify.PolyArray[_Dim]): self > * axis (tuple[()]): The axis or axes to reduce. > > **Returns:** > > amplify.PolyArray[_Dim]: Summation result. Shape depends on `axis`. > [!NOTE] > > **Overload 13.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * axis (int | tuple[int, ...]): The axis or axes to reduce. > > **Returns:** > > Poly | PolyArray[Dim]: Summation result. Shape depends on `axis`. **`swapaxes(self, axis1: int, axis2: int) → PolyArray[_Dim]`** Return a view with two axes swapped. **パラメータ:** * **axis1** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The first axis. * **axis2** ([*int*](https://docs.python.org/3/library/functions.html#int)) -- The second axis. **戻り値:** Array with the two axes swapped. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **例外:** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) -- If either axis is out of bounds. **`take(self, indices: int, axis: Literal[None] = None) → Poly`** **`take(self, indices: list[int], axis: Literal[None] = None) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim], indices: int | list[int], axis: int | None = None) → PolyArray[Dim]`** **`take(self: PolyArray[Dim2], indices: int, axis: int) → PolyArray[Dim1]`** **`take(self: PolyArray[Dim2], indices: list[int], axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: int, axis: int) → PolyArray[Dim2]`** **`take(self: PolyArray[Dim3], indices: list[int], axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: int, axis: int) → PolyArray[Dim3]`** **`take(self: PolyArray[Dim4], indices: list[int], axis: int) → PolyArray[Dim4]`** Take elements from the array along an axis. If `axis` is `None`, indices are interpreted on the flattened array. Elements are always copied, even when a view could be returned. > [!NOTE] > > **Overload 1.** > > **Args:** > > * indices (int): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.Poly: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 2.** > > **Args:** > > * indices (list[int]): A single index or a list of indices. > * axis (typing.Literal[None]): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim]): self > * indices (int | list[int]): A single index or a list of indices. > * axis (int | None): Axis to take from. If `None`, flattened indexing is used. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[Dim]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim1]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim2]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim2]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 7.** > > **Args:** > > * self (amplify.PolyArray[Dim3]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 8.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (int): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim3]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. > [!NOTE] > > **Overload 9.** > > **Args:** > > * self (amplify.PolyArray[Dim4]): self > * indices (list[int]): A single index or a list of indices. > * axis (int): Axis to take from. If `None`, flattened indexing is used. > > **Returns:** > > amplify.PolyArray[Dim4]: Selected elements. Shape depends on `indices` and `axis`. > > **Raises:** > > IndexError: If any index is out of bounds. > ValueError: If axis is out of bounds. > TypeError: If indices is not int or list of ints. **`to_list(self: PolyArray[Dim0]) → Poly`** **`to_list(self: PolyArray[Dim1]) → list[Poly]`** **`to_list(self: PolyArray[Dim2]) → list[list[Poly]]`** **`to_list(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`to_list(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`to_list(self: PolyArray[Dim]) → list`** Convert the polynomial array to nested Python lists. For 0D arrays, return the scalar polynomial itself. > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`to_numpy(self) → numpy.ndarray[dtype=float64]`** Convert the polynomial array to a NumPy `float64` ndarray. **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`tolist(self: PolyArray[Dim0]) → Poly`** **`tolist(self: PolyArray[Dim1]) → list[Poly]`** **`tolist(self: PolyArray[Dim2]) → list[list[Poly]]`** **`tolist(self: PolyArray[Dim3]) → list[list[list[Poly]]]`** **`tolist(self: PolyArray[Dim4]) → list[list[list[list[Poly]]]]`** **`tolist(self: PolyArray[Dim]) → list`** Alias of [`to_list()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). > [!NOTE] > > **Overload 1.** > > **Args:** > > * self (amplify.PolyArray[Dim0]) > > **Returns:** > > amplify.Poly: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 2.** > > **Args:** > > * self (amplify.PolyArray[Dim1]) > > **Returns:** > > list[amplify.Poly]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 3.** > > **Args:** > > * self (amplify.PolyArray[Dim2]) > > **Returns:** > > list[list[amplify.Poly]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 4.** > > **Args:** > > * self (amplify.PolyArray[Dim3]) > > **Returns:** > > list[list[list[amplify.Poly]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 5.** > > **Args:** > > * self (amplify.PolyArray[Dim4]) > > **Returns:** > > list[list[list[list[amplify.Poly]]]]: Nested representation of elements, or the scalar polynomial itself for 0D arrays. > [!NOTE] > > **Overload 6.** > > **Args:** > > * self (amplify.PolyArray[Dim]) > > **Returns:** > > list: Nested representation of elements, or the scalar polynomial itself for 0D arrays. **`tonumpy(self) → numpy.ndarray[dtype=float64]`** Alias of [`to_numpy()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). **戻り値:** Converted NumPy array. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`transpose(self, axes: tuple[int, ...] | None = None) → PolyArray[_Dim]`** **`transpose(self, *axes: int) → PolyArray[_Dim]`** Permute axes and return a transposed view. If `axes` is not specified, the axis order is reversed. Negative axes are supported and are normalized using the array dimension. > [!NOTE] > > **Overload 1.** > > **Args:** > > * axes (tuple[int, ...] | None): Axis permutation. If `None`, the axis order is reversed. Defaults to `None`. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. > [!NOTE] > > **Overload 2.** > > **Args:** > > * \*axes (int): Axis permutation specified as positional arguments. > > **Returns:** > > amplify.PolyArray[_Dim]: Array with permuted axes. > > **Raises:** > > ValueError: If any axis is out of bounds or permutation is invalid. > TypeError: If axes is not a tuple of integers. **`view(self) → PolyArray[_Dim]`** Return a view of the same underlying data. **戻り値:** View of the same underlying data. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`property T`** A transposed view of the array. Equivalent to [`transpose()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) with default axis order. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__deprecated__ = 'IsingPolyArray is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse PolyArray instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`__nb_signature__ = 'class PolyArray(typing.Generic[_Dim])'`** **`property flat`** A 1D view of the array. Unlike [`flatten()`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.flatten), this property is a view. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property shape`** The shape of the array. Read this property to get the current shape as a tuple. Set this property to reshape the array in-place if the requested shape is compatible with the current size. **戻り値の型:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*int*](https://docs.python.org/3/library/functions.html#int), ...] **`property size`** The total number of elements in the array. **戻り値の型:** [*int*](https://docs.python.org/3/library/functions.html#int) --- # BinarySymbolGenerator **`class BinarySymbolGenerator`** **Methods** | | | | --- | --- | | [`__init__`](#amplify.BinarySymbolGenerator.__init__) | | | [`array`](#amplify.BinarySymbolGenerator.array) | | | [`matrix`](#amplify.BinarySymbolGenerator.matrix) | | | [`scalar`](#amplify.BinarySymbolGenerator.scalar) | | **Attributes** | | | | --- | --- | | [`variables`](#amplify.BinarySymbolGenerator.variables) | | **`__init__()`** **`array(*args, **kwargs)`** **`matrix(*args, **kwargs)`** **`scalar(*args, **kwargs)`** **`__deprecated__ = 'BinarySymbolGenerator is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse VariableGenerator instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property variables`** --- # IsingSymbolGenerator **`class IsingSymbolGenerator`** **Methods** | | | | --- | --- | | [`__init__`](#amplify.IsingSymbolGenerator.__init__) | | | [`array`](#amplify.IsingSymbolGenerator.array) | | | [`matrix`](#amplify.IsingSymbolGenerator.matrix) | | | [`scalar`](#amplify.IsingSymbolGenerator.scalar) | | **Attributes** | | | | --- | --- | | [`variables`](#amplify.IsingSymbolGenerator.variables) | | **`__init__()`** **`array(*args, **kwargs)`** **`matrix(*args, **kwargs)`** **`scalar(*args, **kwargs)`** **`__deprecated__ = 'IsingSymbolGenerator is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse VariableGenerator instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property variables`** --- # BinaryMatrix **`class BinaryMatrix`** ベースクラス: [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) **Methods** | | | | --- | --- | | [`__init__`](#amplify.BinaryMatrix.__init__) | | | [`evaluate`](#amplify.BinaryMatrix.evaluate) | Evaluate the matrix objective using the provided variable assignments. | | [`to_poly`](#amplify.BinaryMatrix.to_poly) | Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). | **Attributes** | | | | --- | --- | | [`constant`](#amplify.BinaryMatrix.constant) | Constant term `c`. | | [`linear`](#amplify.BinaryMatrix.linear) | Linear coefficient array `p`. | | [`quadratic`](#amplify.BinaryMatrix.quadratic) | Quadratic coefficient array `Q`. | | [`variable_array`](#amplify.BinaryMatrix.variable_array) | Variable array `x` used in the matrix representation. | **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) → str`** Return a developer-friendly string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** Return a human-readable string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** Evaluate the matrix objective using the provided variable assignments. Substitute variables in `x` with the given `values` and evaluate `x^\top Q x + p^\top x + c`. If `default` is not specified, variables not included in `values` are substituted with a reasonable default value. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: Evaluated objective value. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > * default (float): Default value used for variables not included in `values`. > > **Returns:** > > float: Evaluated objective value. **`to_poly(self) → Poly`** Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **戻り値:** Polynomial converted from this matrix form. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__deprecated__ = 'BinaryMatrix is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Matrix instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property constant`** Constant term `c`. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`property linear`** Linear coefficient array `p`. For a variable array `x` with `n` dimensions, the linear coefficient array `p` also has `n` dimensions. When `x` is one-dimensional, `p` is a 1D vector. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property quadratic`** Quadratic coefficient array `Q`. For a variable array `x` with `n` dimensions, the quadratic coefficient array `Q` has `2n` dimensions. When `x` is one-dimensional, `Q` is a 2D matrix. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property variable_array`** Variable array `x` used in the matrix representation. Use this array when constructing constraints for a matrix objective. **戻り値:** Variable array used in this representation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] --- # IsingMatrix **`class IsingMatrix`** ベースクラス: [`Matrix`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) **Methods** | | | | --- | --- | | [`__init__`](#amplify.IsingMatrix.__init__) | | | [`evaluate`](#amplify.IsingMatrix.evaluate) | Evaluate the matrix objective using the provided variable assignments. | | [`to_poly`](#amplify.IsingMatrix.to_poly) | Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). | **Attributes** | | | | --- | --- | | [`constant`](#amplify.IsingMatrix.constant) | Constant term `c`. | | [`linear`](#amplify.IsingMatrix.linear) | Linear coefficient array `p`. | | [`quadratic`](#amplify.IsingMatrix.quadratic) | Quadratic coefficient array `Q`. | | [`variable_array`](#amplify.IsingMatrix.variable_array) | Variable array `x` used in the matrix representation. | **`__add__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) → bool`** **パラメータ:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **戻り値の型:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) → Model`** Create a [`Model`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **パラメータ:** **arg** ([*Constraint*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) -- Constraints to include. **戻り値:** Model containing this objective and the given constraints. **戻り値の型:** [*Model*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) → str`** Return a developer-friendly string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) → str`** Return a human-readable string representation of the matrix form. **戻り値の型:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`evaluate(self, values: Values) → float`** **`evaluate(self, values: Values, default: float) → float`** Evaluate the matrix objective using the provided variable assignments. Substitute variables in `x` with the given `values` and evaluate `x^\top Q x + p^\top x + c`. If `default` is not specified, variables not included in `values` are substituted with a reasonable default value. > [!NOTE] > > **Overload 1.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > > **Returns:** > > float: Evaluated objective value. > [!NOTE] > > **Overload 2.** > > **Args:** > > * values (amplify.Values): Variable values obtained from optimization results, e.g. `result.best.values`. > * default (float): Default value used for variables not included in `values`. > > **Returns:** > > float: Evaluated objective value. **`to_poly(self) → Poly`** Convert this matrix form to [`Poly`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **戻り値:** Polynomial converted from this matrix form. **戻り値の型:** [*Poly*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__deprecated__ = 'IsingMatrix is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Matrix instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property constant`** Constant term `c`. **戻り値の型:** [*float*](https://docs.python.org/3/library/functions.html#float) **`property linear`** Linear coefficient array `p`. For a variable array `x` with `n` dimensions, the linear coefficient array `p` also has `n` dimensions. When `x` is one-dimensional, `p` is a 1D vector. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property quadratic`** Quadratic coefficient array `Q`. For a variable array `x` with `n` dimensions, the quadratic coefficient array `Q` has `2n` dimensions. When `x` is one-dimensional, `Q` is a 2D matrix. **戻り値の型:** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) **`property variable_array`** Variable array `x` used in the matrix representation. Use this array when constructing constraints for a matrix objective. **戻り値:** Variable array used in this representation. **戻り値の型:** [*PolyArray*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] --- # QuadraticModel **`class QuadraticModel`** ベースクラス: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC) **Methods** | | | | --- | --- | | [`__init__`](#amplify.QuadraticModel.__init__) | | | [`check_constraints`](#amplify.QuadraticModel.check_constraints) | | **Attributes** | | | | --- | --- | | [`input_constraints`](#amplify.QuadraticModel.input_constraints) | | | [`input_matrix`](#amplify.QuadraticModel.input_matrix) | | | [`input_poly`](#amplify.QuadraticModel.input_poly) | | | [`logical_mapping`](#amplify.QuadraticModel.logical_mapping) | | | [`logical_matrix`](#amplify.QuadraticModel.logical_matrix) | | | [`logical_model_matrix`](#amplify.QuadraticModel.logical_model_matrix) | | | [`logical_model_poly`](#amplify.QuadraticModel.logical_model_poly) | | | [`logical_poly`](#amplify.QuadraticModel.logical_poly) | | | [`num_input_vars`](#amplify.QuadraticModel.num_input_vars) | | | [`num_logical_vars`](#amplify.QuadraticModel.num_logical_vars) | | | [`substitution_multiplier`](#amplify.QuadraticModel.substitution_multiplier) | | **`__add__(arg: Constraint | ConstraintList)`** **`__iadd__(arg: Constraint | ConstraintList)`** **`__init__( arg0: Poly, arg1: Constraint | ConstraintList | None = None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD, )`** **`__init__( arg0: Matrix, arg1: Constraint | ConstraintList | None = None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD, )`** **`__init__(arg0: Model, arg1=None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD)`** **`__init__( arg0: Constraint | ConstraintList, arg1=None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD, )`** **`__radd__(arg: Constraint | ConstraintList)`** **`check_constraints(values: Values) → list[tuple[Constraint, bool]]`** **`property input_constraints: ConstraintList`** **`property input_matrix: Matrix | None`** **`property input_poly: Poly | None`** **`property logical_mapping: IntermediateMapping`** **`property logical_matrix: Matrix | None`** **`property logical_model_matrix`** **`property logical_model_poly: Poly`** **`property logical_poly: Poly | None`** **`property num_input_vars: int`** **`property num_logical_vars: int`** **`property substitution_multiplier: float`** --- # BinaryQuadraticModel **`class BinaryQuadraticModel`** ベースクラス: [`QuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md#amplify.QuadraticModel) **Methods** | | | | --- | --- | | [`__init__`](#amplify.BinaryQuadraticModel.__init__) | | | [`check_constraints`](#amplify.BinaryQuadraticModel.check_constraints) | | **Attributes** | | | | --- | --- | | [`input_constraints`](#amplify.BinaryQuadraticModel.input_constraints) | | | [`input_matrix`](#amplify.BinaryQuadraticModel.input_matrix) | | | [`input_poly`](#amplify.BinaryQuadraticModel.input_poly) | | | [`logical_mapping`](#amplify.BinaryQuadraticModel.logical_mapping) | | | [`logical_matrix`](#amplify.BinaryQuadraticModel.logical_matrix) | | | [`logical_model_matrix`](#amplify.BinaryQuadraticModel.logical_model_matrix) | | | [`logical_model_poly`](#amplify.BinaryQuadraticModel.logical_model_poly) | | | [`logical_poly`](#amplify.BinaryQuadraticModel.logical_poly) | | | [`num_input_vars`](#amplify.BinaryQuadraticModel.num_input_vars) | | | [`num_logical_vars`](#amplify.BinaryQuadraticModel.num_logical_vars) | | | [`substitution_multiplier`](#amplify.BinaryQuadraticModel.substitution_multiplier) | | **`__add__(arg: Constraint | ConstraintList)`** **`__iadd__(arg: Constraint | ConstraintList)`** **`__init__(arg0, arg1=None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD)`** **`__radd__(arg: Constraint | ConstraintList)`** **`check_constraints(values: Values) → list[tuple[Constraint, bool]]`** **`__deprecated__ = 'BinaryQuadraticModel is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Model instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property input_constraints: ConstraintList`** **`property input_matrix: Matrix | None`** **`property input_poly: Poly | None`** **`property logical_mapping: IntermediateMapping`** **`property logical_matrix: Matrix | None`** **`property logical_model_matrix`** **`property logical_model_poly: Poly`** **`property logical_poly: Poly | None`** **`property num_input_vars: int`** **`property num_logical_vars: int`** **`property substitution_multiplier: float`** --- # IsingQuadraticModel **`class IsingQuadraticModel`** ベースクラス: [`QuadraticModel`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md#amplify.QuadraticModel) **Methods** | | | | --- | --- | | [`__init__`](#amplify.IsingQuadraticModel.__init__) | | | [`check_constraints`](#amplify.IsingQuadraticModel.check_constraints) | | **Attributes** | | | | --- | --- | | [`input_constraints`](#amplify.IsingQuadraticModel.input_constraints) | | | [`input_matrix`](#amplify.IsingQuadraticModel.input_matrix) | | | [`input_poly`](#amplify.IsingQuadraticModel.input_poly) | | | [`logical_mapping`](#amplify.IsingQuadraticModel.logical_mapping) | | | [`logical_matrix`](#amplify.IsingQuadraticModel.logical_matrix) | | | [`logical_model_matrix`](#amplify.IsingQuadraticModel.logical_model_matrix) | | | [`logical_model_poly`](#amplify.IsingQuadraticModel.logical_model_poly) | | | [`logical_poly`](#amplify.IsingQuadraticModel.logical_poly) | | | [`num_input_vars`](#amplify.IsingQuadraticModel.num_input_vars) | | | [`num_logical_vars`](#amplify.IsingQuadraticModel.num_logical_vars) | | | [`substitution_multiplier`](#amplify.IsingQuadraticModel.substitution_multiplier) | | **`__add__(arg: Constraint | ConstraintList)`** **`__iadd__(arg: Constraint | ConstraintList)`** **`__init__(arg0, arg1=None, *, method: QuadratizationMethod = QuadratizationMethod.IshikawaKZFD)`** **`__radd__(arg: Constraint | ConstraintList)`** **`check_constraints(values: Values) → list[tuple[Constraint, bool]]`** **`__deprecated__ = 'IsingQuadraticModel is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse Model instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property input_constraints: ConstraintList`** **`property input_matrix: Matrix | None`** **`property input_poly: Poly | None`** **`property logical_mapping: IntermediateMapping`** **`property logical_matrix: Matrix | None`** **`property logical_model_matrix`** **`property logical_model_poly: Poly`** **`property logical_poly: Poly | None`** **`property num_input_vars: int`** **`property num_logical_vars: int`** **`property substitution_multiplier: float`** --- # Solver **`class Solver`** **Methods** | | | | --- | --- | | [`__init__`](#amplify.Solver.__init__) | | | [`solve`](#amplify.Solver.solve) | | **Attributes** | | | | --- | --- | | [`chain_strength`](#amplify.Solver.chain_strength) | | | [`client`](#amplify.Solver.client) | | | [`client_result`](#amplify.Solver.client_result) | | | [`deduplicate`](#amplify.Solver.deduplicate) | | | [`embedding_time_limit`](#amplify.Solver.embedding_time_limit) | | | [`execution_time`](#amplify.Solver.execution_time) | | | [`filter_solution`](#amplify.Solver.filter_solution) | | | [`logical_result`](#amplify.Solver.logical_result) | | | [`sort_solution`](#amplify.Solver.sort_solution) | | **`__init__(client)`** **`solve(arg) → SolverResult`** **`__deprecated__ = 'Solver is deprecated since amplify v1.0.0 and will no longer support in the near future.\nUse solve() instead. Please see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property chain_strength`** **`property client`** **`property client_result`** **`property deduplicate`** **`property embedding_time_limit`** **`property execution_time`** **`property filter_solution`** **`property logical_result`** **`property sort_solution`** --- # SolverResult **`class SolverResult`** ベースクラス: [`UserList`](https://docs.python.org/3/library/collections.html#collections.UserList) **Methods** | | | | --- | --- | | [`__init__`](#amplify.SolverResult.__init__) | | | [`append`](#amplify.SolverResult.append) | S.append(value) -- append value to the end of the sequence | | [`clear`](#amplify.SolverResult.clear) | | | [`copy`](#amplify.SolverResult.copy) | | | [`count`](#amplify.SolverResult.count) | | | [`extend`](#amplify.SolverResult.extend) | S.extend(iterable) -- extend sequence by appending elements from the iterable | | [`index`](#amplify.SolverResult.index) | Raises ValueError if the value is not present. | | [`insert`](#amplify.SolverResult.insert) | S.insert(index, value) -- insert value before index | | [`pop`](#amplify.SolverResult.pop) | Raise IndexError if list is empty or index is out of range. | | [`remove`](#amplify.SolverResult.remove) | S.remove(value) -- remove first occurrence of value. | | [`reverse`](#amplify.SolverResult.reverse) | S.reverse() -- reverse *IN PLACE* | | [`sort`](#amplify.SolverResult.sort) | | **Attributes** | | | | --- | --- | | [`solutions`](#amplify.SolverResult.solutions) | | **`__add__(other)`** **`__contains__(item)`** **`__copy__()`** **`__delitem__(i)`** **`__eq__(other)`** Return self==value. **`__ge__(other)`** Return self>=value. **`__getitem__(i)`** **`__gt__(other)`** Return self>value. **`__iadd__(other)`** **`__imul__(n)`** **`__init__(*args, **kwargs)`** **`__iter__()`** **`__le__(other)`** Return self<=value. **`__len__()`** **`__lt__(other)`** Return self **`__mul__(n)`** **`__radd__(other)`** **`__repr__()`** Return repr(self). **`__reversed__()`** **`__rmul__(n)`** **`__setitem__(i, item)`** **`append(item)`** S.append(value) -- append value to the end of the sequence **`clear() → None -- remove all items from S`** **`copy()`** **`count(value) → integer -- return number of occurrences of value`** **`extend(other)`** S.extend(iterable) -- extend sequence by appending elements from the iterable **`index(value[, start[, stop]]) → integer -- return first index of value.`** Raises ValueError if the value is not present. Supporting start and stop arguments is optional, but recommended. **`insert(i, item)`** S.insert(index, value) -- insert value before index **`pop([index]) → item -- remove and return item at index (default last).`** Raise IndexError if list is empty or index is out of range. **`remove(item)`** S.remove(value) -- remove first occurrence of value. Raise ValueError if the value is not present. **`reverse()`** S.reverse() -- reverse *IN PLACE* **`sort(*args, **kwds)`** **`__deprecated__ = 'SolverResult is deprecated since amplify v1.0.0 and will no longer support in the near future.\nPlease see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`__hash__ = None`** **`property solutions: list[SolverSolution]`** --- # SolverSolution **`class SolverSolution`** **Methods** | | | | --- | --- | | [`__init__`](#amplify.SolverSolution.__init__) | | **Attributes** | | | | --- | --- | | [`energy`](#amplify.SolverSolution.energy) | | | [`frequency`](#amplify.SolverSolution.frequency) | | | [`is_feasible`](#amplify.SolverSolution.is_feasible) | | | [`values`](#amplify.SolverSolution.values) | | **`__init__(energy, is_feasible, values)`** **`__deprecated__ = 'SolverSolution is deprecated since amplify v1.0.0 and will no longer support in the near future.\nPlease see the migration guide for details: https://amplify.fixstars.com/docs/amplify/v1/migration.html'`** **`property energy`** **`property frequency`** **`property is_feasible`** **`property values`** --- # SymbolGenerator **`SymbolGenerator(arg=None) → VariableGenerator | BinarySymbolGenerator | IsingSymbolGenerator`** --- # sum_poly **`sum_poly(*args, **kwargs)`** --- # decode_solution **`decode_solution(array: PolyArray, solution: Values)`** --- # penalty **`penalty(poly: Poly, eq=None, le=None, ge=None, label='')`** alias of constructor of [`Constraint`](https://amplify.fixstars.com/ja/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) --- # InequalityFormulation **`class InequalityFormulation`** ベースクラス: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) An enumeration. **Members** **`Binary = PenaltyFormulation.Default`** **`Default = PenaltyFormulation.Default`** **`Linear = PenaltyFormulation.Default`** **`Relaxation = PenaltyFormulation.Relaxation`** **`RelaxationLinear = PenaltyFormulation.LinearRelaxation`** **`RelaxationQuadra = PenaltyFormulation.QuadraticRelaxation`** **`Unary = PenaltyFormulation.Default`** --- 入力できる問題の変数型や次数は、選択したアルゴリズムに依存します。 * クライアントの引数で [QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | \*\* | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。 \*\*: [QAOA の種別](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype) で [制約付き QAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md)が選ばれた場合 N-HOT 制約に対応しています。 * クライアントの引数で [RQAOA](https://amplify.fixstars.com/ja/docs/amplify/v1/quantum/algos/RQAOA.md) が設定されている場合 | | バイナリ変数 | イジング変数 | 整数変数 | 実数変数 | | --- | --- | --- | --- | --- | | 目的関数 | - | N次\* | - | - | | 等式制約 | - | - | - | - | | 不等式制約 | - | - | - | - | \*: 任意次数の問題を求解できます。ただし、量子コンピュータのビットの接続によっては必要な量子ビットが増えることがあります。