# Fixstars Amplify SDK documentation > The Fixstars Amplify SDK (Amplify SDK) is a Python library for formulating combinatorial optimization problems and running external optimization solvers. This file holds every page of the documentation, in the order of the index at . A comment gives the address of the page that follows it, and a horizontal rule separates one page from the next. --- # Fixstars Amplify SDK documentation This is the Markdown edition of the documentation. It holds the same content as the HTML edition at , and it exists so that an AI agent can read the documentation without the markup of a web page. Every page below is a Markdown file, and every link inside those pages points to another Markdown file. `llms.txt` holds this index with absolute addresses, and `llms-full.txt` holds every page in one file. [![Fixstars Amplify](https://amplify.fixstars.com/en/docs/amplify/v1/_images/amplify-logo.svg)](https://amplify.fixstars.com/en/) [![Fixstars Amplify](https://amplify.fixstars.com/en/docs/amplify/v1/_images/amplify-logo-dark.svg)](https://amplify.fixstars.com/en/) [![Fixstars Amplify](https://img.shields.io/badge/-Fixstars%20Amplify-333333.svg)](https://amplify.fixstars.com/en/) [![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) The *Fixstars Amplify SDK* (Amplify SDK) is a Python library for formulating combinatorial optimization problems and running external optimization solvers. The Amplify SDK provides a simple and intuitive way to formulate combinatorial optimization problems. Once the problem is formulated, you can easily use [quantum annealing machines](https://en.wikipedia.org/wiki/Quantum_annealing), Ising machines, [quantum computers](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/index.md), and various hardware and software solvers including MIP solvers, through a common interface. --- **Amplify SDK features** **πŸ”° Intuitive and easy to use** The easiest and most intuitive library to formulate and solve combinatorial optimization problems! [Amplify Annealing Engine](https://amplify.fixstars.com/en/engine), a solver that requires no further installation, is also provided free of charge. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#easy-to-use) **⚑ Fast processing speed** The Amplify SDK is extremely fast and memory-efficient in formulation. You can develop applications for large combinatorial optimization problems. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#blazing-fast) **πŸ”±οΈ Multiple solver support** A wide range of solvers are available in the Amplify SDK, including quantum annealing machines, Ising machines, quantum computers, and MIP solvers. You can choose the solver that best suits your problems. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#multiple-solvers) **πŸ§‘β€πŸ’»οΈ For broad users** The Amplify SDK can be used by a wide range of users engaged in combinatorial optimization. It is designed to support a variety of user groups, from application software development to academic research. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#wide-range-users) > [!NOTE] > > **Changed in version 1.0.0** > > *The Fixstars Amplify SDK* has undergone a significant makeover in version 1.0.0, making it more intuitive and easier to use than ever before, expanding the models covered, and making it more flexible and faster. For a migration guide from previous versions, see [Migrating from Previous Versions](https://amplify.fixstars.com/en/docs/amplify/v1/migration.md). A compatibility layer with the earlier version is also provided to ensure a smooth transition. > You can find documentation for previous versions at . --- **How to get started with Amplify** **πŸ†” STEP 1** [**User Registration**](https://amplify.fixstars.com/en/register) Register as a user and get a free API token for the [Amplify Annealing Engine](https://amplify.fixstars.com/en/engine) ! **πŸ› οΈ STEP 2** [Installation](https://amplify.fixstars.com/en/docs/amplify/v1/quickstart.md) Install the Amplify SDK using the pip command on Windows / Linux / MacOS! **πŸ” STEP 3** [**Demos & Tutorials**](https://amplify.fixstars.com/en/demo) Check out the extensive demos and tutorials to learn how to use Amplify! > [!NOTE] > > **Note** > > *The Fixstars Amplify SDK* is proprietary software. > It is free for non-commercial and academic use. See [Fixstars Amplify Terms of Service](https://amplify.fixstars.com/en/termsofuse) for more information. > When citing in an academic publication, please use the BibTeX formats below. > > * 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/en/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/en/docs/amplify/v1/_downloads/fa40222046f6d5b3cc720832fc4384a9/citation_ae.bib) > * Fixstars Amplify > > Please use this if you want to cite both the Fixsatrs Amplify SDK and AE together. > > ``` > @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/en/docs/amplify/v1/_downloads/586ec087abf5502e07c22b264faf8aeb/citation_amplify.bib) ## Table of contents ### πŸš€ Get Started * [What is Amplify SDK?](https://amplify.fixstars.com/en/docs/amplify/v1/index.md) β€” The Fixstars Amplify SDK (Amplify SDK) is a Python library for formulating combinatorial optimization problems and running external optimization solvers. * [Amplify SDK Features](https://amplify.fixstars.com/en/docs/amplify/v1/features.md) β€” The Amplify SDK aims to formulate combinatorial optimization problems in a simple and intuitive way and solve them using a variety of machines and solvers. To… * [Quickstart](https://amplify.fixstars.com/en/docs/amplify/v1/quickstart.md) β€” You can run the Amplify SDK in any of the following ways. ### 🌱 Basic * [1. Amplify SDK Overview](https://amplify.fixstars.com/en/docs/amplify/v1/overview.md) β€” Before we go into the functionality details, let us summarize the overall picture and execution flow of the Amplify SDK. * [2. Creating Decision Variables](https://amplify.fixstars.com/en/docs/amplify/v1/variables.md) β€” You must express the problem formulation in the program code to solve a combinatorial optimization problem with Amplify SDK. This page describes the first step… * [3. Polynomials and Objective Functions](https://amplify.fixstars.com/en/docs/amplify/v1/objective.md) β€” The objective function is a mathematical expression expressing the degree to which the objective in a combinatorial optimization problem is achieved; in the… * [4. Constructing Constraints](https://amplify.fixstars.com/en/docs/amplify/v1/constraint.md) β€” Constraints are the conditions that must be satisfied by the values of the decision variables in a combinatorial optimization problem. In the Amplify SDK you… * [5. Model Formulation](https://amplify.fixstars.com/en/docs/amplify/v1/model.md) β€” A combinatorial optimization problem comprises decision variables, objective functions, and constraints. In β€œ2. Creating Decision Variables,” β€œ3. Polynomials… * [6. Solver Client](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md) β€” To run a solver from the Amplify SDK, you must create a solver client that abstracts each solver and specifies the connection point, API token, and execution… * [7. Solving a Combinatorial Optimization Problem](https://amplify.fixstars.com/en/docs/amplify/v1/solve.md) β€” This page explains how to solve a combinatorial optimization problem using the model Model and solver client created in β€œModel Formulation” and β€œSolver Client.” ### 🌻 Advanced * [Model Conversions](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md) β€” The Amplify SDK allows you to create models that contain real and integer variables and polynomials of any degree. On the other hand, combinatorial… * [Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md) β€” The Amplify SDK allows you to create models that include real and integer variables and polynomials of any degree. On the other hand, combinatorial… * [Constraints and Penalty Functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md) β€” The Amplify SDK allows you to create models with any variable and polynomial degree constraints. However, each combinatorial optimization solver handles… * [Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md) β€” Some QUBO and Ising solvers do not accept arbitrary second-order polynomials and are limited in the number of second-order terms that you can pass to the… * [Evaluation of Execution Results](https://amplify.fixstars.com/en/docs/amplify/v1/evaluation.md) β€” The execution result returned by the solve() function contains various information about the solutions, model conversion, and execution time. This page… * [Execution Time information](https://amplify.fixstars.com/en/docs/amplify/v1/timing.md) β€” The Amplify SDK provides an interface to obtain information of various execution times when solving combinatorial optimization problems. * [Client details](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md) β€” The Amplify SDK provides client classes for the solvers that you can run from the SDK. The client classes wrap each solver’s API and provide an interface for… * [Fixstars Amplify](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md) β€” Fixstars Amplify Annealing Engine (Amplify AE) is a solver provided by Fixstars Amplify. It uses heuristic algorithms based on simulated annealing on GPUs,… * [D-Wave Systems](https://amplify.fixstars.com/en/docs/amplify/v1/clients/dwave.md) β€” D-Wave Systems offers a quantum annealing machine (quantum processing unit; QPU) that allows you to input QUBO or a combinatorial optimization problem… * [TOSHIBA](https://amplify.fixstars.com/en/docs/amplify/v1/clients/toshiba.md) β€” SQBM+ is a TOSHIBA-developed quantum-inspired optimization solution with a simulated bifurcation machine at its core. * [Fujitsu](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fujitsu.md) β€” Fujitsu DA4 is Fujitsu’s QUBO solver with the 4th-generation Digital Annealing Unit (DAU (GPU)). * [NEC](https://amplify.fixstars.com/en/docs/amplify/v1/clients/nec.md) β€” NEC provides the QUBO solver, which runs on the vector supercomputer SX-Aurora TSUBASA. * [Hitachi](https://amplify.fixstars.com/en/docs/amplify/v1/clients/hitachi.md) β€” The CMOS annealing machine provided by Hitachi. * [Gurobi](https://amplify.fixstars.com/en/docs/amplify/v1/clients/gurobi.md) β€” Gurobi Optimizer is a Mixed Integer Programming (MIP) solver provided by Gurobi that can handle quadratic problems in integer and real variables, including… * [Quantum Computers](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) β€” Clients for quantum computers run optimization with quantum algorithms such as QAOA. * [Serial Solver Execution](https://amplify.fixstars.com/en/docs/amplify/v1/serial.md) β€” You may want to run the solver several times iteratively when evaluating performance. Also, some solvers are more likely to find a good solution by running… * [Parallel Solver Execution](https://amplify.fixstars.com/en/docs/amplify/v1/parallel.md) β€” parallel_solve() can send queries to multiple clients and models simultaneously. Such parallel execution may hide processing times for model transformations… * [Objective Function with a Coefficient Matrix](https://amplify.fixstars.com/en/docs/amplify/v1/matrix.md) β€” One way to represent the objective function is by using a multidimensional polynomial coefficient array. This is a convenient formulation when a real-valued… * [Speedup Formulation](https://amplify.fixstars.com/en/docs/amplify/v1/optimization.md) β€” Formulating a large combinatorial optimization problem using Python’s for statements can be very time-consuming. The Amplify SDK provides a fast way to… * [File input/output of the model](https://amplify.fixstars.com/en/docs/amplify/v1/file_io.md) β€” You can load an LP or QPLIB file and create Model from it, and vice versa, you can save Model and output to an LP or QPLIB file. ### 🧩 Examples * [Subset Sum Problem](https://amplify.fixstars.com/en/docs/amplify/v1/subset_sum.md) β€” This page discuss the subset sum problem as a simple example of formulation and solving with the Amplify SDK. * [Max-Cut Problem](https://amplify.fixstars.com/en/docs/amplify/v1/maxcut.md) β€” The Max-Cut problem is one of the most well-known combinatorial optimization problems. In this tutorial, we will walk through the problem definition and solve… * [Traveling Salesperson Problem](https://amplify.fixstars.com/en/docs/amplify/v1/tsp.md) β€” As an example of using the Amplify SDK, we will explain how to solve the traveling salesperson problem (TSP) with the Amplify SDK. The TSP is a combinatorial… * [Quadratic Assignment Problem](https://amplify.fixstars.com/en/docs/amplify/v1/qap.md) β€” Quadratic assignment problem (QAP) is the following problem. ### πŸ’‘ Tips * [Type Hint Support](https://amplify.fixstars.com/en/docs/amplify/v1/type_hint.md) β€” The Amplify SDK defines type hints for all functions, methods, and attributes. This feature allows IDEs such as Visual Studio Code and Google Colaboratory to… * [Proxy Server Settings](https://amplify.fixstars.com/en/docs/amplify/v1/proxy.md) β€” If you want to connect to the Internet through a proxy server, you must configure the proxy server in the code that runs the Amplify SDK cloud service. * [Formatted Formula View](https://amplify.fixstars.com/en/docs/amplify/v1/pprint.md) β€” The Amplify SDK formulas are automatically rendered in LaTeX in IPython front-end environments that support LaTeX formula display, such as Jupyter Notebook and… * [Migrating from Previous Versions](https://amplify.fixstars.com/en/docs/amplify/v1/migration.md) β€” The Amplify SDK v1 has lost some compatibility with v0. If you have been using an older version, this section explains how to maintain your code so that it… * [Formulation Benchmarks](https://amplify.fixstars.com/en/docs/amplify/v1/benchmark.md) β€” We have benchmarked the formulation of mathematical optimization models provided as a library in Python against the Amplify SDK. We measured the execution time… ### 🎺 Cloud Solvers * [Fixstars Amplify AE](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae.md) β€” Fixstars Amplify Annealing Engine (Amplify AE) is a solver provided by Fixstars Amplify. It uses heuristic algorithms based on simulated annealing on GPUs,… * [Solving Algorithms](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/algorithm.md) β€” Fixstars Amplify Annealing Engine (Amplify AE) utilizes an optimization algorithm based on simulated annealing. This page provides an overview of the Amplify… * [Advanced Usage](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/advanced.md) β€” Leveraging the information obtained from the response data can significantly enhance your use of Amplify AE. This section details advanced techniques for… * [Performance of Amplify AE](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/benchmark.md) β€” To evaluate the performance of Amplify AE, we are obtaining benchmark results from two perspectives: (1) solution performance and (2) annealing speed. * [Changelog](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/changelog.md) β€” Improve performance for linear problems containing only integer-coefficient constraints. * [API Reference](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/api_reference.md) ### βš—οΈ Quantum * [Amplify Quantum](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/index.md) β€” The Amplify SDK provides features for researching and validating combinatorial optimization using quantum computers. * [Quickstart](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/quickstart.md) β€” Quantum computing features are provided as an add-on to the Amplify SDK. To use them, install the package with the extra dependencies using the following… * [List of Supported Devices](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/index.md) β€” A list of quantum computers and their simulators supported by the Amplify SDK. All clients share a common interface, and you can switch the optimization method… * [IBM Quantum](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ibm.md) β€” Uses IBM Quantum QPUs for circuit evaluation. * [Qiskit Aer Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aer.md) β€” Uses the Qiskit Aer Simulator for circuit evaluation. * [Qulacs Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qulacs.md) β€” A local simulator that uses Qulacs for circuit evaluation. * [Amazon Braket Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aws.md) β€” Uses Amazon Braket simulators for circuit evaluation. Both local and cloud simulators are supported. * [AQT](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aqt.md) β€” Uses AQT (Alpine Quantum Technologies) trapped-ion quantum computers for circuit evaluation via Amazon Braket. * [IonQ](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ionq.md) β€” Uses IonQ’s trapped-ion quantum computers for circuit evaluation. * [IQM](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/iqm.md) β€” Uses IQM superconducting quantum computers for circuit evaluation via Amazon Braket. * [Rigetti](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/rigetti.md) β€” Uses Rigetti superconducting quantum computers for circuit evaluation via Amazon Braket. * [QUDORA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qudora.md) β€” Uses QUDORA trapped-ion quantum computers and their cloud simulators for circuit evaluation. * [OQTOPUS Cloud](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/oqtopus.md) β€” Uses cloud quantum computers and simulators available via OQTOPUS Cloud for circuit evaluation. * [List of Supported Algorithms](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/index.md) β€” A list of algorithms that use quantum computers supported by the Amplify SDK. Clients that handle quantum computers are used by specifying one of the algorithm… * [QAOA / Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) β€” QAOA (Quantum Approximate Optimization Algorithm) is a quantum-classical hybrid algorithm that alternates between quantum circuit operations on a quantum… * [Recursive QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) β€” Recursive QAOA is a quantum-classical hybrid algorithm that repeatedly executes QAOA as a subroutine, progressively reducing the problem size to identify the… * [Algorithm Details](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/index.md) β€” This section introduces the theoretical framework of the quantum optimization algorithms supported by the Amplify SDK. * [QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md) β€” This page describes the mathematical framework of QAOA (Quantum Approximate Optimization Algorithm)[1]. * [Constrained QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) β€” Some optimization problems require finding the optimum subject to certain constraints on the variables. * [Recursive QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md) β€” Recursive QAOA[1] (hereafter RQAOA) is a method that repeatedly executes QAOA with shallow ansatz circuits, progressively reducing the problem size to identify… ### πŸ”Œ Black-Box Optimization * [Amplify-BBOpt](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_bbopt.md) β€” An extension library for performing Black-Box Optimization (BBO) using the features of the Amplify SDK. ### πŸ“– Reference * [Changelog](https://amplify.fixstars.com/en/docs/amplify/v1/changelog.md) β€” Support quantum computers via the Amplify Quantum extension. * [API Reference](https://amplify.fixstars.com/en/docs/amplify/v1/reference/index.md) * [Algebra](https://amplify.fixstars.com/en/docs/amplify/v1/reference/algebra.md) β€” amplify.Poly * [Poly](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md) β€” The polynomial class used for representing objective functions and constraints. * [PolyArray](https://amplify.fixstars.com/en/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/en/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/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.einsum.md) β€” Einstein summation for polynomial arrays and NumPy arrays. * [dot](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.dot.md) β€” Compute dot product for polynomial arrays and NumPy arrays. * [matmul](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.matmul.md) β€” Matrix multiplication for polynomial arrays and NumPy arrays. * [newaxis](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.newaxis.md) * [VariableType](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md) β€” Enum of decision variable types: Binary, Ising, Integer, and Real. * [Dim](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md) β€” Base class for PolyArray dimension types. * [Dim0](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim0.md) β€” A 0D PolyArray. * [Dim1](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md) β€” A 1D PolyArray. * [Dim2](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim2.md) β€” A 2D PolyArray. * [Dim3](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim3.md) β€” A 3D PolyArray. * [Dim4](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim4.md) β€” A 4D PolyArray. * [Constraint](https://amplify.fixstars.com/en/docs/amplify/v1/reference/constraint.md) β€” amplify.Constraint * [Constraint](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md) β€” Constraint class representing equality or inequality conditions on polynomial expressions. * [ConstraintList](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md) β€” List-like container of Constraint objects. * [equal_to](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md) β€” Create an equality constraint. * [one_hot](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md) β€” Create a one-hot constraint. * [less_equal](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md) β€” Create a less-than-or-equal constraint. * [greater_equal](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md) β€” Create a greater-than-or-equal constraint. * [clamp](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.clamp.md) β€” Create a range constraint. * [domain_wall](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md) β€” Create domain wall constraints for a variable array. * [PenaltyFormulation](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md) β€” Penalty function formulation strategy used for constraint conversion. * [Model](https://amplify.fixstars.com/en/docs/amplify/v1/reference/model.md) β€” amplify.Model * [Model](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md) β€” Combinatorial optimization model containing objective and constraints. * [IntegerEncodingMethod](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md) β€” Encoding method for integer variables during model conversion. * [RealEncodingMethod](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md) β€” Encoding method for real variables during model conversion. * [QuadratizationMethod](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md) β€” Method used to reduce higher-order terms during conversion. * [Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/reference/graph.md) β€” amplify.Graph * [Graph](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md) β€” Physical graph information used by graph-embedding solvers. * [embed](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md) β€” Perform graph embedding and return embedding information. * [to_edges](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.to_edges.md) β€” Convert a polynomial to its graph edge list. * [EmbeddingMethod](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md) β€” Graph embedding algorithm to apply. * [Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/client.md) β€” amplify.BaseClient * [BaseClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BaseClient.md) β€” Base class of all clients in the Amplify SDK * [AmplifyAEClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md) β€” __init__ * [FixstarsClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md) β€” __init__ * [DWaveSamplerClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md) β€” __init__ * [LeapHybridSamplerClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md) β€” __init__ * [LeapHybridCQMSamplerClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md) β€” __init__ * [FujitsuDA4Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md) β€” __init__ * [FujitsuDA3cClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md) β€” __init__ * [ToshibaSQBM2Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md) β€” __init__ * [GurobiClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md) β€” __init__ * [NECVA2Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md) β€” __init__ * [HitachiClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md) β€” __init__ * [AcceptableDegrees](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Degree.md) β€” Polynomial degree enumeration. * [Solve](https://amplify.fixstars.com/en/docs/amplify/v1/reference/solve.md) β€” amplify.Result * [Result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md) β€” Container of optimization solutions and conversion/runtime metadata. * [Values](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md) β€” Mapping from variables to numeric values in a solution. * [solve](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md) β€” Solve a combinatorial optimization problem. * [parallel_solve](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md) β€” Solve multiple problems in parallel. * [Misc.](https://amplify.fixstars.com/en/docs/amplify/v1/reference/misc.md) β€” amplify.set_num_threads * [set_num_threads](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.load_lp.md) β€” Load an LP file and construct a model. * [save_lp](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.save_lp.md) β€” Save a model to an LP file. * [load_qplib](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_qplib.md) β€” Load a QPLIB file and construct a model. * [save_qplib](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.save_qplib.md) β€” Save a model to a QPLIB file. * [set_seed](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.set_seed.md) β€” Set the seed for random number generation. * [__version__](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.__version__.md) β€” The version of the SDK. * [Quantum](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/index.md) * [Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/client.md) β€” QuantumBaseClient * [QuantumBaseClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md) β€” Abstract base class for clients that target a specific backend sampler. * [AerClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md) β€” Client that executes quantum circuits using the Qiskit Aer simulator. * [AQTClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md) β€” Client that executes quantum circuits on AQT hardware via Amazon Braket. * [BraketSimulatorClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md) β€” Client that executes quantum circuits on Amazon Braket simulators. * [IBMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md) β€” Client that executes quantum circuits on IBM Quantum hardware. * [IonQClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md) β€” Client that executes quantum circuits on IonQ hardware. * [IQMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md) β€” Client that executes quantum circuits on IQM hardware via Amazon Braket. * [QulacsClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md) β€” Client that executes quantum circuits using the Qulacs simulator. * [RigettiClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md) β€” Client that executes quantum circuits on Rigetti hardware via Amazon Braket. * [QUDORAClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md) β€” Client that executes quantum circuits on QUDORA hardware. * [OqtopusClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md) β€” Client that executes quantum circuits on OQTOPUS Cloud. * [Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md) β€” QAOA * [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md) β€” Quantum Approximate Optimization Algorithm (QAOA). * [QAOAType](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md) β€” Selects the QAOA circuit construction strategy. * [QAOAResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAResult.md) β€” Raw result produced by a single QAOA run. * [QAOADurations](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md) β€” Total timing breakdown for a QAOA run. * [QAOAHistoryItem](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md) β€” Record of a single objective function evaluation during QAOA optimization. * [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md) β€” Recursive Quantum Approximate Optimization Algorithm (RQAOA). * [RQAOAType](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAType.md) β€” Selects the QAOA circuit construction strategy used within each RQAOA iteration. * [RQAOAResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAResult.md) β€” Raw result produced by a single RQAOA run. * [RQAOADurations](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md) β€” Total timing breakdown for an RQAOA run. * [RQAOAHistoryItem](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md) β€” Record of a single iteration during RQAOA optimization. * [NormalElimination](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NormalElimination.md) β€” Record of a variable explicitly eliminated during an RQAOA iteration. * [UnintentionalElimination](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.QuantumAlgoProtocol.md) β€” Protocol for quantum optimization algorithms. * [Minimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/minimize.md) β€” ScipyMinimize * [ScipyMinimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md) β€” Classical optimizer for QAOA circuit parameters using scipy.optimize.minimize(). * [ScipyMinimizeOptions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md) β€” Optional keyword arguments for scipy.optimize.minimize(). * [ScipyMinimizeResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md) β€” Result of a ScipyMinimize optimization run. * [NoOpMinimize](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md) β€” Result of a NoOpMinimize run. * [MinimizeProtocol](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md) β€” Protocol for classical optimizers used to tune QAOA circuit parameters. * [MinimizeResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md) β€” Protocol for the result of a classical minimization run. * [Sampler](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/sampler.md) β€” SamplerProtocol * [SamplerProtocol](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md) β€” Protocol for quantum circuit samplers. * [SamplingDurations](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md) β€” Timing breakdown for a single quantum circuit sampling call. * [AerDeviceType](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md) β€” alias of Literal[β€˜CPU’, β€˜GPU’, β€˜Thrust’] * [QiskitJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md) β€” Metadata for a single Qiskit quantum job. * [QulacsJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md) β€” Metadata for a single Qulacs simulation run. * [BraketJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md) β€” Metadata for a single Braket quantum job. * [Circuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/circuit.md) β€” QiskitCircuit * [QiskitCircuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md) β€” Qiskit-based quantum circuit implementation. * [QulacsCircuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md) β€” Qulacs-based quantum circuit implementation. * [Misc.](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/misc.md) β€” IsingSeqFreqList * [IsingSeqFreqList](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md) β€” alias of list[tuple[list[int], int]] * [Deprecated](https://amplify.fixstars.com/en/docs/amplify/v1/reference/deprecated.md) β€” amplify.BinaryPoly * [BinaryPoly](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md) β€” alias of Poly * [IsingPoly](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPoly.md) β€” alias of Poly * [BinaryPolyArray](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md) β€” __init__ * [IsingPolyArray](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md) β€” __init__ * [BinarySymbolGenerator](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md) β€” __init__ * [IsingSymbolGenerator](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md) β€” __init__ * [IsingSymbolGenerator](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md) β€” __init__ * [BinaryMatrix](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md) β€” __init__ * [IsingMatrix](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md) β€” __init__ * [QuadraticModel](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md) β€” __init__ * [BinaryQuadraticModel](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md) β€” __init__ * [IsingQuadraticModel](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md) β€” __init__ * [Solver](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Solver.md) β€” __init__ * [SolverResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverResult.md) β€” __init__ * [SolverSolution](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverSolution.md) β€” __init__ * [SymbolGenerator](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md) * [sum_poly](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum_poly.md) * [decode_solution](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.decode_solution.md) * [penalty](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.constraint.penalty.md) β€” alias of constructor of Constraint * [InequalityFormulation](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.InequalityFormulation.md) β€” An enumeration. ### Other pages * [quantum_algorithm_table](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/quantum_algorithm_table.md) β€” The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. --- # Amplify SDK Features The Amplify SDK aims to **formulate combinatorial optimization problems in a simple and intuitive way and solve them using a variety of machines and solvers**. To this end, the Amplify SDK provides the following features. ## πŸ”° Intuitive and easy to use The Amplify SDK focuses primarily on quadratic programming, a class of combinatorial optimization problems. It provides a simple and intuitive way to build and solve mathematical optimization models described by multivariate polynomials with real, integer, binary (0-1 variables), and Ising ($\pm 1$ variables) variables. On the other hand, the optimization models (the types of variables, the degree of polynomials, and the types of problems) targeted by each machine and solver vary from machine to machine. For example, the [Quantum Annealing Machine](https://en.wikipedia.org/wiki/Quantum_annealing) can be used for [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization), an unconstrained quadratic programming problem with binary (or Ising) variables. MIP solvers like Gurobi can handle real and integer variables. One of the unique features of the Amplify SDK is that it absorbs these machine and solver differences as much as possible and performs [**model conversions**](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md) such as **variable conversions**, **degree reduction**, **constraint implementation**, **embedding in hardware topology**, etc., **automatically** so that you can intuitively formulate a combinatorial optimization problem. The user does not need to know the details of the model conversion process or the machine and solver specifications. In particular, a wealth of functionality has been implemented to treat the QUBO solver as a general-purpose mathematical optimization solver. ## πŸš… Fast processing speed In quadratic programming problems (or higher order), the number of polynomial terms can grow as a power of the number of variables. On the other hand, recent Ising machines have expanded the scale of solvable problems to 100,000 variables. Such a large problem can require several gigabytes of data, making it essential to increase the speed and memory efficiency of mathematical processing. Compared to similar formulation software, the Amplify SDK is designed to be **very fast** and **memory efficient**. See [Formulation Benchmarks](https://amplify.fixstars.com/en/docs/amplify/v1/benchmark.md) for benchmark results. This is because the core functionalities of the Amplify SDK, such as polynomial formulations, model conversions, and building data to send to the machine, are implemented based on highly tuned efficient algorithms in C++. In particular, the Amplify SDK provides array programming capabilities compatible with [NumPy](https://numpy.org/doc/stable/index.html) for polynomial arrays. These features allow high-speed mathematical processing. ## πŸ”± Multiple solver support Amplify supports the following machines and solvers. More machines are expected to be added in the future. We welcome requests for additional support and collaboration with solver developers, so please get in touch with us. * [Quantum Annealing Machine](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] Quantum Monte Carlo Software Simulator (included) * Ising Machine / Annealing Machine * [Fixstars Amplify](https://amplify.fixstars.com/en/) * [Amplify Annealing Engine](https://amplify.fixstars.com/en/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/ww/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 * [Quantum Computers](https://amplify.fixstars.com/en/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 Solver * [Gurobi](https://www.gurobi.com/) ## πŸ§‘β€πŸ’»οΈ For broad users The Amplify SDK is designed for a wide range of users engaged in combinatorial optimization, from application developers to academic researchers studying formulations and hardware. Using the Amplify SDK as middleware to solve combinatorial optimization problems allows quick implementation of the problem. In addition, the high-level **model conversion functions** (variable conversion, degree reduction, constraint implementation, etc.) are based on state-of-the-art knowledge, and all processing details and algorithms are described in the documentation. In addition, the software is designed to allow users to modify the algorithms and parameters of the conversion process, check the results and processing time of model conversions, and debug using a low-level interface. Thus, users formulating combinatorial optimization problems or performing academic research on machines can efficiently develop their new formulation algorithms or investigate solver performance by taking advantage of the capabilities provided by the Amplify SDK. ## 🐲 Ever-evolving Fixstars Amplify The first version of the Amplify SDK was released in July 2020. Initially, the Amplify SDK was designed as software to conveniently use the [quantum annealing machines](https://en.wikipedia.org/wiki/Quantum_annealing) such as D-Wave and cloud services for the [Ising machine](https://en.wikipedia.org/wiki/Quantum_annealing) inspired by them and to build mathematical models based on [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) presumptions. Throughout its development, expanding the machines supported by the Amplify SDK and expanding functionality through machine updates has included support for more flexible formulations that are not necessarily bound by the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) framework. Adding support for Gurobi, a well-known mathematical optimization solver, and the desire to handle integer and real variables even in [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) has required the Amplify SDK to support more general mathematical programming models. In the new version of the Amplify SDK released in 2024 (v1 series), all specifications have been reviewed and redesigned to allow the construction of more general mathematical programming models. Of course, you can still use the Amplify SDK to formulate [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) as before. Still, even with variable types and constraints beyond the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) framework, the model conversion and parameter tuning are automatically optimized to maximize performance according to the search capabilities of the machine and solver. This makes the Amplify SDK suitable for a broader range of users and problems. --- # Quickstart You can run the Amplify SDK in any of the following ways. **πŸ’» Install and Run on Your PC** This procedure installs the Amplify SDK on your PC and runs the sample code. * You need Python installed on your PC. * You need an **Amplify Annealing Engine** API token to run the solver. **☁️ Try it out on BinderHub** You can try the sample code on the Amplify tutorial page. * You do not need an Amplify Annealing Engine API token to run the solver. * When the page expires (about 20 minutes), your input and execution results will be discarded. > [!NOTE] > > **Note** > > An **Amplify Annealing Engine** API token is required to run the sample code. > Anyone can get an API token for free by [registering as an Amplify user](https://amplify.fixstars.com/en/register). ## Installation The Amplify SDK has been tested in the following environments. **Python versions** * 3.10 * 3.11 * 3.12 * 3.13 * 3.14 **Supported 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 or later) * ARM64 (Monterey or later) First, ensure your Python version is included in the above list. ```bash $ python3 --version ``` You can install the Amplify SDK in your environment from [PyPI](https://pypi.org/project/amplify/) with the following command. ```bash $ python3 -m pip install -U amplify ``` > [!TIP] > > **Hint** > > To use D-Wave machines or Amplify Quantum, install with the corresponding extra packages: > > See [D-Wave Systems](https://amplify.fixstars.com/en/docs/amplify/v1/clients/dwave.md) and [Quantum Computing Support](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/index.md) for details. > > ```bash > # To use D-Wave machines > $ python3 -m pip install -U 'amplify[dwave]' > # To use Amplify Quantum > $ python3 -m pip install -U 'amplify[quantum]' > # To install all extra packages > $ python3 -m pip install -U 'amplify[full]' > ``` > > > [!WARNING] > > > > **Caution** > > > > Some extra packages may not be available depending on your Python version and OS. You can verify the installed version once the Amplify SDK has been successfully installed as follows. ```python >>> import amplify >>> amplify.__version__ 1.6.3 ``` ## Running the example code Now that the installation is complete let’s use Amplify to solve a simple QUBO problem. Here, we will use [Fixstars Amplify Annealing Engine](https://amplify.fixstars.com/en/engine) (hereafter referred to as Amplify AE) as the solver. If you do not have an Amplify AE account, please register [here](https://amplify.fixstars.com/en/register) to get an API token. Let’s consider the following problem. **Sample QUBO Problem** **The objective function** $$ \text{minimize:} \quad f = q_0 q_1 + q_0 - q_1 + 1 $$ **The decision variables** $$ q_0, q_1 \in \{0, 1\} $$ **The constraints** $$ \text{None} $$ With a little thought, we can see that the function $f$ has a minimum value $f = 0$ when $q_0 = 0$ and $q_1 = 1$. Let’s solve this problem using the Amplify SDK and see if we get the correct answer. ### 1. Creating a variable array To obtain a solution to a combinatorial optimization problem with the Amplify SDK, you need to define the **objective function**, **decision variables**, and **constraints** in your program code. First, let’s define the decision variables. In the example problem above, the decision variables are the binary variables $q_0$ and $q_1$, which take the values 0 or 1. Using the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class, you can define a variable array `q` of length 2 that outputs decision variables as follows ```pycon >>> from amplify import VariableGenerator >>> gen = VariableGenerator() # Create a generator for decision variables >>> q = gen.array("Binary", 2) # Generate a variable array of two binary decision variables >>> print(q) [q_0, q_1] ``` ### 2. Creating the objective function Next, we will create the objective function using the variables you have defined above. The objective function $f = q_0 q_1 + q_0 - q_1 + 1$ in the example problem can be determined using the variable array `q` as follows. Note that the subscripts of the variable $q$ correspond to the array indices. ```pycon >>> f = q[0] * q[1] + q[0] - q[1] + 1 >>> print(f) q_0 q_1 + q_0 - q_1 + 1 ``` Since there are no constraints in this sample problem, the formulation is complete. ### 3. Creating a solver client Since we use Amplify AE as the solver this time, we will create a client class ([`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)) of Amplify AE as the solver client. We must set up an API token to send the formulated problem to Amplify AE by setting the API token to the [`token`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.token) property of [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient). We will also set the solver timeout to 1 second. ```pycon >>> from amplify import AmplifyAEClient >>> client = AmplifyAEClient() >>> client.token = "***input your token***" >>> client.parameters.time_limit_ms = 1000 # Set run time to 10000 ms ``` ### 4. Running the solver We can execute the solver using the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. This function takes a formulated problem and a solver client as arguments and returns the result of the solver run. ```pycon >>> from amplify import solve >>> result = solve(f, client) ``` ### 5. Checking the solution The result from the solver is returned as an instance of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result). This instance contains the results of the solver run and information about the model conversions performed. Depending on the solver used and the parameters set, there may be more than one solution, but by calling the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) property, the SDK returns the best solution obtained as an instance of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class instance. The [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class contains the values of the variables and the objective function. ```pycon >>> result.best.objective # Value of the objective function 0.0 >>> result.best.values # Values of the variables Values({Poly(q_0): 0, Poly(q_1): 1}) ``` The values of the variables are obtained as instances of the [`Values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) class, which is a dictionary with the decision variables and their values as keys and values. To make the solution easier to see, the [`evaluate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method on the variable array returns an array in which the elements of the variable array are replaced by the values of the [`Values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) class. ```pycon >>> print(f"{q} = {q.evaluate(result.best.values)}") [q_0, q_1] = [0. 1.] ``` From the above, we know that the solution to our example problem is $q_0 = 0$ and $q_1 = 1$. ## Next steps These are the steps of formulating the problem and running the solver using the Amplify SDK. Although we have just covered a straightforward two-variable problem, you can apply the above steps similarly to more complex problems. For the next step, let’s see the [Tutorial](https://amplify.fixstars.com/en/demo) to learn how to solve various problems with the Amplify SDK. To learn more about the features of the Amplify SDK, continue with the [Amplify SDK Overview](https://amplify.fixstars.com/en/docs/amplify/v1/overview.md). **☁️ To view different applications** [**Proceed to Tutorial**](https://amplify.fixstars.com/en/demo) **⏩ To learn more about the features** [**Proceed to Amplify SDK Overview**](https://amplify.fixstars.com/en/docs/amplify/v1/overview.md) --- # 1. Amplify SDK Overview Before we go into the functionality details, let us summarize the overall picture and execution flow of the Amplify SDK. The Amplify SDK performs optimization by formulating a combinatorial optimization problem using the following steps (1) to (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) Decision variables** First, create a generator ([`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)) that creates decision variables. Next, create a variable ([`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) or an array of variables ([`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)) using the VariableGenerator. If the problem you want to formulate is a quadratic programming problem, you can also create a coefficient matrix ([`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) for the quadratic programming problem. **(2) Objective function** An objective function is constructed using the variables generated by the VariableGenerator. You can define the function as a polynomial ([`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) or a coefficient matrix ([`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)). **(3) Constraint** Constraints ([`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) are constructed from polynomials using constraint creation functions. If multiple constraints are needed, you can combine them into a constraint list ([`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)). **(4) Optimization model** An optimization model ([`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model)) is created from the objective function and constraints. **(5) Solver client** Specify a machine or solver to use and create a solver client (e.g., [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)). **(6) Solver execution** Pass the optimization model and solver client, and run the optimization through [`solve`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. The result of the execution is returned as [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result), and the objective function value and the variables of the optimal solution can be obtained. Each of the above steps is described in detail on the following pages. **2. How to create decision variables** This page explains how to create the decision variables, the first step in the formulation process. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/variables.md) **3. Polynomials and objective functions** This page explains how to express the objective function, which corresponds to the degree of achievement of an objective. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/objective.md) **4. Constraint construction** This page explains how to set constraints on the range of possible values for a decision variable and how to construct a constraint object using polynomials. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/constraint.md) **5. Model formulation** This page explains how to express the formulation of combinatorial optimization problems in program code. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/model.md) **6. Solver client** This page describes how to create a solver client that abstracts each solver. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md) **7. Solving combinatorial optimization problems** This page describes solving combinatorial optimization problems using a model and a solver client. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/solve.md) --- # 2. Creating Decision Variables You must express the problem formulation in the program code to solve a combinatorial optimization problem with Amplify SDK. This page describes the first step in the formulation: generating the decision variables. > [!NOTE] > > **See also** > > To issue decision variables, you can also use the [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method, as well as the methods described on this page, [`scalar()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) and [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class. > > You can use the [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method to create a quadratic objective function in a coefficient matrix format. See β€œ[Objective function with a coefficient matrix](https://amplify.fixstars.com/en/docs/amplify/v1/matrix.md)” for details. ## 2.1. Creating a variable generator To formulate a combinatorial optimization problem, it is first necessary to create an instance of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class. This class provides methods for issuing decision variables. ```python from amplify import VariableGenerator gen = VariableGenerator() ``` ## 2.2. Variable generation You can use the [`scalar()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) method of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class to issue a new decision variable by specifying the variable type. | Variable type | Description | | --- | --- | | [`Binary`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Binary) | A variable taking the value 0 or 1 | | [`Ising`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Ising) | A variable taking the value -1 or 1 | | [`Integer`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Integer) | A variable taking an integer value | | [`Real`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType.Real) | A variable taking a real value | Following is an example of issuing a new binary variable. The variable is returned as an instance of the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class, which represents the polynomial of the variable. ```pycon >>> q = gen.scalar("Binary") >>> print(q) q_0 ``` Issued variables are automatically named, but you can also specify a name. ```pycon >>> i = gen.scalar("Ising", name="i") >>> print(i) i ``` Integer or real variables can have a range of possible values. ```pycon >>> x = gen.scalar("Real", bounds=(2.0, 3.0)) >>> print(x) x_0 ``` ## 2.3. Creating an array of variables If you want to create multiple variables at once, you can use the [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) method of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class. This method returns an array of variables in a NumPy-like multidimensional array format. You can create an array of 3 binary variables as follows. Once the new variables are created, the variable names are automatically added with a string representing the array index. ```pycon >>> gen = VariableGenerator() >>> q = gen.array("Binary", 3) >>> print(q) [q_0, q_1, q_2] ``` You can retrieve the elements and slices like a Python [`list`](https://docs.python.org/3/library/stdtypes.html#list) or 1D NumPy array. ```pycon >>> print(q[0]) q_0 ``` ```pycon >>> print(q[:2]) [q_0, q_1] ``` The [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) method of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class can also create multidimensional arrays. The following example creates a two-dimensional $2 \times 3$ variable array. ```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}]] ``` You can retrieve elements and slices in the same way as for a two-dimensional [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray). The retrieved element or slice will be the view of the original array. ```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}] ``` You can specify the lower and upper bounds for variables simultaneously at output time. ```pycon >>> n = gen.array("Integer", shape=(5,), bounds=(1, 3)) >>> print(n) [n_0, n_1, n_2, n_3, n_4] ``` > [!NOTE] > > **See also** > > The [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) method returns an instance of the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class, representing a polynomial array. The [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class provides a variety of methods compatible with [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray), as well as element retrieval and slicing. See the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class [reference](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) for details. ## 2.4. Getting variable information To get variable information from a given variable, use the [`as_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) method. ```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} ``` The Amplify SDK provides variable information as an instance of the [`Variable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) class, which has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`name`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.name) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Variable name | | [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) | [`int`](https://docs.python.org/3/library/functions.html#int) | Variable ID number An integer value assigned starting from 0 in order of issuance | | [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.type) | [`VariableType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType) | Variable type | | [`lower_bound`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.lower_bound) | [`float`](https://docs.python.org/3/library/functions.html#float) | [Integer or real variable only] Variable lower bound [`None`](https://docs.python.org/3/library/constants.html#None) means $- \inf$. | | [`upper_bound`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.upper_bound) | [`float`](https://docs.python.org/3/library/functions.html#float) | [Integer or real variable only] Variable upper bound [`None`](https://docs.python.org/3/library/constants.html#None) means $+ \inf$. | Inverse conversion from [`Variable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) class to [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class is also possible. ```pycon >>> from amplify import Poly >>> v = x.as_variable() >>> print(Poly(v)) x_0 ``` In addition, information about variables issued by the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class can be obtained using the [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.variables) property. ```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})] ``` You can change the variable’s name and lower and upper bounds later. ```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] > > **Attention** > > The variables returned by the methods such as the [`scalar()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar) method are instances of the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class. Note that the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class can represent not only single variables but also general polynomials. However, the [`as_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) method will only succeed if the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class instance represents a unary variable. > [!TIP] > > **Tip** > > For convenience, when the [`is_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) method returns [`True`](https://docs.python.org/3/library/constants.html#True) ([`as_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) method succeeds), you can access the attributes of the [`Variable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) class directly. > > ```pycon > >>> q.is_variable() > True > >>> q.name > 'q_0' > >>> q.id > 0 > >>> print(q.type) > Binary > ``` > [!TIP] > > **Tip** > > For each instance of the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class, you can retrieve information about all of the variables contained in that instance with the [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) property; see β€œ[Polynomials and Objective Functions](https://amplify.fixstars.com/en/docs/amplify/v1/objective.md)” for details about the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class. > > ```pycon > >>> q.variables > [Variable({name: q_0, id: 0, type: Binary})] > ``` > > The methods and attributes for extracting [`Variable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) class from each class instance are as follows. > > * [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) > > * [`get_variables()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.get_variables) > * [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.variables) > * [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) > > * [`as_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) > * [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) > * [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) > > * [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.variables) --- # 3. Polynomials and Objective Functions The objective function is a mathematical expression expressing the degree to which the objective in a combinatorial optimization problem is achieved; in the Amplify SDK, it is the **polynomial** you want to minimize. This page describes how to construct polynomials using the Amplify SDK. > [!TIP] > > **Tip** > > Suppose you want to solve a combinatorial optimization problem where you want to **maximize** a polynomial. In that case, you can convert it to a minimization problem by multiplying its objective function by -1, allowing for optimization with the Amplify SDK. > [!NOTE] > > **See also** > > Another way to implement the objective function is using a multidimensional polynomial coefficient array. > This method is useful when the objective function has already been computed as a 2-dimensional array of real numbers $Q$ and a vector of real numbers $p$ such that $x^\top Q x + p^\top x + c$ is represented. See [Objective Function with a Coefficient Matrix](https://amplify.fixstars.com/en/docs/amplify/v1/matrix.md) for details. ## 3.1. Polynomial construction The Amplify SDK provides the polynomial class [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) to represent the objective function and constraint expressions for combinatorial optimization problems. Variables issued using the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class in the previous section are also instances of [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). You can easily create arbitrary polynomial expressions by performing quadrature operations and powers on variables created by [`VariableGenerator`](https://amplify.fixstars.com/en/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** > > The Amplify SDK also provides the logical operators defined below. These operators help create constraints from polynomials that are known to take only 0 or 1 values, such as a single binary variable. > > | Operator | Effect | > | --- | --- | > | `&` (logical AND) | `x & y` is equivalent to `x * y`. | > | `|` (logical OR) | `x | y` is equivalent to `-x * y + x + y`. | > | `^` (exclusive OR) | `x ^ y` is equivalent to `-2 * x * y + x + y`. | You can include variables from different variable arrays or of different types in the same polynomial if the same [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) created them. ```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] > > **Attention** > > You cannot combine variables issued from different [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) instances to create an objective function or constraint. A single formulation must use variables issued from the same [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) instance. You can use the polynomial created as an objective function without modification. Thus, for example, if the objective function is $q_0 q_1 - q_2$ then the objective function can be expressed as follows ```python gen = VariableGenerator() q = gen.array("Binary", 3) objective = q[0] * q[1] - q[2] ``` ## 3.2. Constructing polynomials using polynomial arrays > [!NOTE] > > **Note** > > This section is for users familiar with the NumPy library. > > Using the array operations of the polynomial array class speeds up the polynomial generation and is intuitive for those familiar with the NumPy library. However, you can skip this section since you can already create arbitrary polynomials using the abovementioned methods. The Amplify SDK provides the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class as a class representing an array of polynomials to make constructing polynomials easier and faster. The [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class is a NumPy-like multidimensional array that implements many methods compatible with NumPy’s [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) array. The variable array created by the [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array) of the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) class in the previous section is an instance of [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray). The following example creates a 3x3 array of variables, just like a NumPy multidimensional array, with attributes representing the [`shape`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.shape) of the array and the number of dimensions, [`ndim`](https://amplify.fixstars.com/en/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 ``` To retrieve an array element, specify the index as in the NumPy array. ```pycon >>> print(q[0, 0]) q_{0,0} ``` It is also possible to retrieve a subarray using a slice. A subarray return view, not copy. ```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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.sum) is one of the handy methods for creating polynomials from a polynomial array. * Calculating the sum of all variables: ```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} ``` * Calculating the sum row by row: ```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}] ``` * Calculating the sum column by column: ```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}] ``` You can also perform quadrature operations on numbers and numpy arrays. ```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] > > **See also** > > In addition to the above, the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class provides various functions and methods such as broadcast, matrix product, and [`einsum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) functions. For a complete list of functions, see the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class reference. For the effects of NumPy-compatible methods, see [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray). ## 3.3. Properties and methods of polynomial This section introduces the methods and properties of the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class to get and change information about polynomials. You can use the method [`degree()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.degree) to get the degree of a polynomial. The methods [`is_number()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_number), [`is_linear()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_linear), and [`is_quadratic()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_quadratic) can tell if the polynomial is below a certain degree. ```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 ``` The [`is_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) method tests whether a polynomial can be considered a single variable, i.e., a one-dimensional monomial with coefficient 1. In particular, [`is_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) returns [`True`](https://docs.python.org/3/library/constants.html#True) for scalar variables and elements of variable arrays created by the [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator). ```pycon >>> q[0].is_variable() True >>> (q[0] + 1).is_variable() False >>> (2 * q[0]).is_variable() False ``` When [`is_variable()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.is_variable) returns [`True`](https://docs.python.org/3/library/constants.html#True), properties such as variable name [`name`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.name) and type [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.type) are valid. ```pycon >>> q[0].name 'q_0' >>> print(q[0].type) Binary ``` > [!NOTE] > > **See also** > > See β€œ[Getting variable information](https://amplify.fixstars.com/en/docs/amplify/v1/variables.md#variable-info)” for detailed information about variables in polynomials, such as [`name`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.name) and [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.type). You can obtain information about all variables in the polynomial from the [`variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.variables) property. ```pycon >>> (q[0] + 2 * q[1]).variables [Variable({name: q_0, id: 0, type: Binary}), Variable({name: q_1, id: 1, type: Binary})] ``` The [`substitute()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.substitute) method obtains the result of assigning numbers or other polynomials to variables of a polynomial expression. This method takes a dict argument and returns an instance of the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class. The key of the argument must be a [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) that can be considered a variable or [`Variable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable), and the value must be a [`float`](https://docs.python.org/3/library/functions.html#float) or a [`Poly`](https://amplify.fixstars.com/en/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** > > If you want to perform a batch assignment for all polynomials in a polynomial array, you can use the [`substitute()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.substitute) method of [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray). > > ```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. Constructing Constraints **Constraints** are the conditions that must be satisfied by the values of the decision variables in a combinatorial optimization problem. In the Amplify SDK you can set constraints on the range of possible values for each variable and constraints on the range of possible values for polynomial expressions. This page explains how to set constraints on decision variables and construct constraint objects using polynomials. ## 4.1. Fixing variable values In some cases, you may want to fix the values of decision variables, such as when the values of some decision variables are pre-determined in a formulation. By replacing part of the variable array with numeric values in advance, as follows, you can effectively fix the values of the variables. ```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** > > The above implementation of assigning numeric values to `q` can also be written as follows, with the same effect. However, the above implementation is generally computationally efficient. > > ```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}]] ``` We can then construct a polynomial with the value of the fixed variable by using `q` ```pycon >>> p = q.sum() >>> print(p) q_{1,1} + q_{1,2} + q_{2,1} + q_{2,2} + 1 ``` You can also impose a constraint where a polynomial with another variable represents a variable by replacing the array of variables with a polynomial. For example, to express the constraint where $q_{1, 1} = q_{2, 2}$, you can do so as follows. ```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** > > If you want to reuse the original variable array `q` later, you can use copy. > > ```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. Setting the range of variable values For integer and real variables, you can set the range of possible values for a variable with [`float`](https://docs.python.org/3/library/functions.html#float) or [`None`](https://docs.python.org/3/library/constants.html#None), where [`None`](https://docs.python.org/3/library/constants.html#None) indicates that the variable is unbounded. To set the bounds of a variable at issuance, set the bounds parameter of the [`scalar()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar), [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array), and [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) methods to the bounds of the variable. ```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} ``` To specify a range for an individual variable, specify it in the [`lower_bound`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.lower_bound) and [`upper_bound`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.upper_bound) attributes. ```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. Setting the range of polynomial values The Amplify SDK manages equality, inequality, and other expressions representing constraints on the range of possible polynomial values as constraint objects of the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) class. By using constraint objects, the Amplify SDK can extract solutions that satisfy the constraints from the results from the machine or solver. If the constraints are not satisfied, the Amplify SDK can determine which constraints were not satisfied. The constraint object also provides the ability to generate penalty functions for solvers that cannot directly handle constraint conditions, such as the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver. A penalty function is a polynomial computed for each constraint condition when a constrained combinatorial optimization problem is converted to an unconstrained problem using a penalty method. The helper functions provided for each constraint type help construct constraints. It automatically analyzes the constraint expressions and generates an optimized penalty function. > [!NOTE] > > **Note** > > Even when you do not need to generate penalty functions, please use the helper functions, as they have no downside. > [!NOTE] > > **See also** > > See the β€œ[Constraints and Penalty Functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md)” section for details on the generated penalty functions and how to adjust their weights. See also β€œ[Specifying a penalty function](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#specify-penalty)” for information on specifying your penalty functions without using helper functions. ### 4.3.1. Equality constraints You can use the following helper functions to create constraint objects that represent equality. | Helper function | Effect | | --- | --- | | [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) | Constrains the polynomial to be equal to the right-hand side. | | [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) | Constrains the polynomial to be equal to 1. | To impose a constraint on a polynomial with equality, use the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) function. The following example creates a constraint object imposing $q_{0,0} + q_{1,1} + q_{2,2} = 1$ for a two-dimensional array of variables $q$. ```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) ``` You can put labels on constraints. The labels are helpful for identification when later reviewing the results of the constraint evaluation. You can change them at a later time. ```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) ``` Passing a polynomial array [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) to the helper function constrains the sum of the array elements. ```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) ``` This is equivalent to the below implementation. ```python c = equal_to(q[0].sum(), 1, label="1st row sum") ``` The [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function creates an equality constraint whose right-hand side is 1. Otherwise, it is the same as the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) function. ```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) ``` This is equivalent to the below implementation. ```python c = equal_to(q[0], 1, label="1st row one-hot") ``` > [!NOTE] > > **Note** > > Equality constraints on polynomials containing real variables and real coefficients are subject to numerical errors, which can lead to an incorrect decision of satisfaction. > > In particular, solvers that cannot handle real variables, such as the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver, may not be able to express equality constraints correctly because they convert real variables to a small number of binary variables (see β€œ[Conversion from real to binary variables](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md#encode-real)” for conversion from real to binary variables). > > In such cases, consider expressing inequality constraints with an acceptable error instead of equality constraints. ### 4.3.2. Inequality constraints You can use the following helper functions to create constraint objects representing inequalities. | Helper function | Effect | | --- | --- | | [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) | Constrains a polynomial to be less than or equal to the right-hand side. | | [`greater_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) | Constrains a polynomial to be greater than or equal to the right-hand side. | | [`clamp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) | Constrains the polynomial to be in a range between. | [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) and [`greater_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) are similar to [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) in that the first argument is a polynomial or polynomial array, and the second argument is the right-hand side value. ```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/en/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) constrains the polynomial to a range. The range is specified as a 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) ``` If the lower and upper bounds of the range are equal, it is treated as an equality constraint. ```pycon >>> c_bw = clamp(q[0], (2, 2)) >>> print(c_bw) q_{0,0} + q_{0,1} + q_{0,2} == 2 (weight: 1) ``` This is equivalent to the below implementation. ```python c_bw = equal_to(q[0], 2) ``` If the lower or upper bound is [`None`](https://docs.python.org/3/library/constants.html#None), this is equivalent to [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) or [`greater_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal), respectively. ```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] > > **Attention** > > The generation of penalty functions for inequality constraints for the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver requires auxiliary variables that may be inefficient or impossible to formulate rigorously. See β€œ[Inequality constraints](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#ineq-penalty)” for details. ### 4.3.3. Constraint list You can use a constraint list [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) to handle multiple constraints. You can add constraint objects [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) together to form a constraint list. ```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)] ``` You can also add constraint objects with the `+` or `+=` operator after creating the [`ConstraintList`](https://amplify.fixstars.com/en/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)] ``` You can create multiple constraint objects at once for an array of polynomials. When you pass the `axis` parameter to the helper function, it calculates the sums along the axes of the polynomial array and creates a constraint object for each result. The following example creates a constraint list [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) so that each row equals 1. If a label is given, the specified string is automatically followed by a number. ```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] > > **Hint** > > It is efficient to batch-create constraints using the `axis` parameter whenever possible. ### 4.3.4. Setting constraint weights You can give a weight to the constraint object [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) created using the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) or [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) functions. The weight parameter is mainly helpful for the QUBO solver or the Ising solver, and the larger the weight, the more likely it is to find a solution that satisfies the constraint. However, if the constraint weights are too large, finding solutions with small objective function values tends to be more challenging. > [!NOTE] > > **See also** > > Setting a constraint weight is necessary when using a solver that expresses constraints using a penalty function. See β€œ[Penalty function weight](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#penalty-weight)” for information about penalty functions and how to adjust the weights. You can obtain and set the weight of a constraint using the [`weight`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) property. The default value is 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 ``` Multiplying a constraint object by a number multiplies its weight. ```pycon >>> c.weight 3.0 >>> c *= 2 >>> c.weight 6.0 ``` Multiplication by numbers for weight is also defined for constraint list [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) objects. ```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. Domain wall constraints The Amplify SDK supports the creation of some special constraints with helper functions. > [!NOTE] > > **Note** > > In most cases, using the functions described above to create equality and inequality constraints is sufficient. The functions described below should be used by those who need to formulate special constraints. A domain wall constraint forces a one-dimensional binary or Ising variable array to have 0 (-1 for Ising variables) for more than or equal to 0 times, followed by 1 for more than or equal to 0 times from the left. For example, for the binary variable array `q = [q_0, q_1, q_2, q_3]`, `q = [0, 0, 0, 0]` or `q = [0, 1, 1, 1]` would satisfy the constraint, but `q = [0, 1, 1, 0]` would not. To create a domain wall constraint, pass an array of variables to the [`domain_wall()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) function. ```python from amplify import domain_wall gen = VariableGenerator() q = gen.array("Binary", 4) dw = domain_wall(q) ``` For a binary variable array, the constraint expression for the domain wall constraint is: $$ \sum_{i=0}^{n-2} q_i - q_i q_{i+1} = 0. $$ The above equation can be interpreted as a constraint where the number of variables that vary from $1 \rightarrow 0$ between adjacent variables is 0. In program code, you can see this as follows. ```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] > > **Note** > > Although the constraint equation for a domain wall constraint is expressed as an equality expression, the constraint constructed by passing both sides of this constraint equation to the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) function is not equivalent to the constraint constructed using the [`domain_wall()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) function. The difference is because the penalty function generated by the constraint differs, and the constraint constructed using the [`domain_wall()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) function is more efficient. See β€œ[Constraints and Penalty Functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md)” for more information about penalty functions. In the case of an Ising variable array, a constraint is generated where the number of variables changing between adjacent variables $+1 \rightarrow -1$ is 0. ```python gen = VariableGenerator() s = gen.array("Ising", 4) dw = domain_wall(s) ``` The expression of the constraint condition is: $$ \frac{1}{4} \sum_{i=0}^{n-2} s_i - s_{i + 1} - s_i s_{i+1} + 1 = 0. $$ You can check this as follows. ```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** > > To reverse the direction of the value change, set the `ascending` parameter of the [`domain_wall()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) function to [`False`](https://docs.python.org/3/library/constants.html#False). In this case, for the binary variable array `q = [q_0, q_1, q_2, q_3]`, `q = [0, 0, 0, 0]` or `q = [1, 1, 1, 0]` would satisfy the constraint, but `q = [0, 0, 1, 1]` would not. --- # 5. Model Formulation A combinatorial optimization problem comprises decision variables, objective functions, and constraints. In β€œ2. [Creating Decision Variables](https://amplify.fixstars.com/en/docs/amplify/v1/variables.md),” β€œ3. [Polynomials and Objective Functions](https://amplify.fixstars.com/en/docs/amplify/v1/objective.md),” and β€œ4. [Constructing Constraints](https://amplify.fixstars.com/en/docs/amplify/v1/constraint.md),” we explained that you can create decision variables using [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator). At the same time, you can construct objective functions and constraints using [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) and [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint). This page describes how these can be combined and used together to express combinatorial optimization problems in program code. > [!NOTE] > > **See also** > > In addition to the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class, you can use instances of the coefficient matrix [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class as an objective function. When you construct the objective function as [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix), you can use it in the same way described on this page. > > For details on the format of the coefficient matrix, see β€œ[Objective Function with a Coefficient Matrix](https://amplify.fixstars.com/en/docs/amplify/v1/matrix.md)”. ## 5.1. Model construction The Amplify SDK represents combinatorial optimization problems as instances of the [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) class. For a combinatorial optimization problem with an objective function and constraints, a simple way is to add a [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) representing the objective function and a [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) defining the constraints. ```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 ``` * Constructing the model by adding the objective function and constraints: ```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) ``` * Constructing the model by adding the objective function and the constraint list: ```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) ``` For a combinatorial optimization problem consisting of either an objective function or constraints, you can pass a [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) (or [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) instance to the constructor of the [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) class to represent the objective function or a [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) instance to represent the constraints. * Constructing a model from the objective function ([`Poly`](https://amplify.fixstars.com/en/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} ``` * Constructing a model from a single constraint object ([`Constraint`](https://amplify.fixstars.com/en/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) ``` * Constructing a model from multiple constraint objects ([`ConstraintList`](https://amplify.fixstars.com/en/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) ``` You can also add constraints ([`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or {py:class}`~amplify.ConstraintList) after the model is constructed. ```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) ``` If the model has the objective function as an instance of the polynomial [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) class, addition and subtraction of the objective function are also possible. ```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. Model attributes The [`objective`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.objective) property allows you to retrieve the objective function of the [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) class. ```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} ``` The [`constraints`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.constraints) property allows the user to retrieve the constraints the [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) class holds. This property returns an instance of the [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) class. ```pycon >>> print(model.constraints) [q_{0,0} + q_{0,1} - q_{0,2} == 0 (weight: 1)] ``` > [!NOTE] > > **Note** > > Note that the Model stores the objective function and constraints without copying them. Therefore, changing the objective function or constraints in the model will also change the variables before model construction. > > ```pycon > model = Model(objective) > model += q[0, 0] > assert model.objective == objective > ``` ## 5.3. Changing the constraint weight in the model After the model is constructed, you may want to change the weight of the constraint included in the model. > [!NOTE] > > **Note** > > See β€œ[Penalty function weight](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#penalty-weight)” for information on adjusting the weights of constraints. In the following example, the weight of a constraint is doubled. ```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. Solver Client To run a solver from the Amplify SDK, you must create a solver client that abstracts each solver and specifies the connection point, API token, and execution parameters. The solver client also contains information about the solver’s capabilities, such as the types of variables, constraints, degree, and so on that it can handle. Amplify SDK uses this information to perform **model conversions** automatically, such as **variable conversions**, **degree reduction**, **constraint implementation**, and **embedding in hardware topology**. ## 6.1. Configuring solver client Using the Amplify Annealing Engine (AE) as an example, let’s create the [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) client as follows. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` > [!TIP] > > **Tip** > > Amplify AE provides a free API token when you [register](https://amplify.fixstars.com/en/register) as a user. Most parameters of the client class are initialized (or unset) with the solver’s default values after construction, so you can use them immediately after setting the required parameters for each client. The required parameters vary from client to client, but you must set an API token in the `token` attribute for most cloud solvers. ```python client.token = "YOUR_API_TOKEN" ``` For all clients, the solver’s execution parameters are retrieved and set to attributes in the `parameters` property. Because the setting items are as consistent as possible with the solver API, see the reference for each solver below for details. For example, in Amplify AE, you can set the execution time as follows. ```python from datetime import timedelta client.parameters.time_limit_ms = timedelta(milliseconds=1000) # 1000 milliseconds ``` > [!TIP] > > **Tip** > > Because each client has a different time unit and time format for time-related parameters, the Amplify SDK uses the [`datetime`](https://docs.python.org/3/library/datetime.html#module-datetime) module for input and output. The Amplify SDK can print parameters set in the client class as strings using the [`str`](https://docs.python.org/3/library/stdtypes.html#str) or [`print()`](https://docs.python.org/3/library/functions.html#print) function. ```pycon >>> print(client) {"url":"https://optigan.fixstars.com","token":"***","compression":true,"solver":"Constraint","parameters":{"time_limit_ms":1000.0}} ``` > [!NOTE] > > **Note** > > Credentials such as the token are displayed as `***` so that they are not disclosed unintentionally. > Only the display is masked; the value itself is still available from [`token`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.token). Setting some parameters to [`None`](https://docs.python.org/3/library/constants.html#None) means they are unset, i.e., using the solver defaults. ```python client.parameters.time_limit_ms = None # reset to solver defaults ``` ## 6.2. List of solver clients The Amplify SDK supports the following solver clients. [amplify.AmplifyAEClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/amplify_ae.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md#clients-amplifyaeclient) [amplify.DWaveSamplerClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/clients/dwave.md#clients-dwavesamplerclient) [amplify.LeapHybridSamplerClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/clients/dwave.md#clients-leaphybridsamplerclient) [amplify.LeapHybridCQMSamplerClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/clients/dwave.md#clients-leaphybridcqmsamplerclient) [amplify.FujitsuDA4Client](https://amplify.fixstars.com/en/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-en.html) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fujitsu.md#clients-fujitsuda4client) [amplify.FujitsuDA3cClient](https://amplify.fixstars.com/en/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-en.html) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fujitsu.md#clients-fujitsuda3cclient) [amplify.ToshibaSQBM2Client](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/_downloads/7e21cdf718c667d7e3b709b4d6413bbd/User_Manual-SQBM%2B_for_On-premises.pdf) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/toshiba.md#clients-toshibasqbm2client) [amplify.NECVA2Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) **NEC Vector Annealing Service 2.0** QUBO VE ☁️ Cloud [πŸ“– User Guide](https://amplify.fixstars.com/en/docs/amplify/v1/_downloads/bbcfcea8bf765d6774aa727a387e0e9c/nec_vector_annealing_service_2.0_user_guide_v3_en.pdf) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/nec.md#clients-necva2client) [amplify.HitachiClient](https://amplify.fixstars.com/en/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/en/web-api/reference/v2.html) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/hitachi.md#clients-hitachiclient) [amplify.GurobiClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/clients/gurobi.md#clients-gurobiclient) [amplify.AerClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/quantum/samplers/aer.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.AQTClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) **AQT** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aqt.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.BraketSimulatorClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/quantum/samplers/aws.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IBMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) **IBM Quantum** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ibm.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IonQClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) **IonQ** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ionq.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.IQMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) **IQM** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/iqm.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.QulacsClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) **Qulacs Simulator** PUBO-Nth Ising Hybrid Gate-Simulator πŸ’» Local [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qulacs.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.RigettiClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) **Rigetti** PUBO-Nth Ising Hybrid Gate-Superconducting ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/rigetti.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.QUDORAClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) **QUDORA** PUBO-Nth Ising Hybrid Gate-Trapped-ion ☁️ Cloud [πŸ“– Document](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qudora.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) [amplify.OqtopusClient](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/quantum/samplers/oqtopus.md) [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md) --- **PCBO-Nth PUBO-Nth QUBO Ising MIP** These represent the types of problems that the solver can directly handle. * PCBO-Nth This solver can handle objective functions and constraints that are $N$-th order polynomials in binary variables. * PUBO-Nth This solver can solve objective functions that are $N$-th order polynomials in binary variables. It cannot handle constraints. * QUBO This solver can solve for the objective function of a quadratic polynomial in binary variables. It cannot directly handle constraints, but some solvers support the input of equality and inequality constraints. * Ising This solver can solve for the objective function of a quadratic polynomial in an Ising variable. It cannot directly handle constraints, but some solvers support the input of equality and inequality constraints. * MIP This solver can solve mixed integer programming problems. It can directly handle binary, integer, and real variables. It generally targets first-order problems (linear programming problems), but some solvers can handle second-order problems, including QUBO. > [!NOTE] > > **Note** > > The Amplify SDK automatically performs transformations such as variable conversion, degree reduction, and constraint penalty function generation for problems the solver cannot handle directly. Therefore, users do not necessarily need to create problems in a format the solver can address directly. However, depending on the type of solver and the type of model input, it may not be supported or formulated accurately. See [Model Conversions](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md) for more information. **Graph** This represents a quadratic term that you can pass to the solver. Solvers without these tags have no restrictions on quadratic terms. Other solvers have restrictions on the quadratic terms in the input model and require an operation called graph embedding to solve arbitrary quadratic polynomials. The problem size the solvers can handle is about $O\left( \sqrt N \right)$ in the worst case for $N$ variables the solver can take. See β€œ[Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md)” for details. **CPU GPU VE QPU Hybrid** This indicates the type of computing device the machine is running on; VE indicates NEC SX-Aurora TSUBASA Vector Engine, and Hybrid indicates that the solver is a hybrid of QPU and other technologies. **Annealing-XXX Gate-XXX** This indicates the type of QPU or Hybrid solver. * Annealing-Superconducting Quantum annealing solver using superconducting qubits. * Gate-Superconducting Gate-based solver using superconducting qubits. * Gate-Trapped-ion Gate-based solver using trapped-ion technology. * Gate-Neutral-atom Gate-based solver using neutral-atom technology. * Gate-Simulator Gate-based quantum computer simulator. **☁️ Cloud πŸ’» Local** This indicates whether the solver is provided as a cloud service or must be installed on the user’s machine. --- # 7. Solving a Combinatorial Optimization Problem This page explains how to solve a combinatorial optimization problem using the model [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) and solver client created in β€œ[Model Formulation](https://amplify.fixstars.com/en/docs/amplify/v1/model.md)” and β€œ[Solver Client](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md).” ## 7.1. Solve function The Amplify SDK provides the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to perform combinatorial optimization. This function takes [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) as its first argument and a solver client object as its second argument and optimizes the model using the solver corresponding to the solver client. Let’s optimize the following example using 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*} $$ First, we create a model by constructing the objective function and constraints. ```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 ``` Then, we create a solver client for Amplify AE and set the timeout period to 1000 milliseconds. ```python from datetime import timedelta client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` Now, we can pass the model and solver client to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function and run the solver as follows. ```python result = solve(model, client) ``` The results obtained can be verified as follows. See β€œ[Retrieving the result](#solver-result)” for more information. ```pycon >>> print(f"objective = {result.best.objective}") objective = -1.0 >>> print(f"q = {q.evaluate(result.best.values)}") q = [0. 0. 1.] ``` > [!NOTE] > > **See also** > > The Amplify SDK automatically performs model transformations such as penalty function calculations, variable conversions, degree reduction, and graph embedding as needed to make the input model client-ready. The [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function allows you to specify several parameters for this model transformation. See the β€œ[Model conversion parameters](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md#conversion-parameters)” pages for a detailed description of each parameter. ### 7.1.1. Skipping the model construction Suppose the model consists only of an objective function or only of constraints. In that case, it is possible to pass an object of the class [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) or an object of the class [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) directly as the first argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. ```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) ``` Solving an unconstrained combinatorial optimization problem: ```python result = solve(objective, client) ``` Solving a combinatorial optimization problem with a single constraint: ```python result = solve(constraint1, client) ``` Solving a combinatorial optimization problem with multiple constraints: ```python result = solve(constraint1 + constraint2, client) ``` ## 7.2. Retrieving the result The [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function contains information about the solution returned by the solver and the time taken to run it. ```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) ``` You can obtain the number of solutions in [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) with the [`len()`](https://docs.python.org/3/library/functions.html#len) function. Only solutions that satisfy all constraints are included in [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) by default. ```pycon >>> len(result) 1 ``` If [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) contains multiple solutions, you can use the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) property to find the best solution. ```pycon >>> type(result.best) ``` The best solution obtained with the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) property is an instance of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class. This class has the following attributes. | | | | --- | --- | | [`objective`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) | The value of the objective function | | [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) | The value of each variable in the solution | | [`feasible`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) | Whether the constraint is satisfied or not | | [`time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | The time at which the solver finds the solution | The values of the objective function, the values of the variables, whether all constraints are satisfied, and the time at which the solution was found can be obtained for the best solution as follows. ```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) ``` By passing [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) to the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method of the variable array, you can obtain the solution values corresponding to each variable in the array as an [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) of the same form as the variable array. ```pycon >>> print(q.evaluate(result.best.values)) [0. 0. 1.] ``` > [!WARNING] > > **Attention** > > Depending on the solver used, it may not be possible to obtain the time at which the solver found the solution. In such cases, the [`time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) attribute will have the same value as the solver’s [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time). See β€œ[Execution Time information](https://amplify.fixstars.com/en/docs/amplify/v1/timing.md)” for more information. [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) can contain not only the best solution but also multiple solutions. You can obtain each solution as an instance of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class by indexing on [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result). ```pycon >>> result[0].objective -1.0 >>> result[0].feasible True ``` Iterative access is also possible. ```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] > > **See also** > > The [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object also contains model transformation, graph embedding, and runtime information. See β€œ[Evaluation of Execution Results](https://amplify.fixstars.com/en/docs/amplify/v1/evaluation.md)” for details. ## 7.3. Options for the execution result output By default, the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function contains only solutions that satisfy the constraints in ascending order of objective function values. You can change this behavior by setting the `filter_solution` and `sort_solution` keyword arguments to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. ### 7.3.1. Filtering the solution If you set the `filter_solution` keyword argument to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to [`False`](https://docs.python.org/3/library/constants.html#False), solutions that do not satisfy the constraints may be included in [`Result`](https://amplify.fixstars.com/en/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 ``` Even after calling the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, you can set the [`filter_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) property of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) to [`False`](https://docs.python.org/3/library/constants.html#False) so that solutions that do not satisfy the constraint conditions are included in [`Result`](https://amplify.fixstars.com/en/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. Sorting solutions The Amplify SDK sorts the solutions included in [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) in ascending order by default. If you specify [`False`](https://docs.python.org/3/library/constants.html#False) for the `sort_solution` keyword argument to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, the order of the solutions in the result remains the same as that of the solutions returned by the solver. ```python result = solve(model, client, sort_solution=False) ``` You can also sort the solutions later using [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result)’s [`sort()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.sort) method. ```python result.sort() ``` > [!NOTE] > > **Note** > > The Amplify SDK determines the goodness of the solution in the following order. > > 1. Whether the constraints are satisfied > 2. Whether the value of the objective function is smaller > > Therefore, the solution that the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) property of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) can obtain is the one with the smallest value of the objective function among the solutions that satisfy the constraints, if any. If no solution satisfies the constraint condition, the Amplify SDK returns the solution with the smallest objective function value if [`filter_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) is [`False`](https://docs.python.org/3/library/constants.html#False). ## 7.4. Dry-run option Specifying [`True`](https://docs.python.org/3/library/constants.html#True) for the `dry_run` keyword argument to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, you can perform the processes before sending the model to the solver. Many solver clients allow you to run the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function with `dry_run` without specifying an API token. This option lets you see if the model you want to solve is available for input to the solver, what model transformations and graph embeddings the Amplify SDK performs, and what kind of query data the Amplify SDK sends before connecting to the solver. ```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) ``` When you run the solve() with the `dry_run` option, the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function does not contain a solution. ```pycon >>> len(result) 0 ``` > [!NOTE] > > **Note** > > When you run the solve() with the `dry_run` option, the [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) and [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) properties of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) are the same as when run without the `dry_run` option. This is useful if you want to know how the Amplify SDK performs model transformations and graph embeddings. See β€œ[Model Conversions](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md)” for more information about each property. > [!NOTE] > > **Note** > > When running with the `dry_run` option, the Amplify SDK does not send the request to the solver, but the request data is written to a file if you set [`write_request_data`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.write_request_data) of the the solver client. For more information about [`write_request_data`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.write_request_data), see β€œ[Save sent and received data ☁️ Cloud πŸ’» Local](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-write-data)”. --- # Model Conversions The Amplify SDK allows you to create models that contain real and integer variables and polynomials of any degree. On the other hand, combinatorial optimization solvers are generally limited in the types and degrees of variables they can handle, the types of constraints the solver can accept, or whether they can take constraints directly, and they may only accept second-order polynomials with a specific structure. When a model that the solver cannot directly handle is fed to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, the Amplify SDK performs the conversion process into a form that the solver can take as automatically as possible. Specifically, the Amplify SDK performs variable conversions, degree reductions, and other model conversions, as well as graph embedding, which converts a second-order polynomial into a form that the solver can accept and then runs the solver. ## Overview of the conversion process First, Amplify SDK performs variable conversion and order reduction according to the types of variables the solver can handle and the order of the objective function and constraints. The model after variable conversion and order reduction is called the **intermediate model**. When the intermediate model is in a form that can be input to the solver, the Amplify SDK asks the solver to solve the intermediate model. The solution returned by the solver is the inverse of the variable conversions performed on the input model, and the Amplify SDK evaluates the solution of the input model. [![_images/conversion_intermediate_light.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_intermediate_light.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_intermediate_light.drawio.svg) [![_images/conversion_intermediate_dark.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_intermediate_dark.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_intermediate_dark.drawio.svg) Depending on the solver type, the solver may not take the intermediate model directly. This is due to the limitation of second-order terms that the solver can take and the limitation of variable type and order. In this case, the Amplify SDK performs an additional operation called **graph embedding** to convert the intermediate model into a form that can be input to the solver. The Amplify SDK computes the solution of the intermediate model by applying the inverse transformation of the graph embedding performed on the intermediate model to the solution returned by the solver. In addition, the Amplify SDK obtains the solution of the input model by applying the inverse transformation of the variable transformation performed on the input model to the solution of the intermediate model. [![_images/conversion_embedding_light.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_embedding_light.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_embedding_light.drawio.svg) [![_images/conversion_embedding_dark.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_embedding_dark.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/conversion_embedding_dark.drawio.svg) ### Intermediate model construction In preparation for the conversion process, the following information is obtained from the solver client to determine the types of problems the solver can handle and the degree of the objective function and constraints of the intermediate model to be output. * Types of variables for the objective functions and their respective degrees * Types of variables for the equality constraints and their respective degrees * Types of variables for the inequality constraints and their respective degrees The Amplify SDK yields the maximum degree the solver can handle for each variable type. Below is an example for [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient). ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` ```pycon >>> client.acceptable_degrees.objective # degree for the objective function {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} >>> client.acceptable_degrees.equality_constraints # degree for the equality constraints {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} >>> client.acceptable_degrees.inequality_constraints # degree for the inequality constraints {VariableType.Binary: Degree.Quartic, VariableType.Ising: Degree.Zero, VariableType.Integer: Degree.Zero, VariableType.Real: Degree.Zero} ``` With {py:class}~amplify.AmplifyAEClient, the objective function can include quartic (fourth-order) terms in binary variables, and the solver is also able to directly handle equality and inequality constraints of up to fourth order. > [!NOTE] > > **Note** > > The degree that the solver can handle varies from client to client and also depends on the solver’s client settings. See β€œ[Client details](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md)” for more information. The Amplify SDK then performs the conversion to an intermediate model as follows. **Steps for the intermediate model construction** 1. Verify that the Amplify SDK can convert the objective function to a form the solver can handle by performing variable conversion and order reduction. 2. Verify that the Amplify SDK can convert equality and inequality constraints to a form that the solver can handle by performing variable conversion and order reduction. 3. If there are constraints that the solver cannot handle, calculate their penalty functions and check if the penalty functions can be converted to the same conditions as the objective function by performing variable conversion and order reduction. 4. If the Amplify SDK can convert the objective function and all constraint conditions, perform variable transformation and order reduction. 5. Delete unused variables and reconstruct variables and model 6. Create a variable conversion map between the input model and the intermediate model. ### Graph Embedding For solvers that require graph embedding, the Amplify SDK performs graph embedding in addition to conversion to an intermediate model. Whether graph embedding is needed is determined on a solver-by-solver basis, and solvers that require graph embedding are labeled Graph in [the solver client list](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md#solver-clients). First, the Amplify SDK obtains the solver-specific graph structure from the solver client. The following is an example of the [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient). ```python from amplify import DWaveSamplerClient client = DWaveSamplerClient() client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` ```pycon >>> graph = client.graph # Graph structure of DWaveSampler >>> graph.type 'Pegasus' >>> len(graph.nodes) 5627 >>> len(graph.edges) 40279 ``` The graph structure of the solver corresponding to [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) is a Pegasus graph with 5627 nodes and 40279 edges. The Amplify SDK uses the following procedure to perform graph embedding on a second-order polynomial so that the solver can handle it. **Graph embedding procedure** 1. Convert the intermediate model to an optimization problem consisting of only one objective function (unconstrained intermediate model) by adding the penalty function of each constraint in the intermediate model to the objective function. 2. Perform graph embedding from the graph representation of the unconstrained intermediate model’s objective function into a solver-specific graph (physical graph). 3. Create a correspondence map (chain) of variables between the intermediate model and the physical graph. 4. Based on the chain, transform the polynomial obtained in 1. to the polynomial in a form that the solver can handle. ### Running the solver and getting results The model transformation and graph embedding described above have converted the model into a format that can be input to the solver. The Amplify SDK then calls the `solve` method on the solver client using the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to perform optimization. The solver client does everything from creating the request data the solver needs to calling the API and optimization functions and analyzing the solver response. The Amplify SDK performs the **inverse conversion** of each variable conversion process in the graph embedding and intermediate model construction step by step on the solution returned by the solver, obtaining the solution of the input model and storing it in the [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) attribute. The [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function stores information about the series of transformations and inverse transformations and the results of the solver execution in the returned [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class. The following are attributes of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class that provide typical information. | Attribute | Data type | Summary | Details | | --- | --- | --- | --- | | [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) | [`SolutionList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.SolutionList) | Stores information such as solutions of the input model and values of the objective function. | | | [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | [`ModelConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) | Stores intermediate model and its variable conversion information. | | | [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | [`GraphConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) | Stores graph embedding information from the intermediate model to the physical graph (only if graph embedding is required). | | | [`client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | `Client.Result` | Stores solver client execution results. | | > [!NOTE] > > **See also** > > For more information about the intermediate model and graph embedding run results, see [Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md) and [Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md). ## Model conversion parameters The parameters used in model transformations are listed below. The [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function can take these parameters as keyword arguments. | Parameter name | Type of model conversion | Summary | Details | | --- | --- | --- | --- | | `integer_encoding_method` | Variable conversion | Algorithm to convert integer variables to binary variables | | | `real_encoding_method` | Variable conversion | Algorithm to convert real variables to binary variables | | | `quadratization_method` | Degree reduction | Algorithm for degree reduction | | | `substitution_multiplier` | Degree reduction | Constraint weights generated by degree reduction | | | `embedding_method` | Graph embedding | Algorithm used for graph embedding | | | `embedding_timeout` | Graph embedding | Graph embedding timeout value (in seconds) | | | `chain_strength` | Graph Embedding | Graph embedding parameters for polynomial expressions. | | For example, the following example sets the algorithm used to convert integer variables to binary variables in the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to [`Unary`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Unary), ```python result = solve(model, client, integer_encoding_method="Unary") ``` The following parameters also specify the penalty generation method for inequality constraints. When constructing a [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) object representing an inequality constraint using a helper function such as [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal) or the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) class constructor, you can use the argument `method` keyword to specify the method. | Parameter name | Type of model conversion | Summary | Details | | --- | --- | --- | --- | | `penalty_formulation` | Penalty generation | Penalty generation algorithm | | For example, the following example sets the algorithm used to generate the penalty for an inequality constraint to an [`IntegerVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) in the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. ```python le_constraint = less_equal( q[0] + q[1] + q[2], 2, penalty_formulation="IntegerVariable" ) ``` ## Next step For those interested in learning more the conversion process, the following pages explain the model conversion process, the implementation of constraints by generating penalty functions, and the graph embedding process performed by the Amplify SDK. **Variable conversion and degree reduction** This page explains how the Amplify SDK performs variable conversions and degree reduction to adapt the model to the type of variables and polynomial degree that the solver can handle. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md) **Constraints and penalties** This page describes how the Amplify SDK generates penalty functions for solvers that cannot directly handle constraints. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md) **Graph embedding** This page describes the graph embedding process that allows arbitrary model input when the quadratic polynomial input to the solver has a solver-specific structure. In particular, we will use the D-Wave example to describe graph embedding implemented in the Amplify SDK. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md) --- # Variable Conversion and Degree Reduction The Amplify SDK allows you to create models that include real and integer variables and polynomials of any degree. On the other hand, combinatorial optimization solvers are generally limited in the types of variables and degrees of polynomials they can handle. This section describes the variable conversion and degree reduction methods implemented in the Amplify SDK to match the model with the variable types and the polynomial degree that the solver can handle. ## Retrieving an intermediate model Using the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method on a model returns an intermediate model transformed to match the specified variable type and polynomial degree. Since this method is used within the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function when building the intermediate model, it is helpful to see how the Amplify SDK performs variable conversion and degree reduction. > [!WARNING] > > **Attention** > > Usually, there is no need to call the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method; use it to see how Amplify SDK performs variable transformations and order reduction within the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. You can specify the intermediate model’s variable type and polynomial degree in the first argument of the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method. If you want to use the degree that the solver can handle, pass the [`acceptable_degrees`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.acceptable_degrees) property as follows. ```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) ``` The [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method returns an intermediate model and a map of variable conversions from the input model to the intermediate model. For example, QUBO mode of [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) can handle a quadratic polynomial of binary variables as an objective function, as seen in β€œ[Intermediate model construction](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md#create-intermediate-model).” In the above example, the input model is a cubic polynomial of binary variables, but the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method converts the intermediate model’s objective function to a quadratic polynomial of binary variables. ```pycon >>> print(im) minimize: q_2 q'_0 subject to: q_0 q_1 - q'_0 == 0 (weight: 1) ``` > [!NOTE] > > **Note** > > The variables in the intermediate model use a different [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) than the input variables. In other words, it is impossible to operate between variables in the input model and the intermediate model. Passing an instance of the [`AcceptableDegrees`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees) class to the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method, you can also freely specify the type and degree of the variable to be converted. ```python bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) im, mapping = model.to_intermediate_model(bq) ``` In addition to specifying the variable type and degree, the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method can specify variable conversion and degree reduction algorithms. The following explains the variable conversion and order reduction methods implemented in the Amplify SDK by looking at the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method results. ## Variable conversion The Amplify SDK converts a variable in an input model to another variable type. This conversion transforms the model into an intermediate model with variable types that the solver can handle. Currently, the following variable conversions are implemented. * Conversion from integer to binary variables * Conversion from real to binary variables * Conversion from binary to Ising variables and vice versa ### Conversion from integer to binary variables For an integer variable $n$ with a lower limit of $l$ and an upper limit of $u$, several binary variables $q_0, q_1, ..., q_{k-1}$ are newly issued. Now, $n$ is converted to a polynomial: $$ a_0 q_0 + a_1 q_1 + \cdots + a_{k-1} q_{k-1} + l. $$ Here, the integer sequence $a_0, a_1, \ldots, a_{k-1}$ is determined so that the possible range of this polynomial matches the set of all integers between $l$ and $u$. Four different algorithms are implemented to determine the number of variables $k$ and the sequence of coefficients $a_0, a_1, \ldots, a_{k-1}$ of the polynomial. As an example, suppose the intermediate model is composed of binary variables for a model with the integer variable `n` as the objective function that takes integers between -10 and 10 as follows. Let us see how the integer variable `n` is transformed into a polynomial of binary variables in each algorithm. ```python gen = VariableGenerator() n = gen.scalar("Integer", bounds=(-10, 10)) # Issue an integer variable model = Model(n) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) ``` The conversion algorithm from integer variables to binary variables is specified in the `integer_encoding_method` keyword argument of the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method and the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. The default is [`Default`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Default). **[`Unary`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Unary)** Sets the number of variables $k = u - l$, and $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/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Linear)** Assigns $(a_0, a_1, a_2, \ldots, a_{k-2}, a_{k-1}, a_k) = (1, 2, 3, \ldots, k-1, k, m)$. $k$ is the maximum integer satisfying $1 + 2 + 3 + \cdots + k \leq u - l$, and $m$ are the fraction. ```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/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Binary)** Assigns $(a_0, a_1, a_2, a_3, \ldots, a_{k-1}, a_k) = (1, 2, 4, 8, \ldots, 2^{k-1}, m)$. $k$ is the maximum integer satisfying $1 + 2 + 4 + \cdots + 2^{k-1} \leq u - l$, and $m$ is the fraction. ```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/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Default) (Default)** Of the above three algorithms, the one that uses the least number of variables $k$ is used. > [!NOTE] > > **Note** > > In [`Linear`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Linear) and [`Binary`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod.Binary), if the fractions $m$, $m_1$, $m_2$ become $0$, the corresponding auxiliary variable is omitted from being issued. ### Conversion from real to binary variables For a real variable $x$ with a lower limit of $l$ and an upper limit of $u$, newly create several binary variables $q_0, q_1, ..., q_{k-1}$. Then, $x$ is converted to a polynomial: $$ a_0 q_0 + a_1 q_1 + \cdots + a_{k-1} q_{k-1} + l, $$ where the coefficients $a_0, a_1, \ldots, a_{k-1}$ are positive real numbers satisfying $a_0 + a_1 + \cdots a_{k-1} = u - l$. A Randomized algorithm [[5]](#id10) is implemented to determine the coefficients of the polynomial $a_0, a_1, \ldots, a_{k-1}$. For example, the model with the real variable `x` as the objective function taking reals between -10 and 10 is converted into a polynomial of binary variables as follows. Let us see how the real variable `x` is transformed into a polynomial of binary variables in each algorithm. ```python gen = VariableGenerator() x = gen.scalar("Real", bounds=(-10, 10)) model = Model(x) bq = AcceptableDegrees(objective={"Binary": "Quadratic"}) ``` The conversion algorithm from real variables to binary variables is specified in the `real_encoding_method` keyword argument of the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method and the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. The default is [`Random16`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md#amplify.RealEncodingMethod.Random16). **`Random`** Set $(a_0, a_1, a_2, a_3, \ldots, a_{k-1})$ by uniform random numbers. The number of binary variables $k$ is one of (4, 8, 16, 32), which is extracted from the last digits of the conversion algorithm name. The following is an example for $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] > > **Note** > > You can set the seed of random numbers used for variable conversion with the [`set_seed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.set_seed.md#amplify.set_seed) function. > [!NOTE] > > **Note** > > In [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), terms with coefficients less than `1e-10` are ignored to deal with numerical errors in symbolic processing. > Therefore, some of the terms of the transformed binary variable may be lost when the difference between the upper and lower limits $u - l$ is very small. ### Conversion from Ising to binary variables For an Ising variable $s$, issue a new binary variable $q$ to convert $s$ to $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 ``` ### Conversion from binary to Ising variables For a binary variable $q$, issue a new Ising variable $s$ to convert $q$ to $(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 ``` ## Degree reduction of binary variable polynomials The Amplify SDK provides functionality to reduce the degrees of polynomials of binary or Ising variables to meet solver requirements. By applying variable conversion and degree reduction, the Amplify SDK can transform polynomials involving integer variables into lower-order polynomials with binary variables. ### Degree reduction algorithm Two algorithms are implemented: [`Substitute`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) [[1]](#id6) and [`IshikawaKZFD`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) [[2]](#id7) [[3]](#id8) [[4]](#id9). The degree reduction algorithm can be specified with the `quadratization_method` keyword argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function and the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method. The default is [`Substitute`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute). To see how the intermediate model is constructed as the degree is reduced in each algorithm, we create a model with the following third-order binary variable polynomial as the objective function. The intermediate model is also specified so that the objective function is binary quadratic and unconstrained. ```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/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) (Default)** For a product $q_a q_b$ of two binary variables that appears in a product of third order or higher, issue the auxiliary variable $x$ and replace all $q_a q_b$ in each term of the polynomial expression with $x$. The following constraints are then added to the intermediate model. $$ \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*} $$ The above operations are repeated until the polynomial becomes the desired order. ```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) ``` In the above, we see that `q_0 q_1` has been replaced by the auxiliary variable `q'_0`. The weights of the penalty function for the constraints added by the order reduction are initially set to the sum of the absolute values of the coefficients of the terms in which the substitution occurs. This is because the weights must be large enough compared to the objective function. Since the initial values of the weights are sometimes too large, the `substitution_multiplier` keyword argument can be used to specify a coefficient for the initial values of the weights. ```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] > > **Note** > > See β€œ[Penalty function weight](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#penalty-weight)” for information on adjusting constraint weights. **[`IshikawaKZFD`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD)** For each higher-order term of the polynomial, an auxiliary variable is issued and the degree of a higher-order term is reduced to quadratic polynomial so that the value does not change when the auxiliary variable takes the optimal value. The following conversions are performed for third-order or higher terms with binary variables $k q_1 q_2 \cdots q_n$. * If the coefficient $k$ of the term is negative, an auxiliary variable $x$ is issued and the term $k q_1 q_2 \cdots q_n$ is converted to: $$ kx (q_1 + q_2 + \cdots + q_n + 1 - n). $$ * If the coefficient $k$ of the term is positive and the degree $n$ is even, issue $(n-2)/2$ number of auxiliary variables $x_1, x_2, \ldots, x_{\left(n-2 \right)/2}$ to convert the term $k q_1 q_2 \cdots q_n$ to: $$ \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*} $$ * If the coefficient of the term $k$ is positive and the degree $n$ is odd, $(n-1)/2$ number auxiliary variables $x_1, x_2, \ldots, x_{\left(n-1\right)/2}$ are issued to convert the term $k q_1 q_2 \cdots q_n$ to: $$ \begin{align*} & k 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 ``` Here, `q'_0` and `q'_1` are the auxiliary variables issued for each term. > [!WARNING] > > **Attention** > > In the [`IshikawaKZFD`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) algorithm, the degree of the constraints cannot be reduced. If you want to pass a constraint with a third-order constraint expression to a solver that accepts a second-order constraint expression, use the [`Substitute`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) algorithm. For Ising variables The following conversions are performed for third-order or higher terms with Ising variables $k s_1 s_2 \cdots s_n$. * If the coefficient of the term $k$ is positive and the degree $n$ is odd, or coefficient $k$ is negative and the degree $n$ is even, then $\mathrm{floor} \left( n / 2 \right)$ number auxiliary variables $x_1, x_2, \ldots, x_{\mathrm{floor} \left( n / 2 \right)}$ are issued to convert the term $k s_1 s_2 \cdots s_n$ to: $$ \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*} $$ * If the coefficient of the term $k$ is positive and the degree $n$ is even, or coefficient $k$ is negative and the degree $n$ is odd, then $\mathrm{floor} \left( \left(n-1\right) / 2 \right)$ number auxiliary variables $x_1, x_2, \ldots, x_{\mathrm{floor} \left( \left(n-1\right) / 2 \right)}$ are issued to convert the term $k s_1 s_2 \cdots s_n$ to: $$ \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*} $$ ### The characteristics of each algorithm Each degree reduction algorithm has the following characteristics. Depending on which algorithm is used, the number of variables in the intermediate model can vary greatly, which can affect the solver’s feasibility and results. | Algorithm | [`Substitute`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) | [`IshikawaKZFD`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.IshikawaKZFD) | | --- | --- | --- | | Variables of the polynomial reducible to lower degree | Binary variables only | Binary or Ising variables | | Degree of Polynomial After Reduction | Arbitrary degree, although quadratic equality constraints or penalties may be added | Always quadratic or lower | | Reduction of Constraint Degree | Possible | Not possible; penalties must be reduced instead | | Number of Auxiliary Variables | The number of auxiliary variables can be smaller compared to Ishikawa-KZFD when cross-term substitution is effective | Roughly proportional to half the degree multiplied by the number of terms (proportional to the number of terms if polynomial coefficients are negative) | ## Solver execution result and intermediate model The result of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function execution can also provide information about the intermediate model and the result of solving for the intermediate model. You can obtain this information from the [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class (the [`ModelConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) class). The [`ModelConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion) class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.model) | [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) | Intermetiate model | | [`mapping`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) | [`IntermediateMapping`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.IntermediateMapping) | Variable transformation map from input model variables to intermediate model variables | | [`num_variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.num_variables) | [`int`](https://docs.python.org/3/library/functions.html#int) | Number of variables used in the intermediate model’s objective function and constraints (including penalty functions, if generated) | | [`values_list`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list) | [`ValuesList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ValuesList) | Result of the intermediate model | As an example, let’s execute [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) with [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) for the following model with integer variables in the objective function. ```python from amplify import VariableGenerator, Model, AmplifyAEClient, solve gen = VariableGenerator() n = gen.scalar("Integer", bounds=(1, 3)) # Issue an integer variable model = Model(n) client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = 1000 result = solve(model, client) ``` You can obtain information about the intermediate model from the [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) attribute of the result. ```pycon >>> print(result.intermediate.model) minimize: q_0 + q_1 + 1 ``` You can see how the integer variable `n` is transformed in [`mapping`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping) as follows. ```pycon >>> print(result.intermediate.mapping[n]) q_0 + q_1 + 1 ``` You can check the solution of the intermediate model with [`values_list`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list). [`values_list`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.values_list) can contain multiple solutions, so we obtain the first solution here. ```pycon >>> result.intermediate.values_list[0] Values({Poly(q_0): 0, Poly(q_1): 0}) ``` The solution for the input model is obtained from the conversion of the solution of the intermediate model based on [`mapping`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ModelConversion.mapping). Although a bit complicated, all intermediate model solutions can be transformed into input model solutions as follows. ```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} ``` We can see that this is consistent with the [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) that are the output of [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). --- [[1](#id2)] I. G. Rosenberg, β€œReduction of Bivalent Maximization to the Quadratic Case,” Cahiers du Centre d’Etudes de Recherche Operationnelle 17, 71–74 (1975). [[2](#id3)] [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](#id4)] [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](#id5)] [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](#id1)] [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) --- # Constraints and Penalty Functions The Amplify SDK allows you to create models with any variable and polynomial degree constraints. However, each combinatorial optimization solver handles different types and orders of variables as constraints, and in particular, some [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solvers do not accept constraints themselves. The Amplify SDK builds an intermediate model compatible with the combinatorial optimization solver by converting the variables, the polynomial degree of the constraints, and the objective function. If these conversions are impossible, the solver is invoked by generating **penalty functions** corresponding to the original constraints and automatically adding the penalty functions to the objective function. These procedures allow models with constraints to be solved even by combinatorial optimization solvers that cannot accept constraints as they are. ## Constraints in intermediate models Each solver client defines the types of variables and degrees of **equality** and **inequality constraints**, as well as the objective function the solver can handle. Here are examples of input model conversions involving equality constraints on integer variables to an intermediate model. ```python from amplify import ( VariableGenerator, Model, AmplifyAEClient, AcceptableDegrees, equal_to, ) gen = VariableGenerator() n = gen.scalar("Integer", bounds=(-10, 10)) # Issue integer variable c = equal_to(n, 1) # Create a constraint, n = 1 model = Model(c) ``` For example, for a solver client that can directly handle equality constraints consisting of first-order binary variables, the following transformation from the input model to the intermediate model is performed. ```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 ``` Similar to [the variable conversion in the objective function](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md#encode-integer), we can see that the constraints included in the intermediate model consist only of binary variables, and the Amplify SDK performs the variable conversion between integer variables and binary variables in the intermediate model. Similarly, for solvers that cannot handle constraints at all, you can still solve problems involving constraints with the Amplify SDK. The following example shows how to transform an input model with integer variables into an intermediate model for the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver. ```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 ``` At first glance, there appears to be no difference from the previous example. Still, a polynomial called the penalty function, which we will explain in the next section, is generated and variable conversions are performed. Because the penalty function is part of the objective function, it undergoes the same variable conversion and degree reduction as the objective function. You can see this process as follows. ```pycon >>> # Penalty function for the constraint of the input model >>> print(model.constraints[0].penalty) n_0^2 - 2 n_0 + 1 ``` ```pycon >>> # Penalty function for the constraint of the intermediate model >>> 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 ``` ## Penalty method The Amplify SDK attempts to convert constraint expressions by variable conversion or degree reduction, depending on the type and degree of constraints the solver can handle. However, if conversion is impossible, a polynomial expression called a penalty function is assigned to the objective function instead of the constraint condition expression. Because the Amplify SDK generates the penalty function equivalent to the corresponding constraint, the constraint is realized indirectly. When constructing the intermediate model, variable conversion and degree reduction of the penalty function are performed in addition to the objective function, if necessary. **Penalty method** For a given constraint $c$ on variables $x_1, x_1, \ldots, x_n$, if a real-valued function $p$ satisfies: $$ p(x_1, x_2, \ldots, x_n) \begin{cases} = 0 \quad & \text{if } c \text{ is satisfied} \\ > 0 \quad & \text{otherwise} \end{cases}, $$ then $p$ is called the penalty function. The **[penalty method](https://en.wikipedia.org/wiki/Penalty_method)** is a method of transforming a combinatorial optimization problem: $$ \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*} $$ into a combinatorial optimization problem without constraints by computing $m$ sets of penalty functions $p_1, p_2, \ldots, p_m$ for each of the constraint conditions: $$ \text{minimize} \quad f(x) + k_1 p_1(x) + k_2 p_2(x) + \cdots + k_m p_m(x). $$ Here, $k_1, k_2, \ldots, k_m$ are sufficiently large hyperparameters. For instances of the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) class, You can obtain its penalty function using the [`penalty`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.penalty) property. For example, the penalty function of a constraint object created using the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) helper function is as follows. ```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 ``` The value of `c.penalty` takes the value 0 if `c` is satisfied, i.e., `q[0] + q[1] + q[2] == 1`, and a value greater than 0 otherwise. In other words, it satisfies the requirements of the penalty function defined in the [previous section](#penalty-definition). ## Penalty function weight The penalty function added to the objective function behaves like a penalty: it increases the value of the objective function only if the constraints are not satisfied. Since the solver searches for a solution that minimizes the sum of the objective function and penalty values, you can expect both the objective function and the penalty to be small in the obtained solution. An essential aspect of the penalty method that makes it work well is that you must set the weights of the constraints ($k_1$, $k_2$, $\ldots$, $k_m$ above) appropriately. This requirement is because the solver minimizes the sum of the objective function and the penalty value. Suppose the value of the penalty for violating a constraint is small. In that case, a solution that does not satisfy the constraint but has a minimal objective function may be β€œbetter” than a solution that satisfies the constraint but has a minimal objective function. In other words, the solver must prioritize minimizing the penalty value over minimizing the objective function. You can set and obtain the weight of the penalty function using the [`weight`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) property of the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) object; the Amplify SDK sets the initial value of the [`weight`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) to be 1, and the penalty function added to the objective function is the value automatically calculated by the Amplify SDK multiplied by the [`weight`](https://amplify.fixstars.com/en/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 ``` As described in the next section, by default, the Amplify SDK automatically normalizes and sets the penalty function to take a value of at least 1 as the penalty. The appropriate value for the [`weight`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) depends on the problem, but a rule of thumb is to set it larger than the value of the objective function involved in the constraint so that a feasible solution is more likely to be obtained. Therefore, if its value is far from 1, you should set the weight of the penalty function accordingly. You can set the [`weight`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.weight) of the penalty function directly by assigning it to the weight property, or you can set it by applying a numeric value to the constraint object [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or the constraint list [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList). The latter is useful when you want to set the same weight value for multiple constraint objects at once or when you want to set the weights after the model has been constructed. ```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)] ``` For more information on setting the weights of the penalty function for specific problems, please refer to the following: * [Traveling Salesperson Problem](https://amplify.fixstars.com/en/docs/amplify/v1/tsp.md#tsp-model) * [Quadratic Allocation Problem](https://amplify.fixstars.com/en/docs/amplify/v1/qap.md#qap-model) > [!TIP] > > **Hint** > > For example, the following procedure can be used to adjust the weights of the penalty function. > > 1. Estimate the **maximum gain of the objective function** with respect to a given constraint when that constraint is not satisfied. > > * For example, in the traveling salesperson problem, the maximum gain from not visiting a city can be estimated as the maximum length of the edges between cities. > 2. Set the weights of the penalty function for the constraint of interest to a value greater than the estimated value. > 3. If no feasible solution is obtained, increase the weights and rerun the solver. > > * For example, you might increase the weights by a factor of 2. > > If you want to increase the accuracy of the solution, follow the steps below after performing the above steps. > > 4. Run the solver several times, decreasing the weights one at a time. > > * For example, you can decrease the weight by a factor of 0.9. > 5. Of all the solutions obtained, the one with the smallest objective function value is the final solution. ## Penalty function auto-generation When you create a constraint object [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) using helper functions such as [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) or [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), the Amplify SDK automatically generates an optimal penalty function as needed. When the Amplify SDK generates a penalty function for a constraint, it first estimates the upper and lower bounds of possible values for the left-hand side of the constraint expression. For example, for a binary polynomial, the Amplify SDK obtains this estimate by calculating the sum of the negative and positive coefficients in the polynomial. Then, depending on the type of equality or inequality constraint and the specified algorithm, a penalty function is generated as follows. ### Equality constraint For equality constraint $f(x) = c$, a penalty function $p$ is generated as follows. **(i) If the lower bound of the range of possible values of the left-hand side $f$ of the constraint expression is $c$** The penalty function $p$ is set to be $f - c$. For example, for the product of binary variables `q[0] * q[1] = 0`, the lower bound of $f$ and the right-hand side $c$ are equal, so the following penalty function is generated. ```pycon >>> c = equal_to(q[0] * q[1], 0) >>> print(c.penalty) q_0 q_1 ``` **(ii) When the upper bound of the range of possible values of the left-hand side $f$ of the constraint equation is $c$** The penalty function $p$ is set to be $c - f$. For example, for the product of binary variables `q[0] * q[1] = 1`, the upper bound of $f$ and the right-hand side of $c$ are equal, so the following penalty function is generated. ```pycon >>> c = equal_to(q[0] * q[1], 1) >>> print(c.penalty) - q_0 q_1 + 1 ``` **(iii) Other cases** The penalty function $p$ is set to be $(f - c)^2$. For example, for a binary variable sum `q[0] + q[1] + q[2] = 2`, the following penalty function is generated. ```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] > > **Note** > > The above applies to an inequality constraint where the upper and lower bounds are equal, and you can regard such constraint as an equality constraint. ### Inequality constraints To generate a penalty function for an inequality constraint, the Amplify SDK first rewrites the constraint using the upper and lower bounds on the possible values for the left-hand side of the constraint expression in the form $a \leq f \leq b$. The Amplify SDK provides the following algorithms to generate penalty functions for inequality constraints of this form. The algorithm is specified using the `penalty_formulation` keyword argument of the [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), [`greater_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal), and [`clamp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) inequality constraint-generating helper functions. The default is [`Default`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default). **[`Default`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default) (Default)** If all variables and coefficients in the constraint expression are integers, the Amplify SDK uses the [`IntegerVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) algorithm; otherwise, it uses the [`RealVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.RealVariable) algorithm. **[`IntegerVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable)** Generates a penalty using auxiliary variables that take integer values. For an inequality constraint $a \leq f \leq b$, the Amplify SDK issues an integer variable $n$ that takes a value between $a$ and $b$, and the penalty function for the equality constraint $f - n = 0$ is the penalty function for the inequality constraint $a \leq f \leq b$. However, as an exception, if $b - a = 1$, then $(f - a)(f - b) / 2$ is the penalty function without issuing an integer variable. > [!WARNING] > > **Attention** > > Note that specifying an [`IntegerVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable) for a constraint that is not an integer value does not result in an exact formulation. For example, for a binary variable sum `q[0] + q[1] + q[2] <= 2`, the following penalty function is generated ```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} ``` Here, `n_0` is an integer auxiliary variable output when the Amplify SDK generates the penalty function. > [!NOTE] > > **Note** > > The Amplify SDK performs variable conversions during intermediate model construction for solvers that cannot handle integer variables, such as the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver. See β€œ[Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md)” for details. > > In this variable conversion, the larger the range of possible values of an integer variable, the larger the number of auxiliary variables required. Therefore, you can make the variable conversion more efficient by reducing the range of inequality constraints at the time of constraint construction, for example, by dividing both sides by a factor. For a binary variable sum `q[0] + q[1] + q[2] <= 1`, the difference between the lower bound $0$ of the left-hand side $f$ and the right-hand side $c=1$ of the constraint is 1, so no integer variables are issued and the following penalty function is generated. ```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/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.RealVariable)** Generates a penalty function using an auxiliary variable that takes a real value. For inequality constraint $a \leq f \leq b$, the Amplify SDK issues a real variable $x$ that takes values between $a$ and $b$, and the penalty function for equality constraint $f - x = 0$ is the penalty function for inequality constraint $a \leq f \leq b$. For example, for the sum of the binary variables `0.1 * q[0] + 0.2 * q[1] + 0.4 * q[2] <= 0.5`, the following penalty function is generated. ```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} ``` Here, `x_0` is the real auxiliary variable that is issued when the penalty function is generated. > [!NOTE] > > **Note** > > The Amplify SDK performs [variable conversions](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md#encode-real) from real to binary variables for solvers that cannot handle real variables, such as the [QUBO](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) solver. The `real_encoding_method` keyword argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function then specifies the conversion method. However, if the number of binary variables used for the conversion is small, the constraint conditions may not be accurately expressed. > > In such cases, the following approach can be considered to avoid using real variables. > > * Multiply both sides of the constraint equation by a constant and use [`IntegerVariable`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.IntegerVariable). > * Try approximation by [`Relaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation) described next. **[`Relaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation)** Uses [`LinearRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation) if the left-hand side of the constraint $f$ is quadratic or greater and the lower or upper bound of $f$ is consistent with the range of the constraint, otherwise uses [`QuadraticRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation). > [!WARNING] > > **Attention** > > Note that the penalty functions generated by the relaxation methods ([`Relaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Relaxation), [`LinearRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation), [`QuadraticRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation)) are not exact formulations because they do not meet the requirements for a penalty function as defined in the [penalty method](#penalty-definition). > > The penalty is applied in the direction of moving $f$ closer to $a$ or $b$ when [`LinearRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation) is applied, and in the direction of moving $f$ closer to $(a + b) / 2$ when [`QuadraticRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation) is applied. However, since the penalty value applied when the constraints are satisfied is not constant, an optimal solution may not be found even if the penalty weights are sufficiently large. Therefore, to find a better solution, the solver should be run many times while changing the [weights of the penalty function](#penalty-weight), and the best solution among the feasible solutions should be selected. **[`LinearRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.LinearRelaxation)** Uses Lagrangian relaxation instead of the penalty method. For the inequality constraint $a \leq f \leq b$, if the lower bound of the range of possible values of $f$ matches $a$, a normalized version of $f - a$ is generated; if the upper bound of the range of possible values of $f$ matches $b$, a normalized version of $b - f$ is generated. If neither is the case, [`QuadraticRelaxation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation) is used. For example, for a binary variable sum `q[0] + q[1] + q[2] <= 2`, the following penalty function is generated. ```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/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.QuadraticRelaxation)** Uses Lagrangian relaxation instead of the penalty method. For inequality constraint $a \leq f \leq b$, a normalized version of $(f - \left(a + b\right)/2)^2$ is generated. For example, for a sum of binary variables `q[0] + q[1] + q[2] <= 2`, the following penalty function is generated. ```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 ``` ## Specifying a penalty function For constraints created with helper functions, the Amplify SDK automatically specifies a penalty function. On the other hand, if you want to set a custom penalty function, you can call the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) constructor. As shown below, you can create a constraint object by specifying a constraint expression and a penalty function. * Creating an equality constraint with constraint expression $q_0 + q_1 = 2$ and penalty $- q_0 - q_1$: ```pycon >>> c = Constraint(q[0] + q[1], eq=2, penalty=-q[0] - q[1]) ``` * Creating an inequality constraint with a constraint expression of $q_0 + q_1 \leq 1$ and a penalty of $q_0 q_1$: ```pycon >>> c = Constraint(q[0] + q[1], le=1, penalty=q[0] * q[1]) ``` * Creating an inequality constraint with constraint expression $q_0 + q_1 \geq 1$ and penalty $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]) ``` * Creating an inequality constraint with constraint expression $1 \leq q_0 + q_1 + q_2 \leq 2$ and penalty $(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)) ``` --- # Graph Embedding Some QUBO and Ising solvers do not accept arbitrary second-order polynomials and are limited in the number of second-order terms that you can pass to the solver; the Amplify SDK performs an operation called graph embedding to convert the polynomial into a form that the solver can accept. A typical example of a solver that requires graph embedding is the D-Wave machines, whose QPUs have a physical topology between the qubits that differs from machine to machine. If you view the coupling between the qubits as a graph structure, the input quadratic polynomial terms are restricted to this graph structure. This graph structure is called the physical graph, and the graph structure of the polynomial in the intermediate model constructed by the Amplify SDK is called the intermediate graph. Graph embedding is the operation to embed the intermediate graph into the physical graph. > [!NOTE] > > **See also** > > Solvers that require graph embedding are those with the Graph tag on [this page](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md#solver-clients). > > See [D-Wave QPU Architecture: Topologies](https://docs.dwavequantum.com/en/latest/quantum_research/topologies.html) for the topology of QPUs on D-Wave machines. ## What is graph embedding? Solvers that require embedding have limited types of quadratic terms they can accept as input. That is, given a set $E$ of index pairs, any quadratic terms in the input polynomial need to be expressed as: $$ c_{ab} q_a q_b \quad (c_{ab} \in \mathbb{R}, (a, b) \in E). $$ $E$ is usually represented as a graph with the variables as nodes, where an edge connects each variable pair contained in the second-order terms that can be input. For any polynomial, you can also look at each second-order term in the polynomial and consider the graph where an edge connects each variable pair. For example, suppose the objective function is $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$, and the graph $E$ representing the second-order terms that can be input to the solver is a $3 \times 4$ lattice graph. In that case, the graphs $P$ and $E$ of the transformed objective function are P$and$E$, respectively, shown in the following figures. [![_images/graph1.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph1.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph1.png) Graph $P$ [![_images/graph2.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph2.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph2.png) Graph $E$ **Graph embedding** is the procedure of assigning each variable in $P$ to some of the nodes in $E$ and finding the correspondence between $P$ and the nodes in $E$ such that the following conditions are satisfied. * For each variable $q_i$ on $P$, there exists one or more corresponding nodes on $E$ (one-to-many mapping is allowed). * For each node $a$ on $E$, there is at most one corresponding variable on $P$ (no duplicate assignments). * If $q_i$ and $q_j$ are neighbors on $P$, then for each of $q_i$ and $q_j$ there is a corresponding node $a$ and $b$ on $E$ that is a neighbor somewhere on $E$ * For each variable $q_i$ on $P$, the subgraph of $E$ consisting of a node $a$ in $E$ corresponding to $q_i$ is connected (called a chain). For example, if a variable is assigned to $E$ as shown in the left diagram below, the condition is not satisfied because the node to which $q_0$ is assigned is not adjacent to the node to which $q_2$ is assigned. On the other hand, if the variables are assigned as shown in the second figure below, the condition is satisfied. [![_images/graph3.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph3.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph3.png) Failed graph embedding example [![_images/graph4.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph4.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/graph4.png) Example of successful graph embedding If graph embedding is successful, the objective function can be transformed into a form acceptable to the solver as follows. **Polynomial transformation by graph embedding** **Second-order terms of the objective function** The second order terms $Q_{ij} q_i q_j$ of the objective function are transformed to be $\sum_{a,b} c_{ab} q_a q_b \left( Q_{ij} = \sum_{a,b} c_{ab} \right)$ and added to the new objective function. Here, $q_a$ is the variable at node $a$ on $E$ associated with $q_i$ and $q_b$ is the variable at node $b$ on $E$ associated with $q_j$, where $a$ and $b$ are adjacent. **First-order terms of the objective function** The first-order term $Q_{ii} q_i$ of the objective function is transformed to be $\sum_{a} c_{aa} q_a \left( Q_{ii} = \sum_{a} c_{aa} \right)$ and added to the new objective function, where $q_a$ is the variable at node $a$ on $E$ to which $q_i$ is assigned. **The constant term of the objective function** The constant term of the objective function is added to the new objective function as is. **Chain constraint** For a subgraph consisting of all nodes $a$ on $E$ corresponding to variables $q_i$ on $P$, add penalty functions such that variables $q_{a}$ and $q_{a'}$ on adjacent nodes satisfy the constraint $q_{a} = q_{a'}$. The penalty function for a chain is given by For a binary variable $q$: $$ \sum_{a, a'} \left( q_a - q_{a'} \right)^2 $$ For an Ising variable $s$: $$ - \frac{1}{2} \sum_{a, a'} s_a s_{a'} $$ The weight of the penalty function depends on the coefficient of $q_i$. This is called the chain strength. The result of the solver run will be for variables on the graph $E$. Therefore, we must perform an inverse transformation of the graph embedding to determine the values of the variables on the original graph $P$. More than one variable $q_a$ in the graph $E$ corresponds to a variable $q_i$ in the graph $P$. Ideally, the values $q_a$ of all variables should be the same, but the solver may return different values in practice. Such a situation is called a broken chain, and the fraction of the chain that is broken for a polynomial on a given physical graph is called the **chain break fraction**. The broken chain is often determined by β€œmajority rule” when $q_i$ is a binary variable. ## Graph embedding process The [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function automatically performs graph embedding after constructing the intermediate model and then runs the solver. The following is a detailed description of the graph embedding process performed by the Amplify SDK within the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. Below is an example of graph embedding for [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) on a model with an objective function and constraints of $4 \times 4$ binary variables. ```python from amplify import DWaveSamplerClient, VariableGenerator, Model, equal_to, to_edges import numpy as np # Generate Variables gen = VariableGenerator() q = gen.array("Binary", shape=(4, 4)) # Define an objective function and a constraint rng = np.random.default_rng() p = (q[:-1] * q[1:] * rng.uniform(-1, 1, (3, 4))).sum() c = equal_to(q, 1, axis=1) # Create an input model m = p + c # Create a solver client client = DWaveSamplerClient() ``` ### Polynomial to graph conversion First, the Amplify SDK uses the [`to_intermediate_model()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.to_intermediate_model) method to obtain the intermediate model. This operation is not mandatory since the model, in this case, consists of quadratic binary variables, but it is necessary in case of variable conversion or order reduction. ```python im, im_mapping = m.to_intermediate_model(client.acceptable_degrees) ``` Next, since [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) cannot handle constraints directly, the Amplify SDK computes a polynomial by adding all constraint penalties to the objective function. ```python im_unconstrained = im.to_unconstrained_poly() ``` We now have the intermediate model as a quadratic polynomial in binary variables. You can obtain the graph representation of the quadratic polynomial using the [`to_edges`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.to_edges.md#amplify.to_edges) function. If a node of the graph is represented by the variable [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id), the function returns the edges as a list of tuples of [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id). The first-order term is represented as a loop. ```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), ...] ``` Using the [networkx](https://networkx.org/documentation/stable/index.html) module, you can visualize the graph. ```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/en/docs/amplify/v1/_images/64ed5f8ccfd9959ca2ae55e9a485de333f30531a74e35024c8363caac93c0f24.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/64ed5f8ccfd9959ca2ae55e9a485de333f30531a74e35024c8363caac93c0f24.png) ### Getting the physics graph Solver client classes that require graph embedding have a [`graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) attribute. This attribute is an instance of the [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) class and represents the solver’s physical graph. The [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) class has the following attributes. | Attribute | Deta type | Details | | --- | --- | --- | | [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.type) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Graph type | | [`shape`](https://amplify.fixstars.com/en/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)] | Graph size parameter | | [`nodes`](https://amplify.fixstars.com/en/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)] | List of nodes in the graph | | [`edges`](https://amplify.fixstars.com/en/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)]] | List of graph edges | | [`adjacency`](https://amplify.fixstars.com/en/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)]] | List of neighbor nodes for each node | As an example, let us obtain the [`graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) attribute for [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient). ```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 ``` You can visualize the physical graph by drawing [`edges`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.edges) with the [networkx](https://networkx.org/documentation/stable/index.html) module. On the other hand, the [dwave-networkx](https://dnx.readthedocs.io/en/latest/index.html) module can be used to draw the graph in a well-formed layout according to [`shape`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph.shape). The following figure shows an example of a Pegasus graph (`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/en/docs/amplify/v1/_images/6f82485a03e6381526d46b0cbf963bd4b0ed20660a47f1991ff4c667349bee85.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/6f82485a03e6381526d46b0cbf963bd4b0ed20660a47f1991ff4c667349bee85.png) Pegasus graph (`shape=4`) ### Executing a graph embedding Call the [`embed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) function to perform a graph embedding and get the embedding information. This function takes an instance of the polynomial [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) and [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) classes as arguments and returns a tuple consisting of the polynomial after graph embedding, the mapping of the graph embedding, and a graph converted from the argument polynomial. ```python from amplify import embed # Perform graph embedding on a D-Wave graph. emb_poly, embedding, src_graph = embed(im_unconstrained, graph) ``` `emb_poly` returns a polynomial [transformed by graph embedding](#embed-polynomial). `embedding` is a list of mappings (chains) from the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) used in `im_unconstrained` to the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) that appears in `emb_poly`. The index of the list is the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) used in `im_unconstrained`. ```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` is the graph representation of `im_unconstrained`. Applying the [`to_edges`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.to_edges.md#amplify.to_edges) function to `im_unconstrained` returns the same result. Using the [dwave-networkx](https://dnx.readthedocs.io/en/latest/index.html) module, you can visualize graph embedding. ```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/en/docs/amplify/v1/_images/f189634ca396139fe6744f9b337f9ae730655d61246fd529bef2ef7530245618.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/f189634ca396139fe6744f9b337f9ae730655d61246fd529bef2ef7530245618.png) Example of graph embedding into a Pegasus graph (`shape=16`) In the figure above, the numbers on the nodes represent the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id) variable of the `im_unconstrained` polynomial before embedding. Multiple nodes connected by the same color represent a chain, corresponding to a single variable before embedding. Also, black lines connecting nodes of different colors represent edges on the physical graph corresponding to second-order terms in the pre-embedded polynomial `im_unconstrained`. ## Graph embedding execution parameters The Amplify SDK provides the following parameters for graph embedding execution. Embedding execution parameters can be specified as keyword arguments to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) and [`embed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) functions. | Parameter | Description | | --- | --- | | `embedding_timeout` | Timeout for graph embedding search | | `embedding_method` | Graph embedding algorithm | | `chain_strength` | Weight of the chain penalty to add to the objective function | ### Embedding timeout You can specify a timeout for embedding a graph by passing a number or a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object as the `embedding_timeout` keyword argument to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) or [`embed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) function. The default is 10 seconds. ### Embedding algorithms The Amplify SDK provides the following embedding algorithms. To specify an embedding algorithm, use the `embedding_method` keyword argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function or the [`embed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) function. **[`Clique`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique)** Search for embeddings of fully connected graphs that have the same number of nodes in the graph to be embedded. Once found, the clique embedding is cached. Caching can be used for fast searches since it depends only on the number of nodes in the target graph. However, the maximum number of nodes for a clique embedding is determined only by the physical graph, so it will always fail for graphs that inherently have more nodes than can be embedded. **[`Minor`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor)** Perform minor embedding with [minorminer](https://github.com/dwavesystems/minorminer). If the target graph is sparse, you can expect more efficient (shorter chain) embedding than [`Clique`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) embedding. This algorithm may succeed for the graph size for which [`Clique`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) embedding would fail. The `embedding_timeout` keyword argument sets the search timeout. **[`Default`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Default) (Default)** First, try [`Clique`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) embedding, and switch to [`Minor`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) if it fails. **[`Parallel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Parallel)** Perform [`Clique`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Clique) and [`Minor`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) embeddings in parallel, and select the result with fewer variables in the chain. ### Chain strength When transforming the objective function for graph embedding, a [chain constraint](#chain-constraint) is applied to ensure that all nodes assigned to the same input variables take the same value. The Amplify SDK automatically adds a chain constraint penalty to the post-embedding polynomial, where the initial value of the penalty weight is the square root of the second-order coefficients of the pre-embedding polynomial divided by the number of variables. You can set the relative weight of this penalty by passing the `chain_strength` keyword argument to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) or [`embed()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) function. The default is 1.0. > [!IMPORTANT] > > **Important** > > The above initial setting for root-mean-square is based on the [D-Wave implementation](https://docs.ocean.dwavesys.com/projects/system/en/latest/reference/generated/dwave.embedding.chain_strength.uniform_torque_compensation.html). The calculation method in the Amplify SDK may change in the future. ## Solver execution results and graph transformations When a solver that requires graph embedding is specified, the Amplify SDK performs the graph embedding in the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. The embedding information is stored as an instance of the [`GraphConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) class in the [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. > [!NOTE] > > **Note** > > The [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) attribute returns [`None`](https://docs.python.org/3/library/constants.html#None) for solvers that do not require graph embedding. The [`GraphConversion`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion) class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`src_graph`](https://amplify.fixstars.com/en/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)]] | Representation of a graph of polynomial equations, adding the intermediate model’s objective function and the constraints’ penalty. | | [`dst_graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.dst_graph) | [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) | Solver-specific physical graph | | [`chains`](https://amplify.fixstars.com/en/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)] | List of correspondences between the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id)’s of variables in the intermediate model and the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id)’s of variables in the physical graph | | [`poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) | [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | Resulting polynomial of graph embedding for polynomials in the intermediate model | | [`num_variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.num_variables) | [`int`](https://docs.python.org/3/library/functions.html#int) | Number of [`poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) variables | | [`values_list`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.values_list) | [`ValuesList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.ValuesList) | Solutions returned by the solver | | [`chain_break_fractions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chain_break_fractions) | [`ChainBreakFractions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.ChainBreakFractions) | Percentage of chain breaks in each solution returned by the solver | For example, you can obtain the graph embedding information from running the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function with [`DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) on the following model. ```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) ``` With the [`src_graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.src_graph) attribute you can obtain a list of edges transformed from the polynomial with the penalty functions of the intermediate model. ```python >>> result.embedding.src_graph [(0, 1), (1, 2), (0, 2)] ``` You can examine the [`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id)’s of the variables in the polynomial of the intermediate model as follows. ```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})] ``` The [`dst_graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.dst_graph) attribute returns an instance of the same [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) class as the solver client’s [`graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.graph) attribute as a physical graph. ```python >>> result.embedding.dst_graph.type 'Pegasus' >>> result.embedding.dst_graph.shape [16] ``` The [`chains`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chains) attribute represents a mapping between variables in the intermediate layer and variables in the solver. [`chains`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chains) are a list of chains, each described as a one-dimensional [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) object. In the following example, we see that the zeroth variable in the inter layer corresponds only to the 2940-th variable . ```python >>> result.embedding.chains [array([2940], dtype=uint32), array([2955], dtype=uint32), array([45], dtype=uint32)] >>> print(result.embedding.chains[0]) [2940] ``` From the [`poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) attribute, we can get the polynomial after graph embedding. This is the same polynomial that was entered into the solver. ```python >>> print(result.embedding.poly) - 3 q_{45} q_{2940} + 2 q_{45} q_{2955} + q_{2940} q_{2955} ``` The [`num_variables`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.num_variables) attribute represents the number of variables in the [`poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.poly) attribute. You can use this as an indicator of a problem’s simplicity; in general, the smaller the value, the easier the problem is to solve. ```python >>> result.embedding.num_variables 3 ``` The [`values_list`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.values_list) attribute provides a list of the solution values returned by the solver. This is a list-like object whose length is equal to the number of solutions returned by the solver, and each element corresponds to a solution returned by the solver. The solutions are represented as a dictionary, and the keys are solver variables. ```python >>> print(result.embedding.values_list) [{q_{45}: 1, q_{2940}: 1, q_{2955}: 0}] ``` The [`chain_break_fractions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.GraphConversion.chain_break_fractions) attribute indicates the percentage of chain constraints broken for each solution returned by the solver. The appropriate value generally depends on the problem and is not necessarily 0. Suppose the value is too large to obtain a good solution. In that case, performance can be improved by providing a value greater than 1.0 for the `chain_strength` keyword argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function or, conversely, a value less than 1.0 if the value is too small. ```python >>> print(result.embedding.chain_break_fractions) [0] ``` > [!TIP] > > **Tip** > > If the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function does not contain a solution, you can retrieve all solutions returned by the solver by setting the [`filter_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) property of the Result object to False. See [Filtering the solution](https://amplify.fixstars.com/en/docs/amplify/v1/solve.md#filter-solution) for details. --- # Evaluation of Execution Results The execution result returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function contains various information about the solutions, model conversion, and execution time. This page explains how to obtain and use this information. The following is an example of obtaining the optimization result for a model consisting of an objective function and a constraint using the [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient). ```python from datetime import timedelta from amplify import VariableGenerator, equal_to, AmplifyAEClient, solve # Create an array of decision variables gen = VariableGenerator() q = gen.array("Binary", 5) # Create an objective function and a constraint objective = q[0] * q[1] - q[2] constraint = equal_to(q[0] + q[1] + q[2], 1) # Define a model model = objective + constraint # Create a solver client client = AmplifyAEClient() # client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) # Obtaining the result of the run result = solve(model, client) ``` ## The Result class The following explains how to obtain information about solutions, model conversion, and execution time from an instance of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. ### Information on the solutions The [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class stores the solutions to the input model. The [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) attribute is an instance of the [`SolutionList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.SolutionList) class, which behaves like a list with the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class as an element. ```pycon >>> type(result.solutions[0]) ``` The [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class represents a solution and has the following attributes. | Attribute name | Type | Summary | | --- | --- | --- | | [`objective`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) | [`float`](https://docs.python.org/3/library/functions.html#float) | Objective function value. | | [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) | [`amplify.Values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) | Values of variables in the solution. | | [`feasible`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Whether the solution meet the constraints. | | [`time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | The timestamp at which the solution is obtained. | The [`Values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) class, which is the type of the [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) attribute, is a class that represents solution values and acts like a dictionary with variables as keys and solution values as 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 ``` You can also use the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate) methods of the variable array and polynomial classes and the [`is_satisfied()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.is_satisfied) method of the constraint class to assign the solution values represented by the {py: class}`~amplify.Values` class to the variable array, polynomial or constraint conditions. See [Decision variable evaluation](#variable-evaluation), [Penalty evaluation](#polynomial-evaluation), and [Constraint evaluation](#constraint-evaluation) for more details. The [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class provides several shortcuts to accessing the solution besides the [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) attribute. First, the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class provides the best solution. Accessing the result directly from the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class by index is also possible. ```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}) ``` ### Information on the model conversion The following attributes can obtain information about the model conversion. See [Model Conversions](https://amplify.fixstars.com/en/docs/amplify/v1/conversion.md) for details. | | | | --- | --- | | [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | The information on the intermediate model | | [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | The information on the graph embedding | ### Information on the response of the solver The [`solve`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function calls the `solve(...)` method of a solver client to run the solver after the model conversion and graph embedding have been performed. The object returned by the solver client can be obtained from the [`client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) attribute. ```pycon >>> type(result.client_result) ``` The type of the [`client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) depends on the type of the solver client. See [Client details](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md) and its subpages for more information about the result type of each solver client. ### Information on the execution time You can obtain information about various execution times through the following attributes. See [Execution Time information](https://amplify.fixstars.com/en/docs/amplify/v1/timing.md) for more information. | | | | --- | --- | | [`total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | Time taken to [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) | | [`response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | Time between sending a request to the solver and receiving a response | | [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | Time spent by the solver in optimization | ## Decision variable evaluation The solution values can be assigned to a variable array used in the formulation. The assigned result is returned as a NumPy array with the same [`shape`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape) as the variable array. The following performs the assignment to evaluate a variable array. The [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) attribute of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) object is passed to the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method of the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class. > [!TIP] > > **Tip** > > The solution in the result can be obtained by retrieving the best result of the run with the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) attribute or by accessing the elements in the same way as for a list. ```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.] ``` If a variable not used in the formulation is included, as in `q[3]` or `q[4]` above, it is assigned one of its possible values by default. In the above example, the Amplify SDK assigns `0` as the default value for the binary variable. The `default` keyword argument to the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method can change the value used if no evaluation is performed; if the `default` keyword argument is given as a number, variables not passed to the solver are assigned that value. ```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] > > **Note** > > A warning is printed if a value outside the bounds of the variable is given, such as `default=3`, as shown above. If the `default` keyword argument is [`None`](https://docs.python.org/3/library/constants.html#None), variables not passed to the solver remain as they are. Only in this case the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method return a [`PolyArray`](https://amplify.fixstars.com/en/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] > > **Attention** > > Some variables may not be passed to the solver even if they are included in the model. This is because model conversions such as penalty function generation or graph embedding can cause terms to cancel each other out. ## Polynomial evaluation The result of evaluating the objective function of the input model with the solution returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function can be obtained using the [`objective`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.objective) attribute of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) object. ```pycon >>> solution = result.best >>> solution.objective -1.0 ``` On the other hand, there are cases where you want to evaluate a polynomial other than the objective function with the solution returned by the solver, for example, when the objective function is expressed as the sum of several polynomials. In this case, we pass the [`values`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.values) attribute of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) object to [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)’s [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.evaluate) method, just as we would evaluate an array of variables. ```pycon >>> objective_1 = q[0] * q[1] # The first term of the objective function >>> objective_1.evaluate(solution.values) 0.0 ``` > [!TIP] > > **Hint** > > The behavior when the polynomial contains variables not passed to the solver is similar to the [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) method of the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class; the `default` keyword argument can change this behavior. ## Constraint evaluation If you want to know if the resulting solution satisfies the constraints, you can check with the [`feasible`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.feasible) attribute of the [`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution) class. ```pycon >>> solution.feasible True ``` By default, this will always be [`True`](https://docs.python.org/3/library/constants.html#True) because the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function retrieves only solutions that satisfy all constraints in the model. To change this behavior and allow the solver to retrieve solutions that do not satisfy the constraints, pass a [`bool`](https://docs.python.org/3/library/functions.html#bool) to the `filter_solution` keyword argument of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function upfront or set [`filter_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.filter_solution) of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class to [`False`](https://docs.python.org/3/library/constants.html#False) afterward. Let’s test this by adding a constraint to the model that cannot be satisfied inconsistently. ```python # Create an objective function and constraints 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") # Define a model (with conflicting constraints) model = objective + constraint1 + constraint2 # Get the result of the run result = solve(model, client) ``` You cannot retrieve the solution from [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) if the solution filter is enabled. ```python >>> result.best.feasible Traceback (most recent call last): File "", line 1, in RuntimeError: result has no feasible solution ``` Turning off the solution filter allows us to obtain solutions that do not satisfy the constraints. ```pycon >>> result.filter_solution = False >>> result.best.feasible False ``` Suppose you obtained a solution that does not satisfy a constraint for some reason, such as model configuration, penalty function weights, or solver settings. In that case, it may be desirable to determine which constraint was not satisfied. You can check whether the constraint conditions are satisfied by passing the solution returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to the [`is_satisfied()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint.is_satisfied) method of the [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) class. ```python >>> constraint1.is_satisfied(result.best.values) True >>> constraint2.is_satisfied(result.best.values) False ``` In the example above, we see that `constraint2` could not be satisfied. We can also mechanically identify constraints from the list of constraints in the model that are not satisfied, as follows. This method is useful when adjusting and rerunning the penalty function weights. ```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"})] ``` --- # Execution Time information The Amplify SDK provides an interface to obtain information of various execution times when solving combinatorial optimization problems. [![_images/timing_light.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_light.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_light.drawio.svg) [![_images/timing_dark.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_dark.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_dark.drawio.svg) ## Types of available time information The following table shows the types of execution time information that you can obtain as [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) objects. | | | | --- | --- | | [`amplify.Result.total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | The total time taken by [`amplify.solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). | | [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | The time between sending the query to the solver and receiving the response. | | [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | The time the solver used to solve the problem. | | [`amplify.Result.Solution.time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) | For each solution the solver returns, this is the time from the start of the solver’s search until the solver obtains the solution. | ## Example of obtaining execution time An example of obtaining execution time is shown below. First, we execute the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to obtain a [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object. ```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) ``` The [`total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) attribute of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) represents the time from the start to the end of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. This time includes the response time of the solver, plus the processing time taken by the Amplify SDK to perform various conversions and create the query data to pass to the solver. ```pycon >>> result.total_time datetime.timedelta(seconds=1, microseconds=870877) ``` The [`response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) attribute of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) represents the time between sending the request to the solver in the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function and receiving the response. ```pycon >>> result.response_time datetime.timedelta(seconds=1, microseconds=865211) ``` The [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) attribute of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) represents the time taken by the solver to find the solution. This time is usually the value contained in the response from the solver. ```pycon >>> result.execution_time datetime.timedelta(microseconds=980543) ``` For each solution ([`Solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution)) in the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result), the time between starting the solver search and finding the solution can be retrieved using the [`time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.Solution.time) attribute. This is usually the value contained in the solver response, but if the solver does not return such information, it will be the same value as the [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) attribute. ```pycon >>> result.best.time datetime.timedelta(microseconds=27925) ``` When the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function is run with the `dry_run` option, [`total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) is approximately equal to the time it took the Amplify SDK to convert the model and generate the query data. Also, [`response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) and [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) will be zero. ```pycon >>> dry_run_result = solve(model, client, dry_run=True) >>> dry_run_result.total_time datetime.timedelta(microseconds=59) ``` ## Plotting the time obtaining the solution For a solver configured to return multiple solutions, we will show you how to plot the time the solver obtained each solution. Such a plot allows us to see the solver’s solutions at a given time during the solver execution. You can use the convergence of the solution to determine if the run time is too short or too long. For example, the following figure shows how Amplify Annealing Engine (AE) updates the solution objective values for a 50-city random traveling salesperson problem. The first step is to create the model. See β€œ[Traveling Salesperson Problem](https://amplify.fixstars.com/en/docs/amplify/v1/tsp.md)” for details on the formulation. ```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 ``` Now, we set the solver client. By default, Amplify AE v1 returns all solutions found during the search. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() client.parameters.time_limit_ms = 1000 # Timeout is 1000 ms ``` Run the solver and plot the times and objective function values of all solutions obtained. ```python from amplify import solve import matplotlib.pyplot as plt # Run the solver result = solve(model, client) # Get time and objective function values for each solution times = [solution.time.total_seconds() for solution in result] objective_values = [solution.objective for solution in result] # Plot plt.scatter(times, objective_values) plt.plot(times, objective_values) plt.xlabel("elapsed time in seconds") plt.ylabel("objective value") plt.grid(True) ``` [![_images/eabb296cd92bab6fe2327ddeb0b0cf9ec1d969d1ae12163a9db457e8463cf828.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/eabb296cd92bab6fe2327ddeb0b0cf9ec1d969d1ae12163a9db457e8463cf828.png)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/eabb296cd92bab6fe2327ddeb0b0cf9ec1d969d1ae12163a9db457e8463cf828.png) History of solutions obtained by Amplify AE for the 50-city traveling salesperson problem You can retrieve the initial and best solutions of the search and plot against each other as follows. ```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() # Plot of the initial solution tsp_plot(q.evaluate(result[-1].values), x, y) # Plot of the best solution tsp_plot(q.evaluate(result[0].values), x, y) ``` ![_images/bc4a5b25cc63521078b8b30468409c2e03a9fff64995e30d2dcff650acf29503.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/bc4a5b25cc63521078b8b30468409c2e03a9fff64995e30d2dcff650acf29503.png) Path (0.02 seconds) of the initial solution ![_images/c921d5753a37df19d0163e6f99749dbc0e3cec10d9559b83c1087143fe9d0f88.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/c921d5753a37df19d0163e6f99749dbc0e3cec10d9559b83c1087143fe9d0f88.png) Path (0.84 seconds) of the best solution --- # Client details The Amplify SDK provides client classes for the solvers that you can run from the SDK. The client classes wrap each solver’s API and provide an interface for configuring the solver and setting execution parameters and methods for requesting the API. Solvers are available in various formats, including WEB API, executable files, and library APIs, but can be handled consistently through the solver client classes of the Amplify SDK. In addition, the Amplify SDK uses a common interface in the client class to allow abstraction of solver execution and analysis of results, in addition to model transformation and graph embedding processes. This page describes the common interfaces provided by the solver clients, and we describe the functions and features specific to each solver client in their respective subpages. ## Client class The client class provides the following three general types of interfaces. * Setting solver execution parameters. * Retrieving client settings and solver information. * Calling solver-provided APIs The common interface for the solver clients is as follows. Interfaces that are only valid for some solvers are classified by the tag assigned to each solver in [the list of solver clients](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md#solver-clients). For solver-specific interfaces, see the subpage for each solver. **Execution parameters**: **`parameters`: [`object`](https://docs.python.org/3/library/functions.html#object)** Returns a parameter class for retrieving and setting the solver execution parameters. The type of parameter class varies from solver to solver but is designed to retrieve and set all possible execution parameters. For more parameter information, see the individual solver subpages and the solver API reference. > [!NOTE] > > **Note** > > For all solver attributes, if [`None`](https://docs.python.org/3/library/constants.html#None) is available, it means it is not set. The Amplify SDK does not set or add the attributes to [`None`](https://docs.python.org/3/library/constants.html#None) for the query data. This procedure is to force the solver to use default values. **Solver information**: **`acceptable_degrees`: [`amplify.AcceptableDegrees`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AcceptableDegrees.md#amplify.AcceptableDegrees)** Retrieves the degree of the problem that the solver can handle. See β€œ[Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md)” for details. **`version`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** Retrieves the solver version information. For remote solvers, you may need to set a token to use this interface since the API may be queried. For local solvers, this retrieves the version information for the executable or library. **Quadratic polynomial graph structure** Graph: **`graph`: [`Graph`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph)** Obtains the solver-specific graph structure. See β€œ[Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md)” for details. **WEB API Connection setting** ☁️ Cloud: **`url`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** Gets and sets the solver endpoint URL. **`token`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** Gets and sets the authentication information such as API token. **`proxy`: [`str`](https://docs.python.org/3/library/stdtypes.html#str)** Gets and sets a proxy server to use for the connection. See β€œ[Proxy Server Settings](https://amplify.fixstars.com/en/docs/amplify/v1/proxy.md)” for details. **Path to executable file and library** πŸ’» Local: **`library_path`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** Specifies the file path of the solver library. **Save sent and received data** ☁️ Cloud πŸ’» Local: **`write_request_data`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** Saves the query data sent to the solver to the specified file path. Data format varies by solver. **`write_response_data`: [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike)** Saves the response data received from the solver to the specified file path. The data format is different for each solver. **Solver execution**: **`solve(...)`:** The `solve(...)` method is implemented in each solver client as a function to execute the solver. This is a wrapper function for the solver API. > [!NOTE] > > **Note** > > Usually, the user does not need to call this method directly. Use the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function instead. The API can be called with a polynomial ([`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)), matrix ([`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)), or constraint ([`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) or [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) argument, or both, depending on what is available to the solver API. However, unlike the global [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, no model transformation or graph embedding is performed. Therefore, if a variable type, order, or constraint condition is given that the solver cannot handle, an exception will be thrown. The return type of the `solve(...)` method is different for each solver. For example, in the case of Amplify AE ([`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient)), it is an instance of the class [`amplify.AmplifyAEClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result). This class is classified so that the data structure of the response data returned by the solver is modified as little as possible. ### Interaction with [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function After performing the model conversion and graph embedding, the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function calls the solver client’s `solve(...)` method to execute the solver and analyze the returned data to obtain information about the solution and execution time. The instance of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class returned by the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function stores the data returned by the solver, the response time, and the execution time in the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`amplify.Result.client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | `Client.Result` | Result of solver client execution (response data) | | [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | Solver internal execution time | | [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) | Solver response time | --- # Fixstars Amplify ## Fixstars Amplify Annealing Engine v1 Fixstars Amplify Annealing Engine (Amplify AE) is a solver provided by Fixstars Amplify. It uses heuristic algorithms based on simulated annealing on GPUs, leveraging their parallel computing capabilities to search for solutions with high speed and accuracy. > [!TIP] > > **Tip** > > A free API token is available upon [user registration](https://amplify.fixstars.com/register). **Solver specification**: | | | | --- | --- | | Client class | [`amplify.AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.parameters) | [`amplify.AmplifyAEClient.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.AmplifyAEClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.AmplifyAEClient.Result.execution_time_ms`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result.execution_time_ms) | | API Method | REST API (JSON) | | API reference | [πŸ“– Documents](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae.md) | * When the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) property is set to [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Constraint) (default): | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 4th | - | - | - | | Equality constraint | 4th | - | - | - | | Inequality constraint | 4th | - | - | - | * When the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) property is set to [`Pubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Pubo): | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 4th | - | - | - | | Equality constraint | 4th\* | - | - | - | | Inequality constraint | 4th\* | - | - | - | \*: must give a penalty function. * When the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) property is set to [`Qubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Qubo): | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | 2nd\* | - | - | - | | Inequality constraint | 2nd\* | - | - | - | \*: must give a penalty function. **Client class**: In addition to the [common interface of the client class](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), it has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.solver) | [`Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver) | Set the solve mode for Amplify AE. The default is [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Constraint). By setting it to [`Pubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Pubo) or [`Qubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Solver.Qubo), you can perform solves that emulate the PUBO / QUBO solvers. For details, please refer to the Amplify AE [documentation](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae.md). | | [`compression`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Compress the requested data before sending. The default is [`True`](https://docs.python.org/3/library/constants.html#True); setting it to [`False`](https://docs.python.org/3/library/constants.html#False) will reduce request data compression time, but may increase transmission time. | **Configuration example**: Here is an example configuration. For parameter details, please refer to the [Amplify AE documentation](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/api_reference.md). ```python from amplify import AmplifyAEClient from datetime import timedelta client = AmplifyAEClient() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set the solver mode client.solver = "Constraint" # For general (Default) # client.solver = "Pubo" # For PUBO simulation # client.solver = "Qubo" # For QUBO simulation # Set timeout to 1 second client.parameters.time_limit_ms = timedelta(milliseconds=1000) # Set the number of GPUs to use to 1 client.parameters.num_gpus = 1 # Get all solutions obtained during the search client.parameters.duplicate_solutions = True ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Define decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver version and GPU name: ```python >>> client.version '1.0.0+V100' ``` Obtain detailed [execution time](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solvetiming): ```python # Get GPU annealing time >>> print(result.client_result.execution_time_ms) 0:00:01.008328 # Get queue wait time >>> print(result.client_result.queue_time_ms) 0:00:00.000108 # Get the time of request reception >>> print(result.client_result.submitted_at) 2025-08-25 17:37:38.553593+09:00 # Get the time when the request processing started >>> print(result.client_result.started_at) 2025-08-25 17:37:38.553701+09:00 ``` Obtain [runtime parameter information](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solveinfo): ```python # Number of GPUs used for solving >>> result.client_result.num_gpus 1 # Total flip count of all GPUs tried until the execution result is returned >>> result.client_result.num_flips 1567467520 # Number of solutions (samples) obtained until the execution result is returned >>> result.client_result.num_samplings 58 ``` ## [Deprecated] Fixstars Amplify Annealing Engine v0 > [!IMPORTANT] > > **Deprecated** > > Amplify AE v0 is now deprecated. Accordingly, [`amplify.FixstarsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) is also deprecated. > For new usage, please use Amplify AE v1 and [`amplify.AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient). The QUBO solver provided by [Fixstars Amplify](https://amplify.fixstars.com/) uses an algorithm based on Simulated Annealing implemented on GPUs. > [!TIP] > > **Tip** > > A free API token is available upon [user registration](https://amplify.fixstars.com/register). **Solver specification**: | | | | --- | --- | | Client class | [`amplify.FixstarsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.parameters) | [`amplify.FixstarsClient.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FixstarsClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FixstarsClient.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.Result.execution_time) | | API method | REST API (JSON) | | API reference | [πŸ“– API Reference](https://amplify.fixstars.com/en/docs/amplify/v0/amplify-ae/reference.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | 2nd\* | - | - | - | | Inequality constraint | 2nd\* | - | - | - | \*: must give a penalty function. **Client class**: In addition to the [common interface of the client class](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), it has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`compression`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Compress the requested data before sending. The default is [`True`](https://docs.python.org/3/library/constants.html#True); setting it to [`False`](https://docs.python.org/3/library/constants.html#False) will reduce request data compression time, but may increase transmission time. | **Configuration example**: ```python from amplify import FixstarsClient from datetime import timedelta client = FixstarsClient() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set timeout to 1 second client.parameters.timeout = timedelta(milliseconds=1000) # Set the number of GPUs to use to 1 client.parameters.num_gpus = 1 # Get all solutions obtained during the search client.parameters.outputs.num_outputs = 0 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Define decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver version: ```python >>> client.version 'v0.8.5-V100' ``` Obtain detailed execution time: ```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 ] }) ``` Obtain runtime parameter information: ```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/) offers a quantum annealing machine (quantum processing unit; QPU) that allows you to input QUBO or a combinatorial optimization problem expressed as a quadratic polynomial in Ising variables. > [!TIP] > > **Tip** > > You can [register as a Fixstars Amplify user](https://amplify.fixstars.com/register) to get a free trial API token for D-Wave Systems, or get an API token with your D-Wave Systems account. > [!TIP] > > **Hint** > > To use D-Wave machines, install with extra packages: > > ```bash > $ python3 -m pip install -U 'amplify[dwave]' > ``` > > > [!WARNING] > > > > **Caution** > > > > Some extra packages may not be available depending on your Python version. See [Supported Environments](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/quickstart.md#quantum-support-env) for details. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [Execution results](https://amplify.fixstars.com/en/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) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["timing"]["qpu_access_time"]` | | API method | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | Execution parameter reference | [πŸ“– Parameters Reference](https://docs.dwavequantum.com/en/latest/quantum_research/solver_parameters.html#qpu-solver-parameters) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd\* | 2nd\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems involving both binary and Ising variables at the same time are not handled. **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Get or set the name of the D-Wave Sampler to use | | [`solver_names`](https://amplify.fixstars.com/en/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)] | Get a list of D-Wave Sampler names that can be specified with the set token. | | [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | Get the solver properties to use (returns the same as [`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)) | **Configuration example**: ```python from amplify import DWaveSamplerClient client = DWaveSamplerClient() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Specify the solver to use # (Specify one of the client.solver_names) client.solver = "Advantage2_system1" # Set the number of runs to 1000 client.parameters.num_reads = 1000 ``` > [!NOTE] > > **See also** > > [`amplify.DWaveSamplerClient.parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.parameters) exposes each solver parameter as a typed attribute, and setting an unknown one raises [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError). Set an attribute to `None` to restore the solver default. For the meaning of each parameter, refer to [πŸ“– Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html). > > [`annealing_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.annealing_time), [`programming_thermalization`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.programming_thermalization) and [`readout_thermalization`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.Parameters.readout_thermalization) are **in microseconds**. They can be set either with a number of microseconds or with a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta), but they are read back as a [`float`](https://docs.python.org/3/library/functions.html#float) of microseconds, because [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) cannot represent a fraction of a microsecond. > > ```python > client.parameters.annealing_time = 0.5 # 0.5 microseconds > client.parameters.annealing_time = timedelta(microseconds=20) # 20.0 microseconds > ``` > > You can also get them from [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.properties) (the output will vary depending on the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient.solver)) as follows. > > ```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.', > ...} > ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver to use (if not specified, it will be determined automatically): ```python >>> client.solver 'Advantage_system4;graph_id=01d07086e1' ``` Obtain the list of solvers currently available: ```python >>> client.solver_names ['Advantage_system6;graph_id=01dae5a273', 'Advantage_system4;graph_id=01d07086e1', 'Advantage2_system1;graph_id=01138bbada'] ``` Obtain detailed execution time: ```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 This is a hybrid solver from [D-Wave Systems](https://www.dwavesys.com/) that works with quantum annealing machines (QPUs) and classical algorithms, allowing input of combinatorial optimization problems expressed as QUBOs or quadratic polynomials in Ising variables, and supporting input of larger problems than [D-Wave Sampler](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient). > [!TIP] > > **Tip** > > You can [register as a Fixstars Amplify user](https://amplify.fixstars.com/register) to get a free trial API token for D-Wave Systems, or get an API token with your D-Wave Systems account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.LeapHybridSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [Execution result](https://amplify.fixstars.com/en/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) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["run_time"]` | | API method | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | Execution parameter reference | [πŸ“– Parameters Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_bqm_parameters.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | 2nd | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Get and set the name of Leap’s Hybrid BQM Sampler. | | [`solver_names`](https://amplify.fixstars.com/en/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)] | Get a list of Leap’s Hybrid BQM sampler names that can be specified with the set token. | | [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | Get the properties of the solver to use (returns the same result as [`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)) | **Configuration example**: ```python from amplify import LeapHybridSamplerClient client = LeapHybridSamplerClient() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Get the solver to use # (if not specified, it will be determined automatically) # print(client.solver) # Get a list of available solvers # print(client.solver_names) # Specify which solver to use # (Specify one of the names in client.solver_names) client.solver = "hybrid_binary_quadratic_model_version2p" # Set the execution time limit to 5 seconds client.parameters.time_limit = 5 ``` > [!NOTE] > > **See also** > > [`amplify.LeapHybridSamplerClient.parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.parameters) exposes each solver parameter as a typed attribute, and setting an unknown one raises [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError). Set an attribute to `None` to restore the solver default. [`time_limit`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.Parameters.time_limit) is in seconds and can be set either with a number or with a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta). For the meaning of each parameter, refer to [πŸ“– Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html). > > You can also get them from [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.properties) as follows (the output will vary depending on the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient.solver)) > > ```python > >>> client.properties["parameters"] > {'time_limit': 'Maximum requested runtime in seconds.'} > ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver to use (if not specified, it will be determined automatically): ```python >>> client.solver 'hybrid_binary_quadratic_model_version2p' ``` Obtain the list of currently available solvers: ```python >>> client.solver_names ['hybrid_binary_quadratic_model_version2p'] ``` Obtain detailed execution time: ```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 This is a hybrid solver from [D-Wave Systems](https://www.dwavesys.com/) that uses quantum annealing machines (QPUs) and classical algorithms to solve combinatorial optimization problems with QUBO or Ising, integer or real variable objective functions, and one or more constraints. > [!TIP] > > **Tip** > > You can [register as a Fixstars Amplify user](https://amplify.fixstars.com/register) to get a free trial API token for D-Wave Systems, or get an API token with your D-Wave Systems account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.parameters) | `amplify.DWaveClientParameters` | | [Execution result](https://amplify.fixstars.com/en/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) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | `dimod.sampleset.SampleSet.info["run_time"]` | | API method | REST API ([SAPI](https://docs.dwavequantum.com/en/latest/leap_sapi/sapi_rest.html)) | | Execution parameter reference | [πŸ“– Parameters Reference](https://docs.dwavequantum.com/en/latest/industrial_optimization/solver_cqm_parameters.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | 2nd | 2nd | 1st | | Equality constraint | 2nd | 2nd | 2nd | 1st | | Inequality constraint | 2nd | 2nd | 2nd | 1st | **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Get and set the name of Leap’s Hybrid CQM Sampler. | | [`solver_names`](https://amplify.fixstars.com/en/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)] | Get the list of Leap’s Hybrid CQM Sampler names you can use with the set token. | | [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.properties) | [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) | Get the properties of the solver to use (returns the same result as [`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)) | **Configuration example**: ```python from amplify import LeapHybridCQMSamplerClient client = LeapHybridCQMSamplerClient() # Set an API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Specify the solver to use # (Specify a name from client.solver_names) client.solver = "hybrid_constrained_quadratic_model_version1p" # Set an execution time limit to 3 seconds client.parameters.time_limit = 3 ``` > [!NOTE] > > **See also** > > [`amplify.LeapHybridCQMSamplerClient.parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.parameters) exposes each solver parameter as a typed attribute, and setting an unknown one raises [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError). Set an attribute to `None` to restore the solver default. [`time_limit`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.Parameters.time_limit) is in seconds and can be set either with a number or with a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta). For the meaning of each parameter, refer to [πŸ“– Parameters Reference](https://docs.dwavesys.com/docs/latest/c_solver_parameters.html). > > You can also get them from [`properties`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.properties) as follows (the output will vary depending on the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient.solver)) > > ```python > >>> client.properties["parameters"] > {'time_limit': 'Maximum requested runtime in seconds.'} > ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver (if not specified it will be automatically set): ```python >>> client.solver 'hybrid_constrained_quadratic_model_version1p' ``` Obtain the list of the solvers currently available: ```python >>> client.solver_names ['hybrid_constrained_quadratic_model_version1p'] ``` Obtain the solver version: ```python >>> client.version '1.12' ``` Obtain detailed execution time: ```python >>> result.client_result.info {'constraint_labels': [], 'qpu_access_time': 15846, 'charge_time': 4305380, 'run_time': 4305380, 'problem_id': '47db4ee7-2e60-4c99-99ae-b596914d4907'} ``` --- # TOSHIBA ## SQBM+ v2.0.3 SQBM+ is a [TOSHIBA](https://www.global.toshiba/jp/products-solutions/ai-iot/sbm.html)-developed quantum-inspired optimization solution with a simulated bifurcation machine at its core. > [!TIP] > > **Tip** > > Available as a paid option on AWS Marketplace or Fixstars Amplify. > [!TIP] > > **Tip** > > The available solvers and variable types vary depending on the version of the SQBM+ server. > You can check the version from [`version`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.version) property of this client. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.ToshibaSQBM2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.parameters) | [`amplify.ToshibaSQBM2Client.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.ToshibaSQBM2Client.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.ToshibaSQBM2Client.Result.time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result.time) | | API method | REST API (HDF5/JSON) | | API reference | [πŸ“– User Guide (v2.0.3)](https://amplify.fixstars.com/en/docs/amplify/v1/_downloads/7e21cdf718c667d7e3b709b4d6413bbd/User_Manual-SQBM%2B_for_On-premises.pdf) | * When [`Qubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qubo) is set in the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) property (default): | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | * When [`Qplib`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qplib) is set in the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) property: | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | 2nd | | Equality constraint | 1st | - | - | 1st | | Inequality constraint | 1st | - | - | 1st | * When [`Pubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Pubo) is set in the [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) property: | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 4th | - | - | 4th | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes and a method. | Attribute | Data type | Details | | --- | --- | --- | | [`solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.solver) | [`Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Specify the solver to use from [`Qubo`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qubo) (default) and [`Qplib`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Solver.Qplib). | | [`compression`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.compression) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Compress the request data before sending. The default value is [`True`](https://docs.python.org/3/library/constants.html#True); setting to [`False`](https://docs.python.org/3/library/constants.html#False) will reduce the compression time of the request data, but may increase the communication time. | | Method | Return type | Details | | --- | --- | --- | | [`health_check()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.health_check) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Query the health check API to verify that the solver is working properly. | **Configuration example**: ```python from amplify import ToshibaSQBM2Client from datetime import timedelta client = ToshibaSQBM2Client() # Set API token # (Not required if using AWS version) client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set URL (required if using AWS version) # client.url = "http://xxx.xxx.xxx.xxx:8000/" # Specify a solver # (Qubo, Qplib, or Pubo) client.solver = "Qplib" # Set execution time to 1 second client.parameters.timeout = timedelta(milliseconds=1000) ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Perform health check API: ```python >>> client.health_check() True ``` Obtain the solver version: ```python >>> client.version '2.0.3' ``` Obtain runtime parameter information: ```python >>> result.client_result.param ToshibaSQBM2Client.Parameters({ "steps": 1, "dt": 1.0, "C": 0.1502210944890976, "algo": 204 }) ``` --- # Fujitsu ## Fujitsu DA4 Solver [Fujitsu DA4](https://www.fujitsu.com/global/services/business-services/digital-annealer/) is Fujitsu’s QUBO solver with the 4th-generation Digital Annealing Unit (DAU (GPU)). **Solver specification**: | | | | --- | --- | | Client class | [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.parameters) | [`amplify.FujitsuDA4Client.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FujitsuDA4Client.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FujitsuDA4Client.SolverTiming.solve_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.SolverTiming.solve_time) | | API method | REST API (JSON) | | API reference | [πŸ“– API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v4-en.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | \*/\*\* | - | - | - | | Inequality constraint | 1st | - | - | - | \*: One-way-one-hot and two-way-one-hot constraints are supported. \*\*: Can be specified as penalty functions. **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes and methods. | Attribute | Data type | Details | | --- | --- | --- | | [`type_id`](https://amplify.fixstars.com/en/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) | Specify the type ID when using the [Premium API](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v3c-v4-premium-en.html). | | [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Pass the penalty function weight setting for the constraint to the `penalty_binary_polynomial` parameter if set to [`True`](https://docs.python.org/3/library/constants.html#True) (default: [`True`](https://docs.python.org/3/library/constants.html#True)). If set to [`False`](https://docs.python.org/3/library/constants.html#False), the penalty function is added to the objective function. | | [`set_inequalities`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_inequalities) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | Pass a first-order inequality constraint to the `inequalities` parameter (default: [`True`](https://docs.python.org/3/library/constants.html#True)) if set to [`True`](https://docs.python.org/3/library/constants.html#True). If set to [`False`](https://docs.python.org/3/library/constants.html#False), a penalty function for the inequality constraint is generated and processed according to [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial). | | [`set_one_way_one_hot_groups`](https://amplify.fixstars.com/en/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) | If set to [`True`](https://docs.python.org/3/library/constants.html#True), detect one-hot constraints from the beginning of the decision variables as much as possible and pass them to the `one_way_one_hot_groups` parameter (default: [`False`](https://docs.python.org/3/library/constants.html#False)). If set to [`False`](https://docs.python.org/3/library/constants.html#False), or if the one-hot constraints cannot be passed to the parameter, penalty functions are generated and processed according to [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial). | | [`set_two_way_one_hot_groups`](https://amplify.fixstars.com/en/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) | If set to [`True`](https://docs.python.org/3/library/constants.html#True), detect equally spaced `one_way_one_hot_groups`, and if additional one-hot constraints can be added that satisfy the `two_way_one_hot_groups` condition, they are detected and passed to the `two_way_one_hot_groups` parameter (default: [`False`](https://docs.python.org/3/library/constants.html#False)). If set to [`False`](https://docs.python.org/3/library/constants.html#False), or if no one-hot constraints can be passed to the parameter, penalty functions are generated and processed according to [`set_penalty_binary_polynomial`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_penalty_binary_polynomial). If set to [`True`](https://docs.python.org/3/library/constants.html#True) at the same time as [`set_one_way_one_hot_groups`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.set_one_way_one_hot_groups), `two_way_one_hot_groups` detection is prioritized. | | Method | Return type | Details | | --- | --- | --- | | [`health_check()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.health_check) | [`CommonError`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.CommonError) | [`None`](https://docs.python.org/3/library/constants.html#None) | Query the health check API and check if the solver is working properly. Returns [`None`](https://docs.python.org/3/library/constants.html#None) if normal. | | [`async_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.async_solve) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Execute the `/async/qubo/solve` API asynchronously and return the job ID. | | [`get_jobs()`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatusInfo)] | Obtain a list of job statuses. | | [`cancel_job()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.cancel_job) | [`JobStatus`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatus) | Attempt to abort a job by specifying its job ID | | [`get_job_result()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.get_job_result) | [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | Obtain the completed result by specifying the job ID. | | [`delete_job_result()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.delete_job_result) | [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | Obtain a completed result and delete the result by specifying the job ID. | > [!NOTE] > > **Note** > > [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.solve) in the common interface of the client class is a synchronous version of [`async_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.async_solve). It waits until the job has completed execution and returns the result of the execution. **Configuration example**: ```python from amplify import FujitsuDA4Client from datetime import timedelta client = FujitsuDA4Client() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Enable detection of one-way one-hot groups client.set_one_way_one_hot_groups = True # Set the execution time to 100 seconds client.parameters.time_limit_sec = timedelta(seconds=100) ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run a solver result = solve(model, client) ``` Perform health check API: ```python >>> client.health_check() ``` Obtain a list of jobs: ```python >>> client.get_jobs() [FujitsuDA4ClientJobStatusInfo({"job_id":"...","job_status":"Done","start_time":"..."}), FujitsuDA4ClientJobStatusInfo({"job_id":"...","job_status":"Done","start_time":"..."}) ...] ``` Obtain and delete job result: ```python >>> client.delete_job_result("...") {"qubo_solution":{"progress":[{"energy":417.0,"penalty_energy":366429644.0,"time":1.179},... ``` Obtain the solver version: ```python >>> client.version 'v4' ``` Obtain detailed execution time: ```python >>> result.client_result.qubo_solution.timing FujitsuDA4Client.SolverTiming({ "solve_time": 101963.0, "total_elapsed_time": 101963.0 }) ``` ## Fujitsu DA3c Solver [Fujitsu DA3c](https://www.fujitsu.com/global/services/business-services/digital-annealer/) is Fujitsu’s QUBO solver with the 3rd-generation Digital Annealing Unit (DAU (GPU)). > [!NOTE] > > **Note** > > The client class specification is the same as [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client). **Solver specification**: | | | | --- | --- | | Client class | [`amplify.FujitsuDA3cClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.parameters) | [`amplify.FujitsuDA3cClient.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.FujitsuDA3cClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.FujitsuDA3cClient.SolverTiming.solve_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient.SolverTiming.solve_time) | | API method | REST API (JSON) | | API reference | [πŸ“– API Reference](https://portal.aispf.global.fujitsu.com/apidoc/da/jp/api-ref/da-qubo-v3c-ja.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | \*/\*\* | - | - | - | | Inequality constraint | 1st | - | - | - | \*: One-way-one-hot and two-way-one-hot constraints are supported. \*\*: Can be specified as penalty functions. --- # NEC ## NEC Vector Annealing (VA) Service 2.0 > [!WARNING] > > **Warning** > > NEC VA Service 2.0 ended on April 1, 2025. [NEC](https://jpn.nec.com/nec-vector-annealing-service/) provides the QUBO solver, which runs on the vector supercomputer SX-Aurora TSUBASA. The Amplify SDK provides [`NECVA2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) which calls the NEC Vector Annealing Service 2.0 API with automatically detected and configured request parameters. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.NECVA2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.parameters)1 | [`amplify.NECVA2Client.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result)2 | [`amplify.NECVA2Client.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) ([details](#clients-necva2client-exectime)) | [`amplify.NECVA2Client.Result.Timing.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time) | | API method3 | SAC Service Client (Python) | | API reference | [πŸ“– User Guide](https://amplify.fixstars.com/en/docs/amplify/v1/_downloads/bbcfcea8bf765d6774aa727a387e0e9c/nec_vector_annealing_service_2.0_user_guide_v3_en.pdf) | 1: Corresponding to [API reference β€œ3-3-2 solve_params”](https://amplify.fixstars.com/en/docs/amplify/v1/_downloads/bbcfcea8bf765d6774aa727a387e0e9c/nec_vector_annealing_service_2.0_user_guide_v3_en.pdf) 2: Corresponding to [API reference β€œ3-4. Response”](https://amplify.fixstars.com/en/docs/amplify/v1/_downloads/bbcfcea8bf765d6774aa727a387e0e9c/nec_vector_annealing_service_2.0_user_guide_v3_en.pdf) 3: No need for additional installation | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | - | - | | Equality constraint | \* | - | - | - | | Inequality constraint | \* | - | - | - | \*: Several 1st and 2nd order constraints described later are supported. **Client class**: In addition to the [common interface of the client class](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), it has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`set_fixed`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_fixed) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `fixed` constraints are detected from the model’s constraints as many as possible and are passed to the `fixed` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_onehot`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_onehot) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `onehot` constraints are detected from the model’s constraints as many as possible and are passed to the `onehot` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_andzero`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_andzero) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `andzero` constraints are detected from the model’s constraints as many as possible and are passed to the `andzero` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_orone`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_orone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `orone` constraints are detected from the model’s constraints as many as possible and are passed to the `orone` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_supplement`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_supplement) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `supplement` constraints are detected from the model’s constraints as many as possible and are passed to the `supplement` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_maxone`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_maxone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `maxone` constraints are detected from the model’s constraints as many as possible and are passed to the `maxone` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | | [`set_minmaxone`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.set_minmaxone) | [`bool`](https://docs.python.org/3/library/functions.html#bool) | If set as [`True`](https://docs.python.org/3/library/constants.html#True), `minmaxone` constraints are detected from the model’s constraints as many as possible and are passed to the `minmaxone` parameter which is a flip option. (Default: [`True`](https://docs.python.org/3/library/constants.html#True)) | Flip option constraints are detected only when a constraint expression is set that matches the following form, including coefficients. $q_1, q_2, \dots , q_N$ ($N$ is a natural number) are binary variables independent of each other and $m, n, k$ are integer constants. | Attribute for the flip option | Form of the constraint to be detected | | --- | --- | | [`set_fixed`](https://amplify.fixstars.com/en/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/en/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/en/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/en/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/en/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/en/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/en/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)$ | The flip options for each constraint expression are detected in the same order of precedence as shown in the table above. If a constraint matches multiple flip options, the flip option with the highest priority among those set to [`True`](https://docs.python.org/3/library/constants.html#True) is selected. > [!NOTE] > > **Note** > > Regardless of whether the flip option is enabled, penalty functions of constraints are added to the objective function as needed. **Execution time**: The NEC VA Service 2.0 returns the execution time for each sampling of VA but does not return the total processing time taken to find the solution. Therefore, in addition to the sampling time, the [`NECVA2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) independently measures and returns the response time of the `solve_qubo()` API of the SAC Service Client ([`solve_qubo_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.solve_qubo_time)), the execution time of the the VA ([`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time)) (which is also included in the response time), and the queue time ([`queue_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.queue_time)). These timing attributes are stored in the [`timing`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.timing) attribute of the result class. | Attribute | Details | | --- | --- | | [`amplify.NECVA2Client.Result.Result.time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Result.time) | VA sampling time for each read. | | [`amplify.NECVA2Client.Result.Timing.solve_qubo_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.solve_qubo_time) | Execution time of the `solve_qubo` Python API | | [`amplify.NECVA2Client.Result.Timing.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.execution_time) | Execution time of the VA (including network overhead and queue time) | | [`amplify.NECVA2Client.Result.Timing.queue_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result.Timing.queue_time) | Queue time | **Configuration example**: ```python from amplify import NECVA2Client client = NECVA2Client() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Run in speed mode client.parameters.vector_mode = "speed" ``` **Execution example**: ```python from amplify import VariableGenerator, Model, solve # Define decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) # Print API execution time print(result.execution_time) ``` Obtain the solver version: ```python >>> client.version '2.0.2' ``` Obtain detailed execution time: ```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 ## Hitachi Annealing Cloud Web The CMOS annealing machine provided by [Hitachi](https://annealing-cloud.com/en/index.html). **γ‚½γƒ«γƒγƒΌδ»•ζ§˜**: | | | | --- | --- | | Client class | [`amplify.HitachiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.parameters) | [`amplify.HitachiClient.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters) | | [Execution results](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.HitachiClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.HitachiClient.Result.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result.Result.execution_time) | | API method | REST API (JSON) | | API Reference | [πŸ“– API Reference](https://annealing-cloud.com/en/web-api/reference/v2.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | - | 2nd | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | > [!NOTE] > > **Note** > > There are three types of machines that can be used, specified by [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type). (Default:[`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 4) > > * [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 3: GPU 32bit (int) > > * Can process 256k spins (equivalent to 512x512 King’s graph) using GPGPU. > * [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 4: GPU 32bit (float) > > * Can process 256k spins (equivalent to 512x512 King’s graph) using GPGPU. > * [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 5: ASIC 4bit > > * Can process 147,456 spins (equivalent to a 384x384 King’s graph) in a single annealing. > > Machines of [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) = 3, 5 can only handle models with integer coefficients. > Refer to [API Reference](https://annealing-cloud.com/en/web-api/reference/v2.html) for the range of integer values for each type. > Even if the objective function has only integer coefficients, the model submitted to the solver may contain real values because the Amplify SDK performs model conversion and graph embedding within the [`amplify.solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. > In such cases, Amplify SDK internally converts them to integers by rounding away from zero, which may result in a discrepancy from the intended formulation. > When utilizing these machines, it is recommended to use [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) method directly. (See [here](#hitachiclient-solve)). **Configuration example**: ```python from amplify import HitachiClient client = HitachiClient() # Set API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set Number of annealing runs to 3 client.parameters.num_executions = 3 # Output average value per site of spin client.parameters.outputs.averaged_spins = True # Output the average value of energy client.parameters.outputs.averaged_energy = True ``` **Execution example**: ```python from amplify import VariableGenerator, Model, solve # Create decision variables and the objective function g = VariableGenerator() s = g.array("Ising", 2) f = s[0] * s[1] + s[0] - s[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the solver version: ```python >>> client.version 'v2' ``` Obtain detailed solution: ```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] ] }) ``` ### Execute with client interface [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) method submits the problem directly to the solver using the solver’s API and retrieves the results. This method is useful for problems that are optimized for the topology of the Hitachi CMOS Annealing Machine chip or for problems that are already embedded in the graphs. The CMOS Annealing Machine API defines the Ising variables with coordinates $(x, y)$ on the King’s graph. On the other hand, the Amplify SDK manages variables by ID ([`id`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable.id)). Thus, in the [`amplify.HitachiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) class, the mapping to the coordinates on King’s graph is defined as `id = x + y * graph_size`. Using the `graph_size` corresponding to the [`type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Parameters.type) of the CMOS Annealing Machine, the variables satisfying this relationship can be output as follows. ```python from amplify import VariableGenerator, HitachiClient client = HitachiClient() client.parameters.type = 3 client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" graph_size = client.graph.shape[0] # Size of a side of the graph g = VariableGenerator() # Generate Ising variables on the King's graph of graph_size x graph_size s = g.array("Ising", (graph_size, graph_size)) ``` The array indices of the generated Ising variable array `s` correspond to the coordinates on King’s graph. For example, `s[x, y]` represents the Ising variable at $(x, y)$ on the King’s graph. Then, an objective function [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) must satisfy the following conditions. * Consists only of Ising variables of degree two or less. * Constraints are included in the objective function in advance as a penalty function. * The range of coefficient values is restricted depending on the machine type (see [API Reference](https://annealing-cloud.com/en/web-api/reference/v2.html)) * The indices of a quadratic term are adjacent to the two-dimensional array vertically, horizontally, or diagonally (adjacent on the King’s graph). The following is an example of an objective function that satisfies the above conditions. ```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 ``` The solver response is returned when the created objective function is submitted with the [`amplify.HitachiClient.solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.solve) method. ```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)]] ``` The solution $s'$ for each Ising variable returned by the solver is stored in [`spins`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient.Result.Result.spins) in the form `[[(x, y, s'), ...], ...]`, where `s'` represents the value of the Ising variable at the coordinates $(x, y)$ on the King’s graph. Note that no values are returned for variables that are not used in the objective function. Since multiple solutions may be returned, variable values are stored as a list of lists of tuples. To obtain the solution of the Ising variable on the King’s graph in the same array shape as the variable array `s`, you can do the following. ```python import numpy as np # Generate a zero array of graph_size x graph_size spin_values = np.zeros((graph_size, graph_size)) # Enumerate and assign solutions with index 0 # (If multiple solutions are returned, an appropriate index should be specified) for x, y, s in res.result.spins[0]: spin_values[x, y] = s ``` --- # Gurobi ## Gurobi Optimizer Gurobi Optimizer is a Mixed Integer Programming (MIP) solver provided by Gurobi that can handle quadratic problems in integer and real variables, including QUBO. > [!NOTE] > > **Note** > > To use Gurobi, you need to install the [Gurobi Optimizer](https://www.gurobi.com/solutions/gurobi-optimizer/) and license on the machine running the Amplify SDK. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.GurobiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.parameters) | [`amplify.GurobiClient.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | [`amplify.GurobiClient.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result) | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | [`amplify.GurobiClient.Result.runtime`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result.runtime) | | Supported version | 9.0.0 or later | | API reference | [πŸ“– Reference Manual](https://www.gurobi.com/documentation/current/refman/index.html) | | | Binary variable | Ising variable | Integer variable | Real variable | | --- | --- | --- | --- | --- | | Objective function | 2nd | - | 2nd | 2nd | | Equality constraint | 2nd | - | 2nd | 2nd | | Inequality constraint | 2nd | - | 2nd | 2nd | **Client class**: In addition to [the common interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following method. | Method | Return type | Details | | --- | --- | --- | | [`tune()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.tune) | [`None`](https://docs.python.org/3/library/constants.html#None) | Perform execution parameter search | > [!NOTE] > > **Note** > > [`GurobiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) file output works as follows. > > * **[`write_request_data`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.write_request_data):** > > Output the model to a file with the specified file path extension. > Possible file extensions are `.mps`, `.rew`, `.lp`, `.rlp`, `.dua/.dlp` (as a model of LP dual problem). > * **[`write_response_data`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.write_response_data):** > > Output the solution in a file with the specified file path extension. > Possible file extensions are `.sol` or `.json`. > [!NOTE] > > **See also** > > See [Gurobi Parameters](https://www.gurobi.com/documentation/current/refman/parameters.html#sec:Parameters) for details on the attributes of the [`Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) class that can be specified in [`parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.parameters). > Note that the attribute names of the [`Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) class are standardized to *snake_case*. > [!NOTE] > > **Note** > > All attributes of the [`Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters) class are initialized to [`None`](https://docs.python.org/3/library/constants.html#None) (unset) by default, but some attributes are explicitly passed to Gurobi when [`None`](https://docs.python.org/3/library/constants.html#None) is specified for convenience, as follows. > > * **[`log_to_console`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters.log_to_console):** > > Contrary to Gurobi’s default (`1`), `0` (no output) is treated as default. > * **[`seed`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Parameters.seed):** > > Contrary to Gurobi’s default (`0`), this is initialized by generating a hardware random number. **Configuration example**: ```python from amplify import GurobiClient from datetime import timedelta client = GurobiClient() # Set installation path # (necessary if the installation path is not detected automatically) # client.library_path = "/opt/gurobi1203/linux64/lib/libgurobi.so.12.0.3" # Set the execution time to 100 seconds client.parameters.time_limit = timedelta(seconds=100) ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` To obtain the solver version: ```python >>> client.version '9.5.0' ``` --- # Quantum Computers Clients for quantum computers run optimization with quantum algorithms such as [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md). They execute quantum circuits using various quantum computers available as cloud services, as well as local simulators. > [!TIP] > > **Tip** > > Clients that use local simulators can be used without any registration. > > For other clients, you need a contract with the respective quantum computing service providers. > [!TIP] > > **Hint** > > To use quantum computers, install Amplify with extra packages using the following command: > > ```bash > $ python3 -m pip install -U 'amplify[quantum]' > ``` > > > [!WARNING] > > > > **Caution** > > > > Some extra packages may not be available depending on your Python version. See [Supported environments](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/quickstart.md#quantum-support-env) for details. The setup steps vary depending on the client. Clients that use cloud APIs require authentication with the license you hold. | Client class | Type | Required steps | | --- | --- | --- | | [QUDORAClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qudora.md) | ☁️ Cloud | Obtain an API token from your [Fixstars Amplify account](https://amplify.fixstars.com/user/token) or your own QUDORA Cloud account. | | [IonQClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ionq.md) | ☁️ Cloud | (When using an API token) Obtain an API token from your [Fixstars Amplify account](https://amplify.fixstars.com/user/token) or your own IonQ account. (When using [Amazon Braket](https://aws.amazon.com/braket/)) Configure your AWS account credentials. | | [AerClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aer.md) | πŸ’» Local | No steps | | [QulacsClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qulacs.md) | πŸ’» Local | No steps | | [BraketSimulatorClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aws.md) | πŸ’» Local ☁️ Cloud | No steps (When using the cloud simulator) Configure your AWS account credentials. | | [IBMClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ibm.md) | ☁️ Cloud | Obtain an IBM Quantum API key from your IBM Cloud account. | | [AQTClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aqt.md) [IQMClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/iqm.md) [RigettiClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/rigetti.md) | ☁️ Cloud | Configure your AWS account credentials. | | [OqtopusClient](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/oqtopus.md) | ☁️ Cloud | Configure the URL and API token for the OQTOPUS Cloud instance you have access to. | Quantum computer clients also require specifying an algorithm at initialization. The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. Quantum computer clients support setting parameters specific to each quantum computer/simulator, in addition to the [common client class interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface). Clients configured with the same algorithm expose the same parameters via `client.parameters`. For details on parameters and result information, see [Algorithm details](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/index.md). **Configuration example**: The following example creates a client that runs QAOA using the Qulacs Simulator. ```python from amplify import QAOA, QulacsClient # Create a solver client by combining the algorithm class QAOA with the backend class QulacsClient client = QulacsClient(QAOA) # Set QAOA parameters: reps and shots client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() '0.6.13' ``` Obtain the [execution time](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-result-duration): ```python >>> d = result.client_result.durations >>> result.total_time # Total time spent in amplify.solve datetime.timedelta(microseconds=26152) >>> d.total_time # Total elapsed time for QAOA datetime.timedelta(microseconds=25779) >>> d.total_response_time # Total communication time with the QPU datetime.timedelta(microseconds=283) >>> d.total_execution_time # Total execution time on the QPU datetime.timedelta(microseconds=283) >>> d.classical_processing_time # Time spent on classical optimization (= total_time - total_response_time) datetime.timedelta(microseconds=25496) ``` Obtaining the quantum circuit: ```python >>> print(result.client_result.history[0].sampling_meta.circuit) ``` The type of the circuit object depends on the backend. Interpreting [sampling results](https://amplify.fixstars.com/en/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"Solution: {values}, Count: {freq}") Solution: [0, 1], Count: 76 Solution: [0, 0], Count: 17 Solution: [1, 0], Count: 4 Solution: [1, 1], Count: 3 ``` --- # Serial Solver Execution You may want to run the solver several times iteratively when evaluating performance. Also, some solvers are more likely to find a good solution by running several iterations with a short timeout than by running a single iteration with a long timeout.Amplify SDK allows running the same combinatorial optimization problem multiple times in a row with the same solver for such needs. > [!NOTE] > > **See also** > > [Parallel Solver Execution](https://amplify.fixstars.com/en/docs/amplify/v1/parallel.md) may be more appropriate for obtaining statistics from multiple runs for formulation, solver performance studies, etc. ## Example of multiple runs First, create a model and solver client as in a usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function execution. ```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) ``` By passing an integer as the `num_solves` keyword argument to [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve), the solver is executed iteratively for `num_solves` times. ```python result = solve(model, client, num_solves=3) ``` As in a usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) call, the solver returns an instance of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class. The return value contains the results of the num_solves iterations. ```pycon >>> len(result) 3 ``` Using the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) attribute, you can obtain the best solution among those returned by the `num_solves` runs. ```pycon >>> print(f"objective = {result.best.objective}, q = {q.evaluate(result.best.values)}") objective = -1.0, q = [0. 0. 1.] ``` ## Fetching results When [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) is called with the `num_solves` keyword, the return value is an instance of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class, as usual. The Amplify SDK determines the number of times of the solver executions by the [`num_solves`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class. This attribute usually yields the same value as the value specified to [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) as the `num_solves` keyword argument. Still, it may be less than the value specified as the `num_solves` keyword argument, if some of the solver runs, fail for some reason. ```pycon >>> result.num_solves 3 ``` Index or iteration access allows you to aggregate all the solutions the solver returns for the `num_solves` runs. By default, the Amplify SDK sorts them in order of preferred solution, and there is no distinction regarding the number of executions the solution was found. ```pycon >>> print(f"objective = {result[0].objective}, q = {q.evaluate(result[0].values)}") objective = -1.0, q = [0. 0. 1.] ``` Use the [`split`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) property to get only the solutions returned by a particular run. ```pycon >>> first_result = result.split[0] # extract only the part of the `result` that was obtained at the first run >>> 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.] ``` The following are included for each property of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object returned by [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) when `num_solves` is specified, and the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) object represents the result of the `i`-th run obtained by using the [`split`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) property on it. | Property name | [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) returned by [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) | [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) after applying [`split`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.split) | | --- | --- | --- | | [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) | The best solution for the [`num_solves`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) runs | The best solution for the `i`-th run | | [`solutions`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.solutions) | All solutions obtained for the [`num_solves`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) runs | All solutions obtained for the `i`-th run | | [`intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate) | Same as usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) execution | Same as usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) execution | | [`embedding`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.embedding) | Same as usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) execution | Same as usual [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) execution | | [`client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Property obtained for the first run | Property obtained for the `i`-th run | | [`execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) | The sum of the [`num_solves`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) runs | Property obtained for the `i`-th run | | [`response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) | The sum of the [`num_solves`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.num_solves) runs | Property obtained for the `i`-th run | | [`total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.total_time) | Time from the start to the end of [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) | Time used for the `i`-th run | --- # Parallel Solver Execution [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) can send queries to multiple clients and models simultaneously. Such parallel execution may hide processing times for model transformations and request data creation and data transfer time due to network access to the solver when multiple runs are required. Also, for solvers that can run multiple problems simultaneously, parallel execution is expected to improve execution efficiency. ## Parallel execution example First, construct a model as if using the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. We will also show examples using multiple models later, so here we will build two models. ```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 ``` Next, we create multiple solver clients. ```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 ``` The [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) function is used to send requests to multiple clients. [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) has the same interface as [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve), but allows a list of arguments. ```python from amplify import parallel_solve amplify_result, dwave_result = parallel_solve(model1, [amplify_client, dwave_client]) ``` The code above has the same effect as running the following `for`-loop in parallel. ```python from amplify import solve for client in [amplify_client, dwave_client]: result = solve(model1, client) ``` [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) can also accept lists for both the model and client arguments. For example, you can use [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) to run multiple models and multiple clients concurrently as follows: ```python result1, result2 = parallel_solve([model1, model2], [amplify_client, dwave_client]) ``` Here, the code has the same effect as running the following `for`-loop in parallel. ```python for model, client in zip([model1, model2], [amplify_client, dwave_client], strict=True): result = solve(model, client) ``` > [!NOTE] > > **Note** > > When both the model and client arguments are given as lists, the number of elements in each list must be the same. If one of the arguments is a scalar value, it is treated as a list where the same value is repeated for each element of the other argument’s list. In the first example, multiple clients were used for a single model, but you can also use a single client for multiple models as follows: ```python # The following is equivalent to parallel_solve([model1, model2], [amplify_client] * 2). result1, result2 = parallel_solve([model1, model2], amplify_client) # The following is equivalent to parallel_solve([model1] * 2, [amplify_client, dwave_client]). result1, result2 = parallel_solve(model1, [amplify_client, dwave_client]) ``` ## Parallel execution parameters [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve) accepts keyword arguments similar to [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). Usually, keyword arguments are common for all parallel runs, but by providing a list, multiple keyword arguments can be specified simultaneously, as with multiple models and clients. In this case as well, the number of elements in the list-type keyword arguments must be the same as that of the model and client arguments. As an example, consider the following parameter specification using lists: ```python amplify_result, dwave_result = parallel_solve( model1, [amplify_client, dwave_client], dry_run=[False, True], num_solves=2, ) ``` The above has the same effect as running the following code in parallel. ```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) ``` Depending on the solver type and contract, sending multiple requests to the same client simultaneously may not be possible; the maximum number of parallel runs can be set by specifying the `concurrency` parameter of [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve). The default is 0, where the number of parallel runs is automatically determined by the number of CPUs on the machine running it. ```python amplify_result, dwave_result = parallel_solve( model1, [amplify_client, dwave_client], concurrency=2, ) ``` --- # Objective Function with a Coefficient Matrix One way to represent the objective function is by using a multidimensional polynomial coefficient array. This is a convenient formulation when a real-valued two-dimensional array $Q$ and a real-valued vector $p$ have already been calculated so that the objective function is represented as $x^\top Q x + p^\top x + c$. Also, when the number of terms in the objective function is approximately the square of the number of variables, this can be advantageous in terms of formulation speed compared to constructing the objective function using the [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). ## Coefficient matrix class A second-order variable polynomial can be represented by a matrix as follows. $$ x^\top Qx + p^\top x + c. $$ Here, $x$ is a vector of variables, $Q$ is a coefficient matrix, $p$ is a vector of coefficients, and $c$ is a constant. For example, the following binary variable quadratic polynomial $$ 2 q_0 q_1 + q_0 - q_1 + 1 $$ can be expressed in terms of the matrix and vector as follows: $$ 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} $$ The [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method of [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) specifies the length of the variable vector and creates a quadratic variable polynomial represented by an instance of the [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class. You can create an instance of the [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class with a binary variable vector of length 2 as follows. ```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 ``` For example, we give the coefficients corresponding to the polynomial $2 q_0 q_1 + q_0 - q_1 + 1$. We give a quadratic coefficient matrix in a NumPy array ([`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray)) with the attributes [`quadratic`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic). You can set the coefficient matrix values by element access as follows. ```python q = m.quadratic q[0, 1] = 1 q[1, 0] = 1 ``` Alternatively, you can assign a NumPy array if the arrays have the same form. ```python import numpy m.quadratic = numpy.array([[0, 1], [1, 0]]) ``` > [!NOTE] > > **Note** > > Q$does not have to be a symmetric matrix. In the example above, it is sufficient if$Q_{0, 1} + Q_{1, 0} = 2$. Similarly, you can obtain the first-order coefficient vectors with the [`linear`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear) attribute and constants with the [`constant`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) attribute. ```python p = m.linear p[0] = 1 p[1] = -1 m.constant = 1 ``` Let’s ensure that the coefficients are set correctly. ```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] > > **Note** > > The diagonal terms in $Q$ represent the coefficients of the squared terms, but be careful with binary and Ising variables since squaring a variable equals that variable or 1, respectively. > > * Binary variable polynomials > > * First-order coefficients are determined from the diagonal of $Q$ and $p$. > * Ising variable polynomials > > * The constant is determined from the diagonal term of $Q$ and $c$. To obtain the variable array that [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) has, refer to the [`variable_array`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.variable_array) attribute. Since constraints are given in polynomial classes ([`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)), you need to obtain the variable array to add constraints on a matrix-based objective function. ```pycon >>> x = m.variable_array >>> print(x) [q_0, q_1] ``` You can convert from the matrix form to a polynomial class ([`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) with the [`to_poly()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.to_poly) method. ```pycon >>> print(m.to_poly()) 2 q_0 q_1 + q_0 - q_1 + 1 ``` > [!TIP] > > **Tip** > > In the example above, the variable array was a one-dimensional vector, but a matrix form can be created for a multidimensional variable array as well. > > ```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 > ``` > > In general, with $n$ as the dimension of the variable array, $Q$ is a coefficient array of dimension $2n$ (a matrix for $n = 1$), $p$ is an array of coefficients of dimension $n$ (a vector for $n = 1$), and $c$ is a constant. > > The matrix form of a multidimensional array can be useful in fast formulations with multidimensional variables, such as the formulation of [Quadratic Assignment Problem](https://amplify.fixstars.com/en/docs/amplify/v1/qap.md). --- # Speedup Formulation Formulating a large combinatorial optimization problem using Python’s `for` statements can be very time-consuming. The Amplify SDK provides a fast way to formulate large optimization problems in practical time. For example, significant speedups can be achieved using Numpy-like methods in the [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) class. This page describes several methods for fast formulations, using the binary variable formulation of the traveling salesperson problem as an example. ## Formulating the traveling salesperson problem The traveling salesperson problem with $n$ cities can be formulated using $(n+1)n$ binary variables as follows: Let $d$ be a distance matrix, where $d_{i,j}$ denotes the distance between city $i$ and city $j$. > [!NOTE] > > **See also** > > We will not explain what the variables, objective function, and constraints refer to since the meaning of the formulation is unimportant here. See [Traveling Salesperson Problem](https://amplify.fixstars.com/en/docs/amplify/v1/tsp.md) for more details on formulating the traveling salesperson problem. $$ \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} $$ Before starting the formulation, let’s create the distance matrix `distance` (= $d$). This time `distance` will be generated as a random symmetric matrix. ```python import numpy as np NUM_CITIES = 100 # Generate a random symmetric matrix 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] > > **Note** > > For practical purposes, it is better to generate the coordinates of each city and find the distance matrix. For example, using [scipy](https://scipy.org/) the following method can be used for fast computation. > > ```python > from scipy.spatial import distance > > locations = np.random.random((NUM_CITIES, 2)) # randomly generate coordinates > distance = distance.cdist(locations, locations, metric='euclidean') > ``` ## Naive formulations The `for` statement and the list comprehension, you can formulate the problem as follows. ```python from amplify import Poly, VariableGenerator, one_hot # Create decision variables gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # Set q[NUM_CITIES, i] = q[0, i] for i in range(NUM_CITIES): q[NUM_CITIES, i] = q[0, i] # Construct the objective function 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] # Construct constraints 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) ) # Create a model model = objective + (row_one_hot_constraints + col_one_hot_constraints) ``` The resulting formulation time is as follows (depending on the execution environment). | Objective function | Constraints | Total | | --- | --- | --- | | 1.55 s | 13.3 ms | 1.56 s | ## Improvement #1: Not using the built-in sum function In the first line of the above code, add ```python from amplify import sum ``` and use the [`amplify.sum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) function instead of the built-in [`sum()`](https://docs.python.org/3/library/functions.html#sum) function. The [`amplify.sum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) function is a class sum-specific function provided by the Amplify SDK. Then the formulation time is improved as follows (depending on the execution environment). | Objective function | Constraints | Total | | --- | --- | --- | | 1.55 s | **3.95 ms** | 1.55 s | Simply importing the Amplify SDK’s [`amplify.sum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) function speeds up the constraint formulation by about a factor of 3. The difference from the overall time is small, but in the case of the traveling salesman problem, this is because the number of constraints ($2n$) is small compared to the number of terms in the objective function ($O\left(n^3\right)$). This optimization can be very effective if the [`sum()`](https://docs.python.org/3/library/functions.html#sum) function is used in areas where the formulation is time-consuming. > [!NOTE] > > **Note** > > The Amplify SDK’s [`amplify.sum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) function overrides the [`sum()`](https://docs.python.org/3/library/functions.html#sum) function. The Amplify SDK’s [`sum()`](https://docs.python.org/3/library/functions.html#sum) function automatically falls back to the built-in [`sum()`](https://docs.python.org/3/library/functions.html#sum) function for classes not provided by the Amplify SDK, allowing for replacement. ## Improvement #2: Not using `for` statements and list comprehension The objective function used to be formulated using the `for` statement, but Python’s `for` statement is slow. As much as possible, we will try to formulate them using the methods of [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray), a numpy-like polynomial array of the Amplify SDK, or numpy. First, let $A$ be the $n \times n$ matrix consisting of the upper $n rows of$q$and$B$be the$n\times n$matrix consisting of the lower$n$ rows. Then the objective function is written as follows. $$ \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} $$ Looking at $A$ and $d$, $$ (Ad)_{k, j} = \sum_{0 \leq k, j < n} A_{k, i} d_{i, j}. $$ Therefore, the objective function $\displaystyle \sum_{0 \leq i, j, k < n} d_{i, j} A_{k, i} B_{k, j}$ can be the sum of β€œthe matrix product of ($A$ and $d$) and the element product of $B$”. Thus, the objective function can be written with the Amplify SDK as follows. ```python q1 = q[:-1] q2 = q[1:] objective = ((q1 @ distance) * q2).sum() ``` Constraints can also be passed to the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function with the `axis` keyword argument and written as follows. ``` row_one_hot_constraints = one_hot(q1, axis=1) col_one_hot_constraints = one_hot(q1, axis=0) ``` Overall the code will looks like this. ```python from amplify import VariableGenerator, one_hot # Generate decision variables gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # Set q[NUM_CITIES, i] = q[0, i] q[-1, :] = q[0, :] # Create slices of q q1 = q[:-1] q2 = q[1:] # Constructe the objective function objective = ((q1 @ distance) * q2).sum() # Construct the constraints 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) ``` With this modification, the time taken is improved as follows (depending on the execution environment). | Objective function | Constraints | Total | | --- | --- | --- | | **152.1 ms** | **0.870 ms** | **154.4 ms** | ## Improvement #3: taking it straightforwardly In the β€œImprovement #2”, we tried to transform the objective function into a form that would work with numpy’s methods, but it takes a lot of work to think about the transformation. The Amplify SDK supports the [`einsum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) function, which can mechanically formulate such a function using Einstein’s contraction notation. First, as in β€œImprovement #2”, by denoting the $n \times n$ matrix consisting of the upper $n$ rows of $q$ as $A$ and the $n\times n$ matrix consisting of the lower n rows as $B$, the objective function is written as follows. $$ \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} $$ Note that the range over which the subscripts $i$, $j$, and $k$ of the matrices $d$, $A$, and $B$ appearing in this formula move coincides with the length of the corresponding row or column, respectively. In such a case, using the [`einsum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) function, the computation of the objective function can be written as follows. ``` # Construct the objective function objective = einsum("ij,ki,kj->", distance, q1, q2) ``` Here, the first argument of the [`einsum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) function represents the sequence of subscripts of the product in Einstein’s contraction notation, where `"ij,ki,kj->"`” is the product $d_{i, j} A_{k, i} B_{k, j}$. The second and subsequent arguments then give the arrays corresponding to the respective subscripts. The complete code is as follows. ```python from amplify import VariableGenerator, one_hot, einsum # Create decision variables gen = VariableGenerator() q = gen.array("Binary", NUM_CITIES + 1, NUM_CITIES) # Set q[NUM_CITIES, i] = q[0, i] q[-1, :] = q[0, :] # Create slices of q q1 = q[:-1] q2 = q[1:] # Construct the objective function objective = einsum("ij,ki,kj->", distance, q1, q2) # Constract the constraints row_one_hot_constraints = one_hot(q1, axis=1) col_one_hot_constraints = one_hot(q1, axis=0) # Create a model model = objective + (row_one_hot_constraints + col_one_hot_constraints) ``` With this formulation, we observed the following times (depending on the execution environment). | Objective function | Constraints | Total | | --- | --- | --- | | **58.11 ms** | 0.870 ms | **60.4 ms** | As a result of the above, the objective function and overall computation time became **25 times** faster, and the constraint construction became **15 times** faster. --- # File input/output of the model You can load an LP or QPLIB file and create [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) from it, and vice versa, you can save [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) and output to an LP or QPLIB file. This is useful for interfacing with other mathematical optimization solvers and for saving and reusing [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model). ## LP file format The format of LP files that the Amplify SDK can handle follows the [Gurobi LP Format](https://www.gurobi.com/documentation/current/refman/lp_format.html). The Amplify SDK supports the input and output of the following models. * Problems involving binary, integer, and real variables, as well as problems combining these variables * Problems consisting only of quadratic or less objective functions and constraints * Problems with objective functions and constraints expressible in LP format ### Restrictions Note the following restrictions about the input and output of LP files. * The following formats and sections are not supported for loading LP files. * Multi-Objective Case * Indicator Constraints * Lazy Constraints Section * User Cuts Section * SOS Section * PWLObj Section * General Constraints Section * Scenario Section * Semi-continuous variables are not supported for loading LP files. * Variables or constraints in the Amplify SDK are not output correctly if their names: * Contain a space, or control characters such as newlines or tabs (`\n, \r, \t, \v, \f`) * Contain the symbols `+, -, *, ^, :, /, [, ]`. * Begin with the symbols `<, >, =, ,, (, )` in addition to the above * Constraint weights in the Amplify SDK are not described in the LP file. ## QPLIB file format The format of QPLIB files that the Amplify SDK can handle follows the [QPLIB: a library of quadratic programming instances](https://doi.org/10.1007/s12532-018-0147-4) and its [Supplementary material 1](https://static-content.springer.com/esm/art%3A10.1007%2Fs12532-018-0147-4/MediaObjects/12532_2018_147_MOESM1_ESM.pdf). The Amplify SDK supports the input and output of the following models. * Problems involving binary, integer, and real variables, as well as problems combining these variables * Problems consisting only of quadratic or less objective functions and constraints * Problems with objective functions and constraints expressible in QPLIB format ### Restrictions Note the following restrictions about the input and output of QPLIB files. * Variables and constraints in the Amplify SDK are not output correctly as a valid QPLIB file if their names contain a space or control characters such as newlines or tabs (`\n, \r, \t, \v, \f`). * Constraint weights in the Amplify SDK are not output to the QPLIB file. * The descriptions of the default values of variables are ignored for loading QPLIB files. ## Output to LP/QPLIB file To output a model created with the Amplify SDK to a file, pass [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) as the first argument and the file path as the second argument to [`save_lp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.save_lp.md#amplify.save_lp) or [`save_qplib()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.save_qplib.md#amplify.save_qplib) for LP and QPLIB files, respectively. ```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") ``` Then, `model.lp` is saved in the current directory. 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 ``` To save to a QPLIB file: ```python from amplify import save_qplib save_qplib(model, "model.qplib") ``` Then, `model.qplib` is saved in the current directory. 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] > > **Note** > > LP and QPLIB files identify variables by their names. > Therefore, when formulating in the Amplify SDK, make sure that the names of variables in the model are not duplicated. ## Read from LP/QPLIB file When the path to an LP/QPLIB files is given as an argument to [`load_lp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) or [`load_qplib()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib), you will get a tuple of ([`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)) is returned. They respectively represent the model described in the input file and the variable generator used to make the model. For example, the `model.lp` created above is loaded and solved as follows. ```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) ``` The decision variables defined in the file can be found as follows. ```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})] ``` The loaded model can be solved by passing it to [`solve()`](https://amplify.fixstars.com/en/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) ``` The mapping between the names and the values of the variables of the best solution is obtained as a dictionary as follows. ```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} ``` ### Change the model after loading You can change the objective and constraints of the loaded model from a file. First, the variables contained in the model are converted into a list of [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), and then create polynomials from the variables contained in the model as follows. ```python from amplify import Poly # Load model from file model, gen = load_lp("model.lp") # Convert variables in the model to a list of Poly vars = [Poly(v) for v in model.variables] # Change the model's objective function and add constraints model += vars[1] * vars[2] model += one_hot(sum(vars[1:])) ``` You can also add new variables to the model using the variable generators obtained from [`load_lp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) or [`load_qplib()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib). New variable names created here should not duplicate the those of variables in the existing model. ```python # Create a new integer variable `n` with the variable generator. add_vars = gen.array("Integer", 2, bounds=(1, 4), name="n") # Change the model's objective function 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) ``` ### Set constraint weights Constraint weights are not described in the LP and QPLIB files. Therefore, you must set the weights for constraints after loading the model if you need. (See [Constructing Constraints/Setting constraint weights](https://amplify.fixstars.com/en/docs/amplify/v1/constraint.md#constraint-weight)) Here, we output the model we have just changed to a file and then re-load and use it as an example. ```python # Output model to file save_lp(model, "model.lp") # Re-Load model from file model, gen = load_lp("model.lp") # Get the ConstraintList in the model. 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)] ``` ### Specify the algorithm for generating the penalty function You can set [`PenaltyFormulation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation) as the second argument of [`load_lp()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_lp.md#amplify.load_lp) and [`load_qplib()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.load_qplib.md#amplify.load_qplib). This parameter represents the algorithm used to generate the penalty for inequality constraints. The default value is [`Default`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PenaltyFormulation.md#amplify.PenaltyFormulation.Default). (See [Constraints and Penalty Functions/Inequality constraints](https://amplify.fixstars.com/en/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 ``` --- # Subset Sum Problem This page discuss the subset sum problem as a simple example of formulation and solving with the Amplify SDK. A subset sum problem is the following problem. Let $N$ and $K$ be positive integers. There is a sequence $A_0, A_1, \ldots, A_{N - 1}$ consisting of $N$ positive integers. Find a subsequence of this sequence whose sum of elements is closest to $K$. Alternatively, the following problem is a subset sum problem. There are $N$ videos of varying lengths. Which of these videos should you select to make the total time closest to $K$ minutes? ## Creating the Problem Before solving a subset sum problem with the Amplify SDK, we first create a subset sum problem and express it in program code. In this example, we will work with a simple problem with $N=10$ elements. ```python import numpy as np N = 10 K = 27 A = np.array([2, 10, 3, 8, 5, 7, 9, 5, 3, 2]) ``` ## Formulation with the Amplify SDK To perform the formulation with Amplify SDK, we need to reformulate the subset sum problem as a polynomial minimization problem. First, β€œthe sum of the elements of the subsequence closest to $K$” can be reformulated as β€œthe difference between the sum of the elements of the subsequence and $K$ squared is the least”. Also, β€œthe sum of the elements of the subsequence” can be written as $q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1}$, where the variable $q_i$ takes $1$ if the $i$-th element of the sequence is chosen, $0$ otherwise. Thus, we can formulate the subset sum problem as follows. If the variables $q_0, q_1, \cdots, q_{N-1}$ take the values $0$ or $1$, minimize the function value below. $$ \quad (q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2 $$ The above $\quad (q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2$ is called the objective function. Let’s express the above in the Amplify SDK. First, create the decision variables (the variables we will optimize in combinatorial optimization). First, instantiate a class [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) to issue variables. $N$ variables are required, all of which take $0$ or $1$ values. Variables that take $0$ or $1$ values are called binary variables, and we can create them easily using the Amplify SDK. ```python from amplify import VariableGenerator gen = VariableGenerator() # The variable type as the 1st and the number of variables as the 2nd arguments. 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] $$ Now we create the objective function $(q_0 A_0 + q_1 A_1 + \cdots + q_{N-1} A_{N-1} - K)^2$. Using NumPy-like notation, we can implement as follows. ```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] > > **Note** > > Of course, in classic Python style, you can implement it as follows. > > ``` > objective = sum(x * a for x, a in zip(q, A)). > ``` > > However, depending on the problem and the data size, such writing can be time-consuming. We recommend a NumPy-like writing like `objective = (q * A) ** 2`. See [Speedup Formulation](https://amplify.fixstars.com/en/docs/amplify/v1/optimization.md) for details. Now, we use the objective function to construct a combinatorial optimization model. ```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 ``` We have completed the model construction. ## Solver setup You can configure various combinatorial optimization solvers with the Amplify SDK. On this page, we will use Fixstars Amplify AE, which is provided as a cloud service. First, create a solver client [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) for the Amplify SDK corresponding to Amplify AE to specify which solver to use. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` Then, we set up the token and solver’s parameters. ```python from datetime import timedelta client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` This completes the solver setup. ## Solver execution with the Amplify SDK Let the Amplify SDK obtain the solution of the combinatorial optimization model created above by executing the solver corresponding to the solver client. The following code executes the Amplify AE. ```python from amplify import solve result = solve(model, client) ``` The value of the variables $q = (q_0, q_1, \ldots, q_{N-1})$ can be obtained as follows. ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [0. 0. 0. 1. 0. 0. 1. 1. 1. 1.] ``` The binary variables $q_i$ take $1$ if the $i$-th element of the number sequence $A$ is chosen and $0$ otherwise. The optimal solution to the subset sum problem is as follows. ```python print(f"selected numbers: {[a for x, a in zip(q_values, A) if x == 1]}") ``` ```text selected numbers: [np.int64(8), np.int64(9), np.int64(5), np.int64(3), np.int64(2)] ``` You can see that the sum is close to $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 Problem The Max-Cut problem is one of the most well-known combinatorial optimization problems. In this tutorial, we will walk through the problem definition and solve it using the Amplify SDK. ## 1. Problem Definition and Ising Variables The Max-Cut problem aims to partition the vertex set $V$ of a graph $G=(V, E)$ into two subsets $V_1$ and $V_2$ such that the total weight of edges crossing the partition is maximized. ### Representing the Partition with Ising Variables To represent which subset each vertex $i \in V$ belongs to, we introduce an Ising variable $s_i \in \{-1, +1\}$. * If $s_i = +1$, vertex $i$ belongs to subset $V_1$ * If $s_i = -1$, vertex $i$ belongs to subset $V_2$ ### Expressing the Cut Condition An edge $(i, j) \in E$ is cut when vertices $i$ and $j$ belong to different subsets, that is, when $s_i$ and $s_j$ have different values ($s_i s_j = -1$). Consider the expression $\left(1 - s_i s_j\right)/2$: | $s_i$ | $s_j$ | $s_i s_j$ | $\left(1 - s_i s_j\right)/2$ | Cut status | | --- | --- | --- | --- | --- | | +1 | +1 | +1 | 0 | Not cut | | -1 | -1 | +1 | 0 | Not cut | | +1 | -1 | -1 | 1 | Cut | | -1 | +1 | -1 | 1 | Cut | This expression takes the value 1 when the edge is cut and 0 otherwise, making it directly usable in the objective function. ## 2. Formulation ### Objective Function (Maximization) Let $w_{ij}$ denote the weight of edge $(i, j)$. The Max-Cut problem can be formulated as the following maximization problem: $$ \text{maximize} \quad J(s) = \sum_{(i, j) \in E} w_{ij} \left( \frac{1 - s_i s_j}{2} \right) $$ ### Objective Function (Minimization / Ising Form) Since the Amplify SDK minimizes the energy, we drop the constant term and minimize the following Ising Hamiltonian: $$ \text{minimize} \quad H(s) = \sum_{(i, j) \in E} w_{ij} s_i s_j $$ ## Problem Setup Consider the following graph with 4 vertices $\{0, 1, 2, 3\}$ where all edge weights are 1.0. ![maxcut_problem](https://amplify.fixstars.com/en/docs/amplify/v1/_images/MaxCut-problem.drawio.svg) We define the weight matrix as the adjacency matrix of the graph. Vertices 0-1, 1-2, 2-3, and 3-0 are connected by edges, all with weight 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], ]) ``` ## Formulation with the Amplify SDK ### Creating Variables We create Ising variables $s_0, s_1, s_2, s_3$ corresponding to each vertex. Ising variables take values in $\{-1, +1\}$ and can be created in the Amplify SDK by specifying `"Ising"`. ```python from amplify import VariableGenerator gen = VariableGenerator() s = gen.array("Ising", 4) s ``` $$ \displaystyle [s_0, s_1, s_2, s_3] $$ ### Creating the Objective Function We construct the objective function $H(s) = \sum_{(i, j) \in E} w_{ij} s_i s_j$ using `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 ``` Using the objective function we created, we build a combinatorial optimization model. ```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 ``` ## Setting Up the Solver We create a solver client and configure the solver parameters. In this example, we use Amplify AE. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` We set the API token required to run the solver and configure the solver parameters. ```python from datetime import timedelta client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.parameters.time_limit_ms = timedelta(milliseconds=1000) ``` ## Solving with the Amplify SDK We execute the solver using the combinatorial optimization model and solver client created above. ```python from amplify import solve result = solve(model, client) ``` ## Checking the Results The values of the variables $s = (s_0, s_1, s_2, s_3)$ can be obtained as follows. ```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.] ``` The solution $[-1, 1, -1, 1]$ or $[1, -1, 1, -1]$ is obtained. These two solutions differ only by an overall sign flip and represent the same cut structure. Both correspond to the partition into $\{0, 2\}$ and $\{1, 3\}$, as shown in the figure below. ![maxcut_answer](https://amplify.fixstars.com/en/docs/amplify/v1/_images/MaxCut-answer.drawio.svg) Vertices 0 and 2 are placed in one group, and vertices 1 and 3 in the other, maximizing the total weight of cut edges. --- # Traveling Salesperson Problem As an example of using the Amplify SDK, we will explain how to solve the traveling salesperson problem (TSP) with the Amplify SDK. The TSP is a combinatorial optimization problem that, given a set of cities, finds the shortest path that starts in one city, visits all the cities once, and returns to the first city. ## Formulating the traveling salesperson problem Let the number of cities be denoted by `NUM_CITIES`. ### Variables First, we will use the `NUM_CITIES` binary (0-1) variables to represent which of the `NUM_CITIES` cities is to be visited. We represent a visit to city `i` by setting the `i`-th binary variable to 1 and all other variables to 0. For example, if the number of cities is 5 and the values of the 5 binary variables are `[0, 0, 0, 0, 1, 0]`, this is an expression for visiting city 3, since only the variable with index 3 is 1. This method of expressing which of the n options we choose by setting one of the n binary variables to 1 is called one-hot encoding, and is often used in machine learning and other applications. | City 0 | City 1 | City 2 | City 3 | City 4 | | --- | --- | --- | --- | --- | | 0 | 0 | 0 | 1 | 0 | Since in the TSP, the salesperson visits cities one at a time and returns to the first city at the end, the number of visits to cities is `NUM_CITIES + 1` times, including the first and last. So we have `(NUM_CITIES + 1) * NUM_CITIES` binary variables. For example, the following example represents a closed path that visits five cities in the order city 3 β†’ city 1 β†’ city 4 β†’ city 0 β†’ city 2 β†’ city 3. Binary variable table | City 0 | City 1 | City 2 | City 3 | City 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 | ### Constraint In the β€œbinary variables table” above, `(NUM_CITIES + 1) * NUM_CITIES` binary variables can take any value of 0 or 1, but such a path is not necessarily a close path representation. For example, having all binary variables as one yields no (closed) path. Therefore, it is necessary to impose constraints appropriately on the binary variables. Three types of constraints are required: 1. The first and last rows of the binary variable table must have the same value. 2. Each row of the binary variable table must have exactly one variable that is 1. 3. Each column of the binary variable table must have exactly one variable that is 1, except for the last row. Conversely, if there is a binary variable table that satisfies the above three constraints, it represents a closed path. Objective function The objective of the TSP is to find the shortest route that visits all cities once and returns to the start city. Therefore, the objective function is the path length of such a route. Suppose the distance between city i and city j is `d[i, j]`. The current goal is to find the path length of the closed route from the values in the binary variable table. If the binary variable table values are known, you can find the path length of the route in the following pseudo-code. Suppose the binary variables in the β€˜k’ rows and β€˜i’ columns can be written as β€˜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) ``` However, when formulating in the Amplify SDK, we only know that each `q[k, i]` is a binary variable, and we do not yet know what value it will take, so we cannot make the conditional decision `if q[k, i] == 1 and q[k+1, j] == 1`. Only the addition and multiplication of binary variables and numbers can represent the objective function. Now, let’s recall that the product of two binary variables `q[k, i] * q[k+1, j]` is 1 if `q[k, i] == 1 and q[k+1, j] == 1` is true and 0 if false. Then the objective function can be implemented as follows. ``` 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] ``` ### Formulation Writing down the above discussion in mathematical form, the formulation of the TSP in terms of binary variables `(NUM_CITIES + 1) * NUM_CITIES` can be written as: $$ \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} $$ However, for notational convenience, the number of cities `NUM_CITIES` is denoted as $N$. ## Creating problem First, let’s create a problem. Let the number of cities be `NUM_CITIES`, and we will randomly select each city’s x and y coordinates from the integers 0~100. In the following, we name city 0, city 1, …, and city `NUM_CITIES - 1`. This sample code sets the number of cities to 5 for simplicity. ```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) ``` Next, we will create a distance matrix representing the distances between cities. Here, the distances are Euclidean distances. The output is a NumPy array of `n * n`, where the elements in the `i` row `j` columns represent the distance between city `i` and city `j`, i.e. `(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. 12.042 36.056 74.431 51.614] [12.042 0. 47.424 83. 51.74 ] [36.056 47.424 0. 44.721 54.148] [74.431 83. 44.721 0. 55.606] [51.614 51.74 54.148 55.606 0. ]] ``` ## Formulation with the Amplify SDK We will now formulate the problem with the Amplify SDK. ### Variable generation First, we create the decision variables. The Amplify SDK allows you to generate variables in the form of the two-dimensional array by using [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator). ```python from amplify import VariableGenerator gen = VariableGenerator() q = gen.array("Binary", (NUM_CITIES + 1, NUM_CITIES)) ``` The binary variables `q` look like the following. ```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} $$ ### Creating constraints Next, we create constraints. As described [above](#tsp-formulation-constraint), there are three types of constraints. 1. The first and last rows of the binary variable table must have the same value. 2. Each row of the binary variable table must have exactly one variable that is 1. 3. Each column of the binary variable table must have exactly one variable that is 1, except for the last row. #### First constraint Create the first constraint β€œthe first and last rows of the binary variable table must have the same value.” is constructed here. We want to fix the last row to the same value as the first row, so we assign the first row to the last row of `q`. The first row of `q` can be written as `q[0]` and the last row of `q` as `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} $$ We can now express the first constraint. > [!WARNING] > > **Attention** > > If you fix variables by assignment, do so before constructing the objective function or other constraints. In subsequent constraint construction, we will not need to consider the last row of the binary variable array `q`, so we will create an array with the `NUM_CITIES` rows cut out from the top of `q`. ```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} $$ #### Second constraint We now create the second constraint, β€œeach row of the binary variable table must have exactly one variable that is 1.” If you want to impose the constraint that exactly one of several binary variables is 1, use the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function. If you want to impose the one-hot constraint on each row of a variable array, set 1 to the `axis` keyword argument of the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function. ```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) constraints were generated at once. #### Third constraint We then create the third constraint β€œeach column of the binary variable table must have exactly one variable that is 1, except for the last row.” As with the second constraint, we use the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function. If you want to impose a one-hot constraint on each column of the variable array, give 0 to the `axis` keyword argument of the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function. ```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} $$ ### Creating the objective function Next, we create the objective function. As mentioned [above](#tsp-formulation-objective), the objective function is the path length of the route and can be written as follows. ```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 12.0415945787923 q_{0,0} q_{1,1} + 36.0555127546399 q_{0,0} q_{1,2} + 74.4311762637136 q_{0,0} q_{1,3} + 51.6139516022558 q_{0,0} q_{1,4} + 12.0415945787923 q_{0,0} q_{4,1} + 36.0555127546399 q_{0,0} q_{4,2} + 74.4311762637136 q_{0,0} q_{4,3} + 51.6139516022558 q_{0,0} q_{4,4} + 12.0415945787923 q_{0,1} q_{1,0} + 47.4236228055175 q_{0,1} q_{1,2} + 83 q_{0,1} q_{1,3} + 51.7397332811061 q_{0,1} q_{1,4} + 12.0415945787923 q_{0,1} q_{4,0} + 47.4236228055175 q_{0,1} q_{4,2} + 83 q_{0,1} q_{4,3} + 51.7397332811061 q_{0,1} q_{4,4} + 36.0555127546399 q_{0,2} q_{1,0} + 47.4236228055175 q_{0,2} q_{1,1} + 44.7213595499958 q_{0,2} q_{1,3} + 54.1479454827235 q_{0,2} q_{1,4} + 36.0555127546399 q_{0,2} q_{4,0} + 47.4236228055175 q_{0,2} q_{4,1} + 44.7213595499958 q_{0,2} q_{4,3} + 54.1479454827235 q_{0,2} q_{4,4} + 74.4311762637136 q_{0,3} q_{1,0} + 83 q_{0,3} q_{1,1} + 44.7213595499958 q_{0,3} q_{1,2} + 55.6057550978314 q_{0,3} q_{1,4} + 74.4311762637136 q_{0,3} q_{4,0} + 83 q_{0,3} q_{4,1} + 44.7213595499958 q_{0,3} q_{4,2} + 55.6057550978314 q_{0,3} q_{4,4} + 51.6139516022558 q_{0,4} q_{1,0} + 51.7397332811061 q_{0,4} q_{1,1} + 54.1479454827235 q_{0,4} q_{1,2} + 55.6057550978314 q_{0,4} q_{1,3} + 51.6139516022558 q_{0,4} q_{4,0} + 51.7397332811061 q_{0,4} q_{4,1} + 54.1479454827235 q_{0,4} q_{4,2} + 55.6057550978314 q_{0,4} q_{4,3} + 12.0415945787923 q_{1,0} q_{2,1} + 36.0555127546399 q_{1,0} q_{2,2} + 74.4311762637136 q_{1,0} q_{2,3} + 51.6139516022558 q_{1,0} q_{2,4} + 12.0415945787923 q_{1,1} q_{2,0} + 47.4236228055175 q_{1,1} q_{2,2} + 83 q_{1,1} q_{2,3} + 51.7397332811061 q_{1,1} q_{2,4} + 36.0555127546399 q_{1,2} q_{2,0} + 47.4236228055175 q_{1,2} q_{2,1} + 44.7213595499958 q_{1,2} q_{2,3} + 54.1479454827235 q_{1,2} q_{2,4} + 74.4311762637136 q_{1,3} q_{2,0} + 83 q_{1,3} q_{2,1} + 44.7213595499958 q_{1,3} q_{2,2} + 55.6057550978314 q_{1,3} q_{2,4} + 51.6139516022558 q_{1,4} q_{2,0} + 51.7397332811061 q_{1,4} q_{2,1} + 54.1479454827235 q_{1,4} q_{2,2} + 55.6057550978314 q_{1,4} q_{2,3} + 12.0415945787923 q_{2,0} q_{3,1} + 36.0555127546399 q_{2,0} q_{3,2} + 74.4311762637136 q_{2,0} q_{3,3} + 51.6139516022558 q_{2,0} q_{3,4} + 12.0415945787923 q_{2,1} q_{3,0} + 47.4236228055175 q_{2,1} q_{3,2} + 83 q_{2,1} q_{3,3} + 51.7397332811061 q_{2,1} q_{3,4} + 36.0555127546399 q_{2,2} q_{3,0} + 47.4236228055175 q_{2,2} q_{3,1} + 44.7213595499958 q_{2,2} q_{3,3} + 54.1479454827235 q_{2,2} q_{3,4} + 74.4311762637136 q_{2,3} q_{3,0} + 83 q_{2,3} q_{3,1} + 44.7213595499958 q_{2,3} q_{3,2} + 55.6057550978314 q_{2,3} q_{3,4} + 51.6139516022558 q_{2,4} q_{3,0} + 51.7397332811061 q_{2,4} q_{3,1} + 54.1479454827235 q_{2,4} q_{3,2} + 55.6057550978314 q_{2,4} q_{3,3} + 12.0415945787923 q_{3,0} q_{4,1} + 36.0555127546399 q_{3,0} q_{4,2} + 74.4311762637136 q_{3,0} q_{4,3} + 51.6139516022558 q_{3,0} q_{4,4} + 12.0415945787923 q_{3,1} q_{4,0} + 47.4236228055175 q_{3,1} q_{4,2} + 83 q_{3,1} q_{4,3} + 51.7397332811061 q_{3,1} q_{4,4} + 36.0555127546399 q_{3,2} q_{4,0} + 47.4236228055175 q_{3,2} q_{4,1} + 44.7213595499958 q_{3,2} q_{4,3} + 54.1479454827235 q_{3,2} q_{4,4} + 74.4311762637136 q_{3,3} q_{4,0} + 83 q_{3,3} q_{4,1} + 44.7213595499958 q_{3,3} q_{4,2} + 55.6057550978314 q_{3,3} q_{4,4} + 51.6139516022558 q_{3,4} q_{4,0} + 51.7397332811061 q_{3,4} q_{4,1} + 54.1479454827235 q_{3,4} q_{4,2} + 55.6057550978314 q_{3,4} q_{4,3} ``` Alternatively, the following code creates the same objective function. This code is faster because it takes full advantage of the Amplify SDK’s features and is recommended for those familiar with the NumPy library. See [Speedup Formulation](https://amplify.fixstars.com/en/docs/amplify/v1/optimization.md) for details. ```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 12.0415945787923 q_{0,0} q_{1,1} + 36.0555127546399 q_{0,0} q_{1,2} + 74.4311762637136 q_{0,0} q_{1,3} + 51.6139516022558 q_{0,0} q_{1,4} + 12.0415945787923 q_{0,0} q_{4,1} + 36.0555127546399 q_{0,0} q_{4,2} + 74.4311762637136 q_{0,0} q_{4,3} + 51.6139516022558 q_{0,0} q_{4,4} + 12.0415945787923 q_{0,1} q_{1,0} + 47.4236228055175 q_{0,1} q_{1,2} + 83 q_{0,1} q_{1,3} + 51.7397332811061 q_{0,1} q_{1,4} + 12.0415945787923 q_{0,1} q_{4,0} + 47.4236228055175 q_{0,1} q_{4,2} + 83 q_{0,1} q_{4,3} + 51.7397332811061 q_{0,1} q_{4,4} + 36.0555127546399 q_{0,2} q_{1,0} + 47.4236228055175 q_{0,2} q_{1,1} + 44.7213595499958 q_{0,2} q_{1,3} + 54.1479454827235 q_{0,2} q_{1,4} + 36.0555127546399 q_{0,2} q_{4,0} + 47.4236228055175 q_{0,2} q_{4,1} + 44.7213595499958 q_{0,2} q_{4,3} + 54.1479454827235 q_{0,2} q_{4,4} + 74.4311762637136 q_{0,3} q_{1,0} + 83 q_{0,3} q_{1,1} + 44.7213595499958 q_{0,3} q_{1,2} + 55.6057550978314 q_{0,3} q_{1,4} + 74.4311762637136 q_{0,3} q_{4,0} + 83 q_{0,3} q_{4,1} + 44.7213595499958 q_{0,3} q_{4,2} + 55.6057550978314 q_{0,3} q_{4,4} + 51.6139516022558 q_{0,4} q_{1,0} + 51.7397332811061 q_{0,4} q_{1,1} + 54.1479454827235 q_{0,4} q_{1,2} + 55.6057550978314 q_{0,4} q_{1,3} + 51.6139516022558 q_{0,4} q_{4,0} + 51.7397332811061 q_{0,4} q_{4,1} + 54.1479454827235 q_{0,4} q_{4,2} + 55.6057550978314 q_{0,4} q_{4,3} + 12.0415945787923 q_{1,0} q_{2,1} + 36.0555127546399 q_{1,0} q_{2,2} + 74.4311762637136 q_{1,0} q_{2,3} + 51.6139516022558 q_{1,0} q_{2,4} + 12.0415945787923 q_{1,1} q_{2,0} + 47.4236228055175 q_{1,1} q_{2,2} + 83 q_{1,1} q_{2,3} + 51.7397332811061 q_{1,1} q_{2,4} + 36.0555127546399 q_{1,2} q_{2,0} + 47.4236228055175 q_{1,2} q_{2,1} + 44.7213595499958 q_{1,2} q_{2,3} + 54.1479454827235 q_{1,2} q_{2,4} + 74.4311762637136 q_{1,3} q_{2,0} + 83 q_{1,3} q_{2,1} + 44.7213595499958 q_{1,3} q_{2,2} + 55.6057550978314 q_{1,3} q_{2,4} + 51.6139516022558 q_{1,4} q_{2,0} + 51.7397332811061 q_{1,4} q_{2,1} + 54.1479454827235 q_{1,4} q_{2,2} + 55.6057550978314 q_{1,4} q_{2,3} + 12.0415945787923 q_{2,0} q_{3,1} + 36.0555127546399 q_{2,0} q_{3,2} + 74.4311762637136 q_{2,0} q_{3,3} + 51.6139516022558 q_{2,0} q_{3,4} + 12.0415945787923 q_{2,1} q_{3,0} + 47.4236228055175 q_{2,1} q_{3,2} + 83 q_{2,1} q_{3,3} + 51.7397332811061 q_{2,1} q_{3,4} + 36.0555127546399 q_{2,2} q_{3,0} + 47.4236228055175 q_{2,2} q_{3,1} + 44.7213595499958 q_{2,2} q_{3,3} + 54.1479454827235 q_{2,2} q_{3,4} + 74.4311762637136 q_{2,3} q_{3,0} + 83 q_{2,3} q_{3,1} + 44.7213595499958 q_{2,3} q_{3,2} + 55.6057550978314 q_{2,3} q_{3,4} + 51.6139516022558 q_{2,4} q_{3,0} + 51.7397332811061 q_{2,4} q_{3,1} + 54.1479454827235 q_{2,4} q_{3,2} + 55.6057550978314 q_{2,4} q_{3,3} + 12.0415945787923 q_{3,0} q_{4,1} + 36.0555127546399 q_{3,0} q_{4,2} + 74.4311762637136 q_{3,0} q_{4,3} + 51.6139516022558 q_{3,0} q_{4,4} + 12.0415945787923 q_{3,1} q_{4,0} + 47.4236228055175 q_{3,1} q_{4,2} + 83 q_{3,1} q_{4,3} + 51.7397332811061 q_{3,1} q_{4,4} + 36.0555127546399 q_{3,2} q_{4,0} + 47.4236228055175 q_{3,2} q_{4,1} + 44.7213595499958 q_{3,2} q_{4,3} + 54.1479454827235 q_{3,2} q_{4,4} + 74.4311762637136 q_{3,3} q_{4,0} + 83 q_{3,3} q_{4,1} + 44.7213595499958 q_{3,3} q_{4,2} + 55.6057550978314 q_{3,3} q_{4,4} + 51.6139516022558 q_{3,4} q_{4,0} + 51.7397332811061 q_{3,4} q_{4,1} + 54.1479454827235 q_{3,4} q_{4,2} + 55.6057550978314 q_{3,4} q_{4,3} ``` ### Creating a combinatorial optimization model We now create a combinatorial optimization model by combining the objective function and constraints constructed in β€œ[creating constraints](#tsp-constraint)” and β€œ[creating the objective function](#tsp-objective)”. ```python model = route_length + (constraints2 + constraints3) * np.max(distance) print(model) ``` ```text minimize: 12.0415945787923 q_{0,0} q_{1,1} + 36.0555127546399 q_{0,0} q_{1,2} + 74.4311762637136 q_{0,0} q_{1,3} + 51.6139516022558 q_{0,0} q_{1,4} + 12.0415945787923 q_{0,0} q_{4,1} + 36.0555127546399 q_{0,0} q_{4,2} + 74.4311762637136 q_{0,0} q_{4,3} + 51.6139516022558 q_{0,0} q_{4,4} + 12.0415945787923 q_{0,1} q_{1,0} + 47.4236228055175 q_{0,1} q_{1,2} + 83 q_{0,1} q_{1,3} + 51.7397332811061 q_{0,1} q_{1,4} + 12.0415945787923 q_{0,1} q_{4,0} + 47.4236228055175 q_{0,1} q_{4,2} + 83 q_{0,1} q_{4,3} + 51.7397332811061 q_{0,1} q_{4,4} + 36.0555127546399 q_{0,2} q_{1,0} + 47.4236228055175 q_{0,2} q_{1,1} + 44.7213595499958 q_{0,2} q_{1,3} + 54.1479454827235 q_{0,2} q_{1,4} + 36.0555127546399 q_{0,2} q_{4,0} + 47.4236228055175 q_{0,2} q_{4,1} + 44.7213595499958 q_{0,2} q_{4,3} + 54.1479454827235 q_{0,2} q_{4,4} + 74.4311762637136 q_{0,3} q_{1,0} + 83 q_{0,3} q_{1,1} + 44.7213595499958 q_{0,3} q_{1,2} + 55.6057550978314 q_{0,3} q_{1,4} + 74.4311762637136 q_{0,3} q_{4,0} + 83 q_{0,3} q_{4,1} + 44.7213595499958 q_{0,3} q_{4,2} + 55.6057550978314 q_{0,3} q_{4,4} + 51.6139516022558 q_{0,4} q_{1,0} + 51.7397332811061 q_{0,4} q_{1,1} + 54.1479454827235 q_{0,4} q_{1,2} + 55.6057550978314 q_{0,4} q_{1,3} + 51.6139516022558 q_{0,4} q_{4,0} + 51.7397332811061 q_{0,4} q_{4,1} + 54.1479454827235 q_{0,4} q_{4,2} + 55.6057550978314 q_{0,4} q_{4,3} + 12.0415945787923 q_{1,0} q_{2,1} + 36.0555127546399 q_{1,0} q_{2,2} + 74.4311762637136 q_{1,0} q_{2,3} + 51.6139516022558 q_{1,0} q_{2,4} + 12.0415945787923 q_{1,1} q_{2,0} + 47.4236228055175 q_{1,1} q_{2,2} + 83 q_{1,1} q_{2,3} + 51.7397332811061 q_{1,1} q_{2,4} + 36.0555127546399 q_{1,2} q_{2,0} + 47.4236228055175 q_{1,2} q_{2,1} + 44.7213595499958 q_{1,2} q_{2,3} + 54.1479454827235 q_{1,2} q_{2,4} + 74.4311762637136 q_{1,3} q_{2,0} + 83 q_{1,3} q_{2,1} + 44.7213595499958 q_{1,3} q_{2,2} + 55.6057550978314 q_{1,3} q_{2,4} + 51.6139516022558 q_{1,4} q_{2,0} + 51.7397332811061 q_{1,4} q_{2,1} + 54.1479454827235 q_{1,4} q_{2,2} + 55.6057550978314 q_{1,4} q_{2,3} + 12.0415945787923 q_{2,0} q_{3,1} + 36.0555127546399 q_{2,0} q_{3,2} + 74.4311762637136 q_{2,0} q_{3,3} + 51.6139516022558 q_{2,0} q_{3,4} + 12.0415945787923 q_{2,1} q_{3,0} + 47.4236228055175 q_{2,1} q_{3,2} + 83 q_{2,1} q_{3,3} + 51.7397332811061 q_{2,1} q_{3,4} + 36.0555127546399 q_{2,2} q_{3,0} + 47.4236228055175 q_{2,2} q_{3,1} + 44.7213595499958 q_{2,2} q_{3,3} + 54.1479454827235 q_{2,2} q_{3,4} + 74.4311762637136 q_{2,3} q_{3,0} + 83 q_{2,3} q_{3,1} + 44.7213595499958 q_{2,3} q_{3,2} + 55.6057550978314 q_{2,3} q_{3,4} + 51.6139516022558 q_{2,4} q_{3,0} + 51.7397332811061 q_{2,4} q_{3,1} + 54.1479454827235 q_{2,4} q_{3,2} + 55.6057550978314 q_{2,4} q_{3,3} + 12.0415945787923 q_{3,0} q_{4,1} + 36.0555127546399 q_{3,0} q_{4,2} + 74.4311762637136 q_{3,0} q_{4,3} + 51.6139516022558 q_{3,0} q_{4,4} + 12.0415945787923 q_{3,1} q_{4,0} + 47.4236228055175 q_{3,1} q_{4,2} + 83 q_{3,1} q_{4,3} + 51.7397332811061 q_{3,1} q_{4,4} + 36.0555127546399 q_{3,2} q_{4,0} + 47.4236228055175 q_{3,2} q_{4,1} + 44.7213595499958 q_{3,2} q_{4,3} + 54.1479454827235 q_{3,2} q_{4,4} + 74.4311762637136 q_{3,3} q_{4,0} + 83 q_{3,3} q_{4,1} + 44.7213595499958 q_{3,3} q_{4,2} + 55.6057550978314 q_{3,3} q_{4,4} + 51.6139516022558 q_{3,4} q_{4,0} + 51.7397332811061 q_{3,4} q_{4,1} + 54.1479454827235 q_{3,4} q_{4,2} + 55.6057550978314 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: 83), q_{1,0} + q_{1,1} + q_{1,2} + q_{1,3} + q_{1,4} == 1 (weight: 83), q_{2,0} + q_{2,1} + q_{2,2} + q_{2,3} + q_{2,4} == 1 (weight: 83), q_{3,0} + q_{3,1} + q_{3,2} + q_{3,3} + q_{3,4} == 1 (weight: 83), q_{4,0} + q_{4,1} + q_{4,2} + q_{4,3} + q_{4,4} == 1 (weight: 83), q_{0,0} + q_{1,0} + q_{2,0} + q_{3,0} + q_{4,0} == 1 (weight: 83), q_{0,1} + q_{1,1} + q_{2,1} + q_{3,1} + q_{4,1} == 1 (weight: 83), q_{0,2} + q_{1,2} + q_{2,2} + q_{3,2} + q_{4,2} == 1 (weight: 83), q_{0,3} + q_{1,3} + q_{2,3} + q_{3,3} + q_{4,3} == 1 (weight: 83), q_{0,4} + q_{1,4} + q_{2,4} + q_{3,4} + q_{4,4} == 1 (weight: 83) ``` We multiply the constraints by the maximum value of the distance matrix to give weight to the constraints. In Amplify AE, the solver used in this example, unless appropriate weights are specified for the constraints, the solver will move toward reducing the objective function rather than trying to satisfy the constraints and will not be able to find a feasible solution. See [Constraints and Penalty Functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md) for details. ## Creating a solver client Here, we will create a solver client, specify a solver for solving, and set solver parameters. The Amplify SDK supports various solvers. Here, we will use Amplify AE. The solver client class for Amplify AE is the [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) class. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` We will set an API token required for running Amplify AE. > [!TIP] > > **Tip** > > [Register as a user](https://amplify.fixstars.com/en/register) to obtain a free API token that you can use for evaluation and validation purposes. ```python client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` We also need to set the timeout value of the solver; the unit of the timeout value of Amplify AE is ms, but since the unit of the timeout value varies from solver to solver, the timeout value can be specified uniformly by using [`datetime`](https://docs.python.org/3/library/datetime.html#module-datetime) module. ```python import datetime client.parameters.time_limit_ms = datetime.timedelta(seconds=1) ``` This completes the solver setup. ## Executing the solver Let’s execute the solver using the created combinatorial optimization model and the solver client to solve the traveling salesperson problem. ```python from amplify import solve result = solve(model, client) ``` The value of the objective function, i.e., the length of the closed route, can be obtained as follows. ```python result.best.objective ``` ```text 200.16395526236548 ``` The values of the variables in the optimal solution can be obtained in the form of a multidimensional NumPy array as follows. ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [[0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.] [0. 1. 0. 0. 0.] [1. 0. 0. 0. 0.] [0. 0. 1. 0. 0.]] ``` ## Checking the result This is enough for a tutorial on the Amplify SDK, but we want to visualize the result. ```python import matplotlib.pyplot as plt %matplotlib inline ``` First, we visualize the locations of the cities. ```python plt.scatter(x, y) plt.show() ``` ![_images/81d38c85bf3ac456e51a57c80030c0f830e21fe4a17abea062a6e2774c2b15d8.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/81d38c85bf3ac456e51a57c80030c0f830e21fe4a17abea062a6e2774c2b15d8.png) Lastly, we visualize the route. Since `q_values` can be considered a substitution matrix (with one row added to the end), we can sort the cities in the order they are visited on the route by multiplying the ordered vector of cities by `q_values` from the left. ```python route_x = q_values @ x # x-coordinate of the itinerary route_y = q_values @ y # y-coordinate of the itinerary plt.scatter(x, y) plt.plot(route_x, route_y) plt.show() ``` ![_images/2024fce1df1477d403f6acbb4f03d6b5e293cae726da3335df894f7eb83a2f17.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/2024fce1df1477d403f6acbb4f03d6b5e293cae726da3335df894f7eb83a2f17.png) --- # Quadratic Assignment Problem Quadratic assignment problem (QAP) is the following problem. **Quadratic assignment problem** Let $N$ be a positive integer. Consider $N$ factories to be built on $N$ candidate sites. Each factory can be built on any of the candidate sites. Every two factories have trucks traveling to and from them, and their transportation volumes are known in advance. How can we minimize the sum of the amount transported x the distance traveled? An application could be to determine the seating chart for a meeting so that people close to each other have seats closely. ## Formulation Let $N$ potential factory locations be denoted by land $0$, land $1$, … , and $N$ factories are denoted as factories $0$, factories $1$, …, factories $N-1$. Also let $D_{i, j}$ denote the distance between land $i$ and land $j$, and $F_{k, l}$ denote the transport volume between factory $k$ and factory $l$. ### Variables With $N \times N$ binary variables $q$, let $q_{i, k}$ represent whether factory $k$ is to be built on land $i$. For example, factory $3$ will be built on land $0$ if $q$ has the following value. Binary variable table | | factory 0 | factory 1 | factory 2 | factory 3 | factory 4 | | --- | --- | --- | --- | --- | --- | | land 0 | 0 | 0 | 0 | 1 | 0 | | land 1 | 0 | 1 | 0 | 0 | 0 | | land 2 | 0 | 0 | 0 | 0 | 1 | | land 3 | 1 | 0 | 0 | 0 | 0 | | land 4 | 0 | 0 | 1 | 0 | 0 | ### Constraints Each row and column of the binary variable table must have exactly one variable that is 1, so we place a one-hot constraint on each row and column. Conversely, if these are satisfied, then there is only one way to determine which factory to build on which land. ### Objective function The objective function is the sum of transport volume x distance between factories. This can be expressed in the equation using $q$ as follows. $$ \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} $$ ### Formulation The above formulation, with $N\times N$ binary variables $q$, can be written as follows. $$ \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} $$ ## Problem setting Before formulating with the Amplify SDK, we will create a problem. For simplicity, let the number of factories $N=10$. ```python import numpy as np ``` ```python N = 10 ``` Next, we create a distance matrix $D$ representing the distances between lands. The lands are randomly generated on the Euclidean plane. The distance matrix `distance` is created as a two-dimensional [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray). ```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. 50.16 98.995 41.231 41.34 62.968 83.451 8.246 24.739 52.393] [ 50.16 0. 55.462 41.183 28.302 54.672 40.497 52.154 52.154 32.388] [ 98.995 55.462 0. 67.082 59.405 59.54 15.62 103.479 88.837 84.172] [ 41.231 41.183 67.082 0. 13. 22.023 53.141 48.662 22.627 66.219] [ 41.34 28.302 59.405 13. 0. 29.155 44.418 47.424 30.083 55.227] [ 62.968 54.672 59.54 22.023 29.155 0. 49.163 70.576 41.629 84.119] [ 83.451 40.497 15.62 53.141 44.418 49.163 0. 87.864 74.243 70.576] [ 8.246 52.154 103.479 48.662 47.424 70.576 87.864 0. 32.985 49.163] [ 24.739 52.154 88.837 22.627 30.083 41.629 74.243 32.985 0. 67.417] [ 52.393 32.388 84.172 66.219 55.227 84.119 70.576 49.163 67.417 0. ]] ``` Also, we create a matrix $F$ representing the amount of transport between factories, a random symmetric matrix of dimension 2, named `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 70 81 42 41 42 86 22 79 34] [70 0 8 95 40 39 22 99 37 80] [81 8 0 11 54 32 13 1 3 31] [42 95 11 0 83 12 95 12 33 80] [41 40 54 83 0 3 28 18 36 94] [42 39 32 12 3 0 69 31 80 8] [86 22 13 95 28 69 0 8 98 74] [22 99 1 12 18 31 8 0 22 83] [79 37 3 33 36 80 98 22 0 81] [34 80 31 80 94 8 74 83 81 0]] ``` ## Formulation with the Amplify SDK In the formulation, we can use the [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class for efficient formulation, since a quadratic term consisting of any two binary variables can appear in the objective function. ### Creating variables To formulate using the [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class, [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator)’s [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method to issue variables. ```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} $$ ### Creating the objective function The `matrix` created above is an instance of the class [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix), which has the following three properties. * [`quadratic`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) * [`linear`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear) * [`constant`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) [`quadratic`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) is [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray) representing the coefficients of the second order terms, and its [`shape`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape) is `(N, N, N, N)` this time. `quadratic[i, k, j, l]` corresponds to the coefficients of `q[i, k] * q[j, l]`. That is, [`quadratic`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.quadratic) must be set to a 4-dimensional NumPy array such that `quadratic[i, k, j, l] = distance[i, j] * flow[k, l]` [`linear`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.linear) and [`constant`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix.constant) represent the coefficient and constant terms of the linear term, respectively, but since the objective function used in this problem contains only second order terms, we will not set them. ```python np.einsum("ij,kl->ikjl", distance, flow, out=matrix.quadratic) ``` ### Creating constraints Impose a one-hot constraint on each row and column of the variable array `q` created in [Creating variables](#creating-variables). ```python from amplify import one_hot constraints = one_hot(q, axis=1) + one_hot(q, axis=0) ``` ### Creating a combinatorial optimization model Let’s combine the objective function and constraints to create a model. ```python penalty_weight = np.max(distance) * np.max(flow) * (N - 1) model = matrix + penalty_weight * constraints ``` The `penalty_weight` is applied to the constraints to give weight to the constraints. In Amplify AE, the solver used in this example, if you do not specify appropriate weights for the constraints, the solver will search in the direction of making the objective function smaller rather than trying to satisfy the constraints, and you will not be able to find a feasible solution. See [Constraints and Penalty Functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md) for details. ## Creating a solver client Now, we will create a solver client to perform combinatorial optimization using Amplify AE. The solver client class corresponding to Amplify AE is [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) class. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() ``` We also need to set the API token required to run Amplify AE. > [!TIP] > > **Tip** > > After [user registration](https://amplify.fixstars.com/en/register), you can obtain a free API token that can be used for evaluation and validation purposes. ```python client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` We will set the solver’s timeout. ```python import datetime client.parameters.time_limit_ms = datetime.timedelta(seconds=1) ``` ## Executing the solver Finally, we will execute the solver using the created combinatorial optimization model and the solver client to find the solution to the quadratic programming problem. ```python from amplify import solve result = solve(model, client) ``` The objective function value based on the best solution is shown below. ```python result.best.objective ``` ```text 177708.93275633463 ``` The values of the variables in the optimal solution can be obtained in the form of a NumPy multidimensional array as follows. ```python q_values = q.evaluate(result.best.values) print(q_values) ``` ```text [[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 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. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [1. 0. 0. 0. 0. 0. 0. 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. 1. 0. 0. 0. 0.]] ``` ## Checking the results We will visualize the results using 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/e9730ee7c465bb96d4dca4fb196a38ca9f51fd4cd274c4a0e9a9328a53ca9b48.png](https://amplify.fixstars.com/en/docs/amplify/v1/_images/e9730ee7c465bb96d4dca4fb196a38ca9f51fd4cd274c4a0e9a9328a53ca9b48.png) --- # Type Hint Support ![_images/type_hints.gif](https://amplify.fixstars.com/en/docs/amplify/v1/_images/type_hints.gif) The Amplify SDK defines type hints for all functions, methods, and attributes. This feature allows IDEs such as Visual Studio Code and Google Colaboratory to detect code errors through code completion and type checking. > [!TIP] > > **Hint** > > If using Visual Studio Code, install the [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) extension and add the following settings to enable code completion and type checking. > > `settings.json` > > ```json > { > "python.languageServer": "Pylance", > "python.analysis.typeCheckingMode": "basic", > } > ``` > [!TIP] > > **Hint** > > Depending on the method or function you call, the type or array dimension may not always be deterministic. > > For example, the [`amplify.einsum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) function returns [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) or [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) depending on the value of its argument, which may not be deterministic, resulting in an error or warning from the type checker. In such cases, you can avoid the error by specifying the type explicitly, as follows. > > ```python > from amplify import Poly, einsum > > # The argument "ij,ki,kj->" is expected to return a poly (scalar), but the type checker cannot determine it. > objective: Poly = einsum("ij,ki,kj->", d, q1, q2) # type: ignore > ``` --- # Proxy Server Settings If you want to connect to the Internet through a proxy server, you must configure the proxy server in the code that runs the Amplify SDK cloud service. > [!NOTE] > > **Note** > > You do not need to read this page if you are not using a proxy server to connect to the Internet. ## Installing the Amplify SDK You will need to specify a proxy when using the pip command. ```bash $ python3 -m pip install --proxy http://user:password@xxx.xxx.xxx.xxx:xxxx -U amplify ``` ## Running the solver from the Amplify SDK If your solver is deployed as a cloud service, you must set up a proxy for the solver client. > [!NOTE] > > **Note** > > Solvers provided as a cloud service are those with the ☁️ Cloud tag in the list of solvers on [this page](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md#solver-clients). Solvers with the πŸ’» Local tag do not require Internet access and, therefore, do not require proxy settings. Specify the proxy in the `proxy` keyword argument when building the solver client. The following example uses [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) as the solver client, but the same applies to other solver clients. ```python from amplify import AmplifyAEClient client = AmplifyAEClient(proxy="http://user:password@xxx.xxx.xxx.xxx:xxxx") ``` You can also specify the proxy at a later time. ```python from amplify import AmplifyAEClient client = AmplifyAEClient() client.proxy = "http://user:password@xxx.xxx.xxx.xxx:xxxx" ``` --- # Formatted Formula View The Amplify SDK formulas are automatically rendered in LaTeX in IPython front-end environments that support LaTeX formula display, such as Jupyter Notebook and Visual Studio Code. Polynomials, polynomial arrays, coefficient matrices, constraints, and models are displayed as mathematical expressions as follows. ## Variable array ```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} $$ ## Polynomial ```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} $$ ## Polynomial array ```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} $$ ## Constraint ```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} $$ ## Coefficient matrix ```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} $$ ## Model ```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} $$ --- # Migrating from Previous Versions The Amplify SDK v1 has lost some compatibility with v0. If you have been using an older version, this section explains how to maintain your code so that it will continue to work. ## Continue using the Amplify SDK v0 To keep your current code completely unchanged, you can continue to use the Amplify SDK v0. ```bash $ python3 -m pip install -U 'amplify<1.0.0' ``` To include additional packages, use the following. ```bash $ python3 -m pip install -U 'amplify[extra]<1.0.0' ``` Documentation for the Amplify SDK v0 is available at the following URL. > [!IMPORTANT] > > **Important** > > The Amplify SDK v0 is not guaranteed to work continuously. Other than critical bug fixes, there will be no feature additions or updates to the supported solvers. > > Please also note that it may stop working due to changes in the environment, such as the release of a new version of Python or changes in solver specifications. ## Migrating to the Amplify SDK v1 You can use the following guidelines to migrate code written in v0 to v1 ### Creating decision variables [`BinarySymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator) and [`IsingSymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) have been replaced by [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) with the addition of integer and real variables. The type of variable is specified by the [`array()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.array), [`scalar()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.scalar), and [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method arguments. Previous writing style: ```python from amplify import BinarySymbolGenerator, IsingSymbolGenerator gen = BinarySymbolGenerator() q = gen.array(10) gen = IsingSymbolGenerator() s = gen.array(shape=(4, 4)) ``` New writing style: ```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)) ``` ### Creating the objective function Once you create the variables described above, you can construct a polynomial as in previous versions. However, [dictionary construction](https://amplify.fixstars.com/en/docs/amplify/v0/polynomial.html#id2) is deprecated and will not be available. Matrix-style objective functions are now constructed using the [`matrix()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator.matrix) method instead of directly creating a matrix class. Also, the [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) class now includes quadratic, linear, and constant terms of the coefficients and the variables they contain. See β€œ[Objective Function with a Coefficient Matrix](https://amplify.fixstars.com/en/docs/amplify/v1/matrix.md)” for more information. Previous writing style (currently not working): ```python from amplify import BinaryMatrix m = BinaryMatrix(3) m[0, 0] = -2 m[0, 1] = 1 m[1, 2] = -1 m[2, 2] = 1 ``` New writing style: ```python from amplify import VariableGenerator gen = VariableGenerator() m = gen.matrix("Binary", shape=3) # Obtain quadratic terms m.quadratic[0, 0] = -2 m.quadratic[0, 1] = 1 m.quadratic[1, 2] = -1 m.quadratic[2, 2] = 1 # Obtain variables corresponding to the coefficient matrix q = m.variable_array ``` ### Creating constraints We have moved the constraint creation functions and classes from the `amplify.constraint` submodule to the `amplify` module. In addition, we have removed the penalty function, and the users can now define their own penalty functions by constructing [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) classes. See [specifying penalty functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#specify-penalty) for details. All other helper functions are only available by changing modules. Previous writing style: ```python from amplify.constraint import equal_to, penalty c = equal_to(q.sum(), 1) p = penalty(q[0] * q[1]) ``` New writing style: ```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]) ``` ### Model creation As before, models can be created by explicitly constructing the model class [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) in the Amplify SDK v1 or by summing the objective function and constraints. In previous versions, [`BinaryQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) and [`IsingQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) were the classes that represented the model and were also responsible for transforming the model into a second-order model based on the type of variables. In Amplify SDK v1, however, the models are no longer bound to variable types and orders, as they are compatible with solvers that can handle various variable types and orders. Therefore, the Amplify SDK no longer performs the model transformation process when the model is constructed, but rather, the optimal transformation process for the solver is performed within the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function by passing the client corresponding to the solver to be used to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. Previous writing style: ```python from amplify import BinaryQuadraticModel model = BinaryQuadraticModel(q.sum() ** 2, c) ``` New writing style: ```python from amplify import Model model = Model(q.sum() ** 2, c) ``` Previously, the users could obtain the result of the conversion to a quadratic model from the [`BinaryQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) and [`IsingQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) attributes, but in Amplify SDK v1, you can obtain them from the attribute of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class, which is the return value of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function, or you can explicitly call a model conversion method to check it. See β€œ[Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md)” for details. ### Executing the solver We have moved the solver client from the `amplify.client` submodule to the `amplify` module. The [`Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) class has also been removed, and the solver is now executed by passing the model and solver client to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. You can pass all model transformation and graph embedding parameters as parameters to the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function rather than as attributes of the model or solver class. [`FixstarsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) is still available in Amplify SDK v1, but it is recommended to use [`AmplifyAEClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient), which supports the new version of the Amplify AE solver. For details, see β€œ[Fixstars Amplify](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md)”. Previous writing style: ```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) ``` New writing style: ```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) ``` Also, the Amplify SDK sets the solution of intermediate models (old logical models) and the result of graph embedding to attributes of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class, which is the return value of the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. See β€œ[Variable Conversion and Degree Reduction](https://amplify.fixstars.com/en/docs/amplify/v1/intermediate.md)” and β€œ[Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/graph.md)” for details. ## Using the backward-compatible API To ensure that code written in v0 will work with Amplify SDK v1, we provide the legacy API as a backward-compatible API for v1. The backward-compatible API is not guaranteed to be 100% compatible, but it maintains compatibility with commonly used features and should work without modification in most cases. > [!IMPORTANT] > > **Important** > > We recommend migrating to the v1 API as soon as possible, as the backward-compatible API may be removed in future releases. > > This will be output as a warning ([`DeprecationWarning`](https://docs.python.org/3/library/exceptions.html#DeprecationWarning)) when the backward-compatible API is used. We provide the backward-compatible API with the following policy. ### Classes | Amplify SDK v0 (link to v1 compatible API) | Backward-compatible API details | | --- | --- | | [`BinaryPoly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md#amplify.BinaryPoly), [`IsingPoly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPoly.md#amplify.IsingPoly) | Subclassed as an alias of [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), but is not restricted to binary or Ising variables. Also, constructors and some methods are incompatible. | | [`BinaryPolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md#amplify.BinaryPolyArray), [`IsingPolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md#amplify.IsingPolyArray) | Subclassed as an alias of [`PolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray), but not restricted to binary or Ising variables. Also, constructors and some methods are not compatible. | | `BinaryIntPoly`, `IsingIntPoly`, `BinaryIntPolyArray`, `IsingIntPolyArray` | Not provided | | [`BinarySymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator), [`IsingSymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | Function as [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator), restricted to binary and Ising variables, respectively. | | `BinaryIntSymbolGenerator`, `IsingIntSymbolGenerator` | Not provided | | [`BinaryMatrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md#amplify.BinaryMatrix), [`IsingMatrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md#amplify.IsingMatrix) | Subclassed as an alias for [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix), but not restricted to binary or Ising variables. Also, the interfaces are not interchangeable. | | `BinaryIntMatrix`, `IsingIntMatrix` | Not provided | | [`BinaryQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel), [`IsingQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) | These are not created unless you explicitly call the constructor. They serve as v0-compatible models that can be used to obtain quadratic intermediate models (old logical models) of the binary and Ising variables, respectively. However, they cannot be passed to the new [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function; they can only be passed to the backward-compatible [`Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) class. | | `BinaryIntQuadraticModel`, `IsingIntQuadraticModel` | Not provided | | [`Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver), [`SolverResult`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverResult.md#amplify.SolverResult), [`SolverSolution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverSolution.md#amplify.SolverSolution) | Provided the same interface as v0 as a wrapper class for the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function. The return values of methods and properties are changed to the corresponding v1 classes. | ### Functions | Amplify SDK v0 (link to v1 compatible API) | Backward-compatible API details | | --- | --- | | `replace_all()` | Not provided | | [`sum_poly()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum_poly.md#amplify.sum_poly) | Alias for [`sum`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum.md#amplify.sum) | | `pair_sum()` | Not provided | | `product()` | Not provided | | `intersection()` | Not provided | | `union()` | Not provided | | `symmetric_difference()` | Not provided | | [`SymbolGenerator()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md#amplify.SymbolGenerator) | Alias for [`VariableGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableGenerator.md#amplify.VariableGenerator) | | `gen_symbols` | Not provided | | [`decode_solution()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.decode_solution.md#amplify.decode_solution) | A function version of [`evaluate()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.evaluate) | | `convert_to_matrix` | Not provided | ### Namespace | Amplify SDK v0 (link to v1 compatible API) | Backward-compatible API details | | --- | --- | | `amplify.constraint` | Provided for compatibility | | `amplify.client` | Provided for compatibility | --- # Formulation Benchmarks We have benchmarked the formulation of mathematical optimization models provided as a library in Python against the Amplify SDK. We measured the execution time to create a model and output it as QUBO using the [traveling salesperson problem formulation](https://amplify.fixstars.com/en/docs/amplify/v1/tsp.md) as an example, assuming using the QUBO solver. However, each library, including the Amplify SDK, covers different features depending on the formulation method. Here is a summary of the features and policies of each library, formulated as follows. | - | [Amplify](https://amplify.fixstars.com/en/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\* | | --- | --- | --- | --- | --- | --- | | Symbolic operation | βœ… | βœ… | ❌ | βœ… | βœ… | | Objective function | βœ… | βœ… | βœ… | βœ… | βœ… | | Constraint | βœ… | βœ…\*\* | ❌\*\*\* | ❌\*\*\* | βœ…\* | | Higher order polynomial | βœ… | βœ… | ❌ | ❌ | ❌ | | Coefficient matrix | βœ… | ❌ | ❌ | ❌ | ❌ | | Variable type | B/S/I/R | B/S | B/S | B/S | B/S/I/R | | Supported machines | Various | Depends on user | D-Wave only | D-Wave only | D-Wave only | B: Binary, S: Ising Spin, I: Integer, R: Real \*: Model creation only, as QUBO output (conversion of constraints to the penalty functions) is not available. \*\*: Must define penalty function \*\*\*: Constraints are expressed by adding penalty functions to the objective function 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 function objective: amplify.Poly = amplify.einsum( "ij,ki,kj->", distances, q[:-1], q[1:] ) # Constraints 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) # Objective function 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], ) # Constraint on each row for n in range(ncity): left = [(n * ncity + i, 1) for i in range(ncity)] bqm.add_linear_equality_constraint(left, dmax, -1) # Constraint on each column 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) ] # Objective function 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] # Constraint on each row for n in range(ncity): bqm += dmax * (sum(vars[n][i] for i in range(ncity)) - 1) ** 2 # Constraint on each column 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) ] # Objective function 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) # Constraint on each row for n in range(ncity): cqm.add_constraint(sum(vars[n]) == 1) # Constraint on each column 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 ``` Benchmark code ```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}") ``` **Benchmark environment** **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 ## Benchmark results *An interactive chart. Only the HTML edition shows it.* ### 32 cities (1,024 binary variables) | Formulation | Model construction | QUBO construction | Total | | --- | --- | --- | --- | | [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 cities (10,000 binary variables) | Formulation | Model construction | QUBO construction | Total | | --- | --- | --- | --- | | [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 cities (100,489 binary variables) | Formulation | Model construction | QUBO construction | Total | | --- | --- | --- | --- | | [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) is a solver provided by Fixstars Amplify. It uses heuristic algorithms based on simulated annealing on GPUs, leveraging their parallel computing capabilities to search for solutions with high speed and accuracy. It can handle binary variable optimization problems, which are composed of objective functions and constraints, making it suitable for practical applications. When combined with the Amplify SDK, it can be utilized to solve a broader range of general optimization problems. Further more, it serves as a highly accurate QUBO solver, ideal for researchers working with quantum annealing and Ising machines. For usage with the Amplify SDK, please refer to [Client Page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md) . ## Features of Amplify AE Amplify AE is a solver that explores solutions to optimization problems using a heuristic algorithm based on the annealing method. A particularly unique aspect is its utilization of parallel computing technology, specifically GPUs, which are known as AI semiconductors. By highly parallelizing the solving process, it harnesses the full potential of GPUs to minimize objective functions with high speed and accuracy. The functional specifications for the cloud-based Amplify AE are as follows: | | | | --- | --- | | **Variable Type** | Binary | | **Maximum Problem Size (Fully Connected)** | 8,192 variables (Basic) / 65,536 variables (Standard) / 131,072 variables (Premium) | | **Maximum Degree** | 4th degree (Objective Function) / 4th degree (Constraints) | | **Constraint Type** | Equality/Inequality (Constraint mode) / Penalty function (PUBO mode) | | **Precision** | Input: 64-bit real number / Computation: 64-bit real number / Data: 32-bit real number | | **Maximum Execution Time** | 10 seconds (Basic) / Over 10 minutes (Standard, Premium) | | **Supported GPUs** | NVIDIA Volta (Basic, Standard) / NVIDIA Ampere (Premium) / NVIDIA Hopper (Premium) | | **Multi-GPU Support** | 1 GPU (Basic) / Up to 8 GPUs (Standard, Premium) | | **Endpoint URL** | https://optigan.fixstars.com | **Basic, Standard, Premium:** Amplify subscription plans (Basic is free.). The Enterprise plan offers unlimited execution time with customizable settings. Problem size limitations are contingent upon GPU memory capacity and can exceed 131,072 variables. Supported GPUs include NVIDIA Volta / Ampere / Hopper and the latest NVIDIA Blackwell (coming soon). Access to Amplify AE with these GPUs is provided through Fixstars Amplify’s cloud service, as well as on-premises deployments. > [!TIP] > > **Changed in version 1.0.0** > > *Fixstars Amplify AE* received a major update in version 1.0.0, including support for higher-order polynomials, enhanced constraint handling, and improved solving performance. While previous versions only supported quadratic objective functions and penalty functions, the new version supports objective functions up to the 4th degree and equality/inequality constraints. Additionally, the automatic adjustment of penalty function weights has been improved. > This enables solving more complex optimization problems for a broader range of applications. A transition period is provided to ensure that previous versions remain available for a limited time. ### Input Specifications Amplify AE accepts polynomials of binary variables with real-valued coefficients. It addresses problems formulated with an objective function and constraints (or penalty functions), all expressible as polynomials up to the 4th degree. It supports up to 131,072 binary variables, but this is the maximum for a fully connected model (a model where variables are connected to all other variables). Input in a sparse format is possible, allowing you to solve larger problems with fewer connections. Constraints support both equality and inequality constraints (Constraint mode). In the PUBO mode described later, constraints can also be set using penalty functions. Solving requests are made as requests to the WEB API in JSON format. For API specifications, please refer to [API Reference](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/api_reference.md). ### Solving Modes Amplify AE features two solving modes: the default Constraint mode and PUBO (Polynomial Unconstrained Binary Optimization) mode. For general use, we recommend using the default Constraint mode. The PUBO mode, on the other hand, is designed for researchers using it as a simulator for quantum annealing or Ising machines. The main difference between the two lies in constraint handling. In the default Constraint mode, the solver directly handles equality and inequality constraints. In the PUBO mode, the user sets penalty functions for the desired constraints in the objective function. For technical details on these differences based on the Amplify AE operating algorithm, please refer to [Solving Algorithms](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/algorithm.md). Using the functions of the Amplify SDK, the Amplify SDK can automatically set constraints and penalty functions. Switching between Constraint mode and PUBO mode is also easy. Please refer to the [Clients page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md) for details. > [!TIP] > > **Changed in version 1.1.0** > > In version 1.1.0, a dense coupling mode specialized for large-scale quadratic problems with many terms has been added. > When using the Amplify SDK, the dense coupling mode can be used by formulating the objective function with [`Matrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix). > On the other hand, when [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) is used, the conventional sparse coupling mode is used. > However, depending on the number of terms and problem size, if the specified mode is determined to be inefficient, the other mode will be used instead. ### Parameter-Free Amplify AE does not require the user to adjust any parameters for solving. When the user input the optimization problem, the solver automatically determines the optimal annealing strategy and performs the appropriate solution process. For example, the temperature drop schedule in simulated annealing and penalty function weights are automatically adjusted. This allows users to maximize the performance of GPU annealing without requiring complex parameter tuning. ### Multi-GPU Support Amplify AE supports multi-GPU environments, allowing for parallel processing using multiple GPUs. Applications of multi-GPU utilization for Amplify AE include solving multiple different problems simultaneously and enhancing computational power for a single problem. The former is effective for multi-user environments or solving multiple problems concurrently. The latter allocating more computational resources to the same problem and performing inter-GPU communication to obtain a more accurate solution. In other words, higher-accuracy solutions can be obtained in a shorter time. --- # Solving Algorithms Fixstars Amplify Annealing Engine (Amplify AE) utilizes an optimization algorithm based on simulated annealing. This page provides an overview of the Amplify AE algorithm and details internal processing steps. ## GPU Annealing Simulated annealing aims to minimize an objective function to solve optimization problems. It begins by generating an initial solution for the variable set, which is then iteratively improved. At each step, a temperature parameter governs the transition to a new state. Higher temperatures increase the probability of transitioning to states further from the current solution (those with a higher objective function value), while lower temperatures favor transitions to states closer to the current solution (those with a lower objective function value). Initially, with higher temperatures, the algorithm explores a wider range of possibilities, allowing for significant changes. As the temperature decreases, the search narrows, focusing on finer improvements to the solution. By gradually reducing the temperature, the algorithm seeks to converge on an optimal solution. This process can be formulated as follows. Let $T$ denote the current temperature, $S$ the current state, $S'$ a new state, and $\varDelta f = f\left(S'\right) - f\left(S\right)$ the difference in the objective function $f$. The transition probability $P_{S \rightarrow S'}$ is expressed as (in the case of the Metropolis algorithm): $$ P_{S \rightarrow S'} = \min \left( 1, \exp \left( -\varDelta f / T \right) \right) $$ A new state $S'$ is generated, and the above equation is evaluated to probabilistically determine whether a state transition occurs. If the transition is accepted, the current state is updated to $S'$. By repeating updates while decreasing the temperature $T$ from high to low, improvement of the solution is expected. Because this process is performed sequentially, simulated annealing is generally difficult to parallelize. While several parallelization approaches have been proposed, Amplify AE employs a unique parallelization algorithm [[1]](#id2) specifically designed to leverage the computational power of GPUs, enabling it to execute the entire search process efficiently and at high speed. Specifically, it utilizes GPU parallel computing to generate candidate next states and evaluate the objective function, enabling efficient exploration with multiple candidate transitions. > [!NOTE] > > **Note** > > Due to the use of pseudo-random numbers for probabilistic state transitions, different solutions may be obtained across multiple runs, even with the same input. > Parallel computation on GPUs does not allow control over the order of calculations, meaning that even with a fixed pseudo-random number seed, consistent results cannot be guaranteed. > Therefore, setting a seed value is not currently supported in Amplify AE. On the other hand, in simulated annealing, scheduling the temperature changes is crucial. This temperature scheduling refers to determining the initial and final temperatures, as well as how the temperature decreases from the initial to the final value. Tuning the temperature schedule is essential for achieving high-precision solutions. To address this issue, Amplify AE features automatic temperature scheduling adjustment, allowing users to obtain optimal solutions without needing to configure temperature-related parameters. Conventional temperature schedules end the search after a specified number of steps. Amplify AE, in contrast, automatically determines the minimum unit of the search process based on the input problem and solving status. This is repeated continuously until the search continues until the specified solving time (`time_limit_ms` request parameter) elapses. Consequently, longer execution times increase the likelihood of obtaining higher-precision solutions. ### Objective Function Optimization Following the algorithm described above, a new state $S'$ and the corresponding objective function value $f\left(S'\right)$ are calculated for an input objective function as follows. First, we explain the optimization of the objective function in the absence of constraints. Since Amplify AE accepts polynomials of binary variables as input, a new state $S'$ is generated by flipping the value of a variable $q$ using the operation $q \leftarrow 1 - q$ (changing $0$ to $1$ or $1$ to $0$). The resulting difference in the objective function, $\varDelta f$, is expressed as: $$ \varDelta f_{\rm{obj}}^q = f\left(S'\,|\,q \leftarrow 1 - q \right) - f\left(S \,|\,q\right) $$ From this value, the state transition probability $P_{S \rightarrow S'}$ is calculated, and a uniform random number is generated to determine whether the state transition is accepted. If the transition is accepted, the current state $S$ is updated to the new state $S'$. ### Constraint Optimization When handling constraints in an annealing process, it is necessary to minimize the objective function for solutions that satisfy the given constraints. To obtain solutions that satisfy these constraints, one approach is to allow only state transitions that adhere to them. However, verifying whether candidate state transitions satisfy the constraints requires evaluating all constraints, which increases computational cost. Furthermore, restricting transitions to only those that satisfy the constraints can narrow the search space and may prevent reaching the optimal solution. Therefore, Amplify AE addresses this by introducing penalty functions corresponding to the constraints, treating them as additional terms to the objective function. Essentially, the penalty function is $0$ for solutions that satisfy the constraints and takes a positive value for those that do not. Minimizing the objective function while simultaneously driving the penalty function to $0$ results in a solution that satisfies the constraints. This approach is widely used when handling constraints in QUBO solvers such as quantum annealing and Ising machine hardware. During the search, deliberately allowing constraint-violating state transitions can broaden the search space. Given a constraint $c$ with penalty $g_c$, similar to the objective function, the difference in the penalty function $\varDelta g_c$ when flipping the variable $q$ is defined as: $$ \varDelta g_c^{q} = g_c\left(S'\,|\,q \leftarrow 1 - q \right) - g_c\left(S \,|\,q\right) $$ Furthermore, the difference in the objective function $\varDelta f$ is reinterpreted as: $$ \varDelta f = \varDelta f_{\rm{obj}}^q + w \sum_c \varDelta g_c^{q} $$ The state transition probability $P_{S \rightarrow S'}$ is calculated from this $\varDelta f$ to update the state. Here, $w \left(> 0 \right)$ represents the weight of the penalty function. It is important to note that the penalty function must be tuned appropriately to satisfy the constraints in the final state. If the weight of the constraints is too small relative to the change in the objective function, solutions that do not satisfy the constraints are more likely to be selected. Conversely, if the weight is too large, minimizing the objective function may become difficult. Achieving this balance is crucial for obtaining high-accuracy solutions. Amplify AE features an automatic penalty function weight adjustment, allowing users to achieve appropriate solutions without setting these parameters. Amplify AE evaluates penalty functions in two ways, depending on user input: (i) Default Mode When the user provides constraint expressions, Amplify AE calculates the penalty function at runtime as an expression that monotonically increases with the constraint violation amount. In this case, Amplify AE generates the penalty function $g_c$ as a function of the violation amount $d$ that satisfies the following properties: $$ \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*} $$ The penalty function is automatically generated based on the constraints entered by the user during the Amplify AE’s solving process. If the user wishes to specify the penalty function directly, use the PUBO mode. (ii) PUBO Mode When the user provides penalty functions instead of constraint conditions, the penalty value is evaluated using the specified penalty function. This operation mode is called PUBO mode. The penalty function must satisfy the following requirement: $$ g_c\left(d \right) \ge 0 $$ In PUBO mode, the user directly specifies the penalty function $g_c$ and its weight $w_c$. Using these, the difference in state transitions is calculated as follows: $$ \varDelta f = \varDelta f_{\rm{obj}}^q + w \sum_c w_c \varDelta g_c^{q} $$ The weight $w$ applied to the entire penalty function is automatically adjusted by Amplify AE, as described previously. In PUBO mode only, control over this feature can be requested using the `penalty_weight_calibration` field in the request data. If this is disabled (`false`), $w$ is fixed at 1. On the other hand, $w_c$ can be specified individually for each penalty function by the user, representing the relative weighting. The default value is $w_c = 1$. In cases where a solution satisfying the constraints cannot be obtained, adjusting this value by the user can improve the solution accuracy. Typically, when the violation amount $d$ is 0, the value of the penalty function is also 0, indicating that the constraint is satisfied. As an option, a threshold $d_{\text{th}}$ can be set to consider the violation amount below which the constraint is satisfied, even if the value of the penalty function value is not 0. This value needs to be set, for example, when setting the penalty for constraint conditions using [penalty relaxation](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#penalty-relaxation). Amplify AE uses this value to determine whether the obtained solution satisfies the constraints. When formulating using the Amplify SDK, $d_{\text{th}}$ is automatically set to an appropriate value according to the properties of the penalty function. > [!NOTE] > > **See also** > > For information on how to switch modes and set penalty functions using the Amplify SDK, please refer to [Client Page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md). --- [[1](#id1)] Patented --- # Advanced Usage Leveraging the information obtained from the response data can significantly enhance your use of Amplify AE. This section details advanced techniques for utilizing Amplify AE. ## Obtaining Execution Time Information After receiving a solving request from the user, Amplify AE executes the following steps and returns the results. [![../_images/timing_light.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_light.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_light.drawio.svg) [![../_images/timing_dark.drawio.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_dark.drawio.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/timing_dark.drawio.svg) 1. Request Data Parsing * Parses the user’s solve request and extracts necessary information from the JSON data. 2. Resource Allocation * Reserves available GPU resources for the user and prepares the environment for computation. 3. GPU-Based Solving * Executes an optimization algorithm based on the simulated annealing method. 4. Result Analysis and Return * Transfers computation results to host memory and returns the optimal solution, along with evaluation results for objective functions and constraints. The diagram above illustrates the solver execution timing as envisioned by the Amplify SDK. Amplify AE operates according to this diagram. The time from β€œReceive Request” to β€œStart Execution” corresponds to the processing time for steps 1 and 2 above. The time from β€œStart Execution” to β€œEnd Execution” corresponds to step 3, and the time from β€œEnd Execution” to β€œSend Response” corresponds to step 4. The `time_limit_ms` parameter in the request data specifies the time for step 3, but achiving exact adherence can be difficult, and the specified time may be slightly exceeded. Therefore, the actual processing time is recorded in the `execution_time_ms` field of the response data. Additionally, the waiting time for step 2 can be obtained from the `queue_time_ms` field in the response data. The timing information included in the response data is summarized below. | | | | --- | --- | | `execution_time_ms` | GPU solving time (in milliseconds) | | `queue_time_ms` | Waiting time in the resource allocation queue (step 2) (in milliseconds) | | `submitted_at` | Timestamp when the request was received (time of β€œReceive Request”) | | `started_at` | Timestamp when GPU processing started (start time of step 3) | > [!NOTE] > > **See also** > > For information on obtaining timing information using the Amplify SDK, refer to the [Client Page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md). During the period from β€œStart Execution” to β€œEnd Execution” in step 4, Amplify AE runs the optimization algorithm. It records the solution obtained and its execution times each time the best solution is updated. This provides the user with a history of the explored solutions. The acquisition timestamp for each solution is recorded in the `time_stamp_ms` field within the array elements of the `solutions` field. This timestamp represents the elapsed time since the start of step 3 (`started_at`). This information enables users to track the exploration progress. For an example of analyzing execution time using the Amplify SDK, refer to [Execution Time information](https://amplify.fixstars.com/en/docs/amplify/v1/timing.md). ## Obtaining Solve Information During the β€œExecution Time” in the above solve process, detailed information about the number of solving iterations performed by Amplify AE is recorded in the response data. During the solving phase, Amplify AE creates the next state from the current state (a combination of variable values) using a specified number of GPUs based on the annealing method. This operation is called a β€œflip”. The GPU performs a predetermined number of flips based on the solving situation and returns the best solution obtained to the CPU. This is called β€œsampling”. If the solution obtained through sampling is better than the previously known best solution, the known best solution is updated. This series of operations is performed until the specified time is reached, and the results are returned to the user as a history of solution updates. During the above solving process, Amplify AE records the following information in the response data. | | | | --- | --- | | `num_gpus` | Number of GPUs used for solving | | `num_flips` | Total number of flips attempted by all GPUs until the execution result is returned | | `num_samplings` | Number of solutions obtained (number of samplings) until returning the execution result is returned | | `version` | Version of Amplify AE and GPU name | > [!NOTE] > > **See also** > > For information on obtaining solving information with the Amplify SDK, refer to the [Client Page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md). ## Retrieving Duplicate Solutions When multiple solutions with the same objective function value exist, Amplify AE defaults to recording only the first solution found. This is because the process of updating the known best solution is only updated when a better solution is found. To change this behavior and retrieve all discovered duplicate solutions, set the `duplicate_solutions` parameter in the request data to `true`. This will record all solutions with different variable combinations but the same objective function value and return them in the array included in the `solutions` field of the response data. > [!NOTE] > > **Note** > > Note that the retrieval of all duplicate solutions is not assured. Amplify AE’s exploration algorithm is probabilistic, and even if multiple solutions with the same objective function value exist, all solutions are not guaranteed to be found. > [!NOTE] > > **See also** > > For information on obtaining duplicate solutions using the Amplify SDK, refer to the [Client Page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/fixstars.md). --- # Performance of Amplify AE To evaluate the performance of Amplify AE, we are obtaining benchmark results from two perspectives: (1) solution performance and (2) annealing speed. ## Solution Performance Benchmark We obtained the objective function values at different execution times using publicly available benchmark problems and real-world optimization problems as our benchmark set. For comparison, we also obtained benchmarks for two types of Ising machines from other companies. For these solvers, we tested multiple configurable parameter settings and present the case that yielded the best results. Since the internal algorithms and solution performance of Amplify AE are not dependent on the execution time (`time_limit_ms`), we plot multiple solutions (elapsed time and objective function value) included in the response of a single execution. On the other hand, for the solvers from other companies, we only obtained the best result per execution, so the data with different execution times are independent. Each data point displays the median value from 11 trials. If a feasible solution could not be obtained within the specified execution time, that data point is not plotted. ### Execution Environment * Amplify SDK v1.4.0 * Amplify AE v1.0.0 * 1 NVIDIA Hopper * Constraint mode ### Benchmark Problems The following is a summary of the problems used for benchmarking. We have selected several benchmark problems with objective functions of degree 2 or higher, as well as operational challenges from existing companies. | Problem Set | Number of Variables | Objective Function | Equality Constraints (Degree/Number) | Inequality Constraints | | --- | --- | --- | --- | --- | | [QKP (jeu_300_50_1)](https://cedric.cnam.fr/~soutif/QKP/jeu_300_50_1.txt) | 300 | Quadratic | None | Up to linear/1 | | [CVRP (E-n51-k5)](https://vrp.atd-lab.inf.puc-rio.br/media/com_vrp/instances/E/E-n51-k5.vrp) | 5,100 | Quadratic | Up to linear/160 | Up to linear/5 | | Production Planning Problem | 7,400 | Quadratic | Up to linear/933 | None | | Staff Scheduling Problem | 730 | Quadratic | Up to quadratic/365 | Up to linear/720 | ### Benchmark Results (Solving Performance) #### 2-Dimensional Quadratic Knapsack Problem (QKP, jeu_300_50_1) The knapsack problem is to find the selection of items that maximizes the total value, given the value and weight of items, such that the total weight does not exceed a specific limit. The *quadratic* knapsack problem (QKP) is a more challenging problem that considers the additional value generated by pairs of items. *An interactive chart. Only the HTML edition shows it.* | Solver Name | Time to Obtain Feasible Solution [[1]](#no-zero) | Time to Obtain Optimal Solution | | --- | --- | --- | | Amplify AE | **0.00176 s** πŸ† | **0.233 s** πŸ† | | Company A Solver | 3.09 s | 4.08 s | | Company B Solver | 0.12 s | 50.0 s | #### Capacitated Vehicle Routing Problem (CVRP, E-n51-k5) The Capacitated Vehicle Routing Problem (CVRP) is a problem of selecting the routes with the minimum distance or transportation cost among those that deliver goods to $n$ destinations using $k$ vehicles with limited carrying capacity. *An interactive chart. Only the HTML edition shows it.* | Solver Name | Time to Obtain Feasible Solution | Objective Function Value of Best Solution [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.0780 s** πŸ† | **589** πŸ† | | Company A Solver | 1.12 s | 653 | | Company B Solver | (Could not obtain feasible solution) | (Could not obtain feasible solution) | #### Production Planning Problem We solved the business challenge of minimizing production costs in a factory’s production schedule using Amplify AE. *An interactive chart. Only the HTML edition shows it.* | Solver Name | Time to Obtain Feasible Solution [[2]](#sec) | Time to Obtain Optimal Solution [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.140 s** πŸ† | **0.142 s** πŸ† | | Company A Solver | 30.7 s | 34.5 s | | Company B Solver | 4.08 s | (Could not obtain optimal solution) | #### Staff Scheduling Problem We solved the business challenge of creating the most efficient worker shift schedule under various constraints with Amplify AE. *An interactive chart. Only the HTML edition shows it.* | Solver Name | Time to Obtain Feasible Solution | Objective Function Value of Best Solution [[2]](#sec) | | --- | --- | --- | | Amplify AE | **0.026 s** πŸ† | **23.7** πŸ† | | Company A Solver | 21.0 s | 24.5 | | Company B Solver | (Could not obtain feasible solution) | (Could not obtain feasible solution) | ## Annealing Speed Benchmark In GPU annealing, a higher number of [flips per second](https://amplify.fixstars.com/en/docs/amplify/v1/amplify_ae/advanced.md#amplifyae-solveinfo) increases the number of combinations that can be explored, thus improving the chances of finding a better solution within a given time limit. Amplify’s cloud service offers higher-performance GPUs for its higher-tier plans. Therefore, we defined β€œannealing speed” as the number of variable flips per second and measured it in relation to GPU performance and the number of GPUs provided for each plan. The benchmarks used a set of problem sizes: small, medium, and large. For information on the types of GPUs provided in each plan, please refer to the [Pricing Page](https://amplify.fixstars.com/en/pricing). | GPU Name | Offered Plans | | --- | --- | | NVIDIA Volta | Basic / Standard | | NVIDIA Ampere | Premium | | NVIDIA Hopper | S Premium / Enterprise | ### Execution Environment * Amplify SDK v1.4.0 * Amplify AE 1.0.0 Constraint Mode * Number of GPUs: 1 - 4 (2 or more only for NVIDIA Hopper) ### Benchmark Results (Annealing Speed) We plotted the annealing speed as a ratio to the Basic plan and as absolute values. The differences between plans become more pronounced as the problem size increases. #### Max-Cut Problem (Fully Connected) **Basic Ratio** *An interactive chart. Only the HTML edition shows it.* **Absolute Value** *An interactive chart. Only the HTML edition shows it.* #### Max-Cut Problem (Sparsely Connected) **Basic Ratio** *An interactive chart. Only the HTML edition shows it.* **Absolute Value** *An interactive chart. Only the HTML edition shows it.* #### Traveling Salesman Problem **Basic Ratio** *An interactive chart. Only the HTML edition shows it.* **Absolute Value** *An interactive chart. Only the HTML edition shows it.* --- [[1](#id1)] Excluding the trivial solution (all zeros) [2] ([1](#id2),[2](#id3),[3](#id4),[4](#id5)) Time limit set to 60 seconds. --- # 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": "Check if the service is running properly.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Check if the service is running properly.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Check if the service is running properly.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Execute the solver synchronously.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Execute the solver asynchronously.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Execute the solver synchronously.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Execute the solver synchronously.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Execute the solver asynchronously.", "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": "Authorization header. Use `Bearer ` format." } ], "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": "Fetch the result of a job.", "operationId": "job_result_v1_jobs__job_id__get", "parameters": [ { "name": "job_id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "Job ID", "title": "Job Id" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "Authorization header. Use `Bearer ` format." } ], "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": "Fetch the result of a job.", "operationId": "job_result_v0_jobs__job_id__get", "parameters": [ { "name": "job_id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid", "description": "Job ID", "title": "Job Id" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string" }, "description": "Authorization header. Use `Bearer ` format." } ], "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": "Polynomial in the condition" }, "op": { "type": "string", "enum": [ "=", "==", "eq", "EQ", "<", "lt", "LT", ">", "gt", "GT", ">=", "ge", "GE" ], "title": "Op", "description": "Comparison operator", "default": "=" }, "right": { "type": "number", "title": "Right", "description": "Right-hand side value", "default": 0 } }, "type": "object", "required": [ "left" ], "title": "ConditionV0" }, "ConstraintV0": { "properties": { "penalty": { "$ref": "#/components/schemas/PolynomialV0", "description": "Penalty polynomial" }, "multiplier": { "type": "number", "title": "Multiplier", "description": "Weight of the penalty function", "default": 1 }, "condition": { "anyOf": [ { "$ref": "#/components/schemas/ConditionV0" }, { "type": "null" } ], "description": "Condition for the penalty function. If None, `penalty` is used as a value" } }, "type": "object", "required": [ "penalty" ], "title": "ConstraintV0" }, "ConstraintV1": { "anyOf": [ { "required": [ "lower" ] }, { "required": [ "upper" ] } ], "properties": { "lower": { "type": "number", "title": "Lower", "description": "Lower bound", "default": "-inf" }, "upper": { "type": "number", "title": "Upper", "description": "Upper bound", "default": "+inf" }, "expression": { "$ref": "#/components/schemas/PolynomialV1", "description": "polynomial for constraint" } }, "type": "object", "required": [ "expression" ], "title": "constraint" }, "DenseObjectiveV1": { "properties": { "matrix": { "items": { "items": { "type": "number" }, "type": "array" }, "type": "array", "title": "Matrix", "description": "Dense matrix representation of the objective function. It must be an upper-triangularmatrix whose format is [[a_11, ..., a_1n], [a_22, ..., a_2n], ..., [a_nn]]", "default": [] }, "constant": { "type": "number", "title": "Constant", "description": "Constant term of the objective function", "default": 0 } }, "type": "object", "title": "DenseObjectiveV1" }, "ExecutionParametersV0": { "properties": { "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs used" }, "timeout": { "type": "number", "minimum": 0, "title": "Timeout", "description": "Given timeout (msec)" }, "num_iterations": { "type": "integer", "minimum": 1, "title": "Num Iterations", "description": "Number of iterations until timeout" }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "description": "Whether calibration of penalty multipliers were enabled or not" }, "penalty_multipliers": { "items": { "type": "number" }, "type": "array", "title": "Penalty Multipliers", "description": "List of penalty multipliers used in search" }, "version": { "type": "string", "title": "Version", "description": "Version of 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": "Annealing time (msec)" }, "queue_time": { "type": "number", "minimum": 0, "title": "Queue Time", "description": "Queue waiting time (msec)" }, "cpu_time": { "type": "number", "minimum": 0, "title": "Cpu Time", "description": "CPU processing time (msec)" }, "time_stamps": { "items": { "type": "number" }, "type": "array", "title": "Time Stamps", "description": "Elapsed time when the solutions are obtained since the start of annealing (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 matrix" }, "OutputsV0": { "properties": { "spins": { "type": "boolean", "title": "Spins", "description": "Whether to output variable values", "default": true }, "energies": { "type": "boolean", "title": "Energies", "description": "Whether to output energy values", "default": true }, "feasibilities": { "type": "boolean", "title": "Feasibilities", "description": "Whether to output feasibility values", "default": true }, "sort": { "type": "boolean", "title": "Sort", "description": "Whether to sort outputs", "default": true }, "duplicate": { "type": "boolean", "title": "Duplicate", "description": "Whether to allow duplicates", "default": false }, "num_outputs": { "type": "integer", "title": "Num Outputs", "description": "Number of outputs", "default": 1 } }, "type": "object", "title": "OutputsV0" }, "PenaltyV1": { "properties": { "threshold": { "type": "number", "minimum": 0, "title": "threshold", "description": "Threshold of the penalty function", "default": 0 }, "weight": { "type": "number", "exclusiveMinimum": 0, "title": "weight", "description": "Weight for the penalty function", "default": 1 }, "expression": { "$ref": "#/components/schemas/PolynomialV1", "description": "penalty function" } }, "type": "object", "required": [ "expression" ], "title": "penalty" }, "PolynomialV0": { "items": { "anyOf": [ { "anyOf": [ { "type": "number", "description": "Coefficient" }, { "prefixItems": [ { "type": "number", "description": "Coefficient" } ], "type": "array", "maxItems": 1, "minItems": 1 } ], "title": "coefficient" }, { "prefixItems": [ { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "Index of variable" }, { "type": "number", "description": "Coefficient" } ], "type": "array", "maxItems": 2, "minItems": 2, "title": "linear" }, { "prefixItems": [ { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "Index of variable" }, { "type": "integer", "maximum": 4294967295, "minimum": 0, "description": "Index of variable" }, { "type": "number", "description": "Coefficient" } ], "type": "array", "maxItems": 3, "minItems": 3, "title": "quadratic" } ] }, "type": "array", "title": "PolynomialV0", "description": "QUBO polynomial" }, "PolynomialV1": { "items": { "prefixItems": [ { "type": "number", "description": "Coefficient" } ], "items": { "type": "integer", "maximum": 4294967295, "minimum": 0, "maxLength": 4, "minLength": 1, "description": "Indices of variables" }, "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": "Constant term", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "Settings for outputs" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "Constraints" } }, "type": "object", "required": [ "constraints" ], "title": "constraints-only" }, "RequestV0SolveMatrix": { "properties": { "constant": { "type": "number", "title": "Constant", "description": "Constant term", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "Settings for outputs" }, "matrix": { "$ref": "#/components/schemas/MatrixV0" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "Constraints" } }, "type": "object", "required": [ "matrix" ], "title": "matrix" }, "RequestV0SolvePolynomial": { "properties": { "constant": { "type": "number", "title": "Constant", "description": "Constant term", "default": 0 }, "timeout": { "type": "integer", "maximum": 600000, "minimum": 0, "title": "Timeout", "description": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "maximum": 4, "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "penalty_calibration": { "type": "boolean", "title": "Penalty Calibration", "default": true }, "outputs": { "$ref": "#/components/schemas/OutputsV0", "description": "Settings for outputs" }, "polynomial": { "$ref": "#/components/schemas/PolynomialV0" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV0" }, "type": "array", "title": "Constraints", "description": "Constraints" } }, "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": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "Whether to include duplicate solutions in response", "default": false }, "dense_objective": { "$ref": "#/components/schemas/DenseObjectiveV1", "description": "Objective function in matrix form" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV1" }, "type": "array", "title": "Constraints", "description": "List of constraints" } }, "type": "object", "required": [ "dense_objective", "constraints" ], "title": "Constraint mode (dense)" }, "RequestV1SolveDensePenalty": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "Whether to include duplicate solutions in response", "default": false }, "dense_objective": { "$ref": "#/components/schemas/DenseObjectiveV1", "description": "Objective function in matrix form" }, "penalties": { "items": { "$ref": "#/components/schemas/PenaltyV1" }, "type": "array", "title": "Penalties", "description": "List of penalty functions" }, "penalty_weight_calibration": { "type": "boolean", "title": "Penalty Weight Calibration", "description": "Whether to calibrate penalty weights automatically", "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": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "Whether to include duplicate solutions in response", "default": false }, "sparse_objective": { "$ref": "#/components/schemas/PolynomialV1", "description": "Objective function in polynomial form" }, "constraints": { "items": { "$ref": "#/components/schemas/ConstraintV1" }, "type": "array", "title": "Constraints", "description": "List of constraints" } }, "type": "object", "required": [ "sparse_objective", "constraints" ], "title": "Constraint mode (sparse)" }, "RequestV1SolveSparsePenalty": { "properties": { "time_limit_ms": { "type": "number", "exclusiveMinimum": 0, "title": "Time Limit Ms", "description": "Limit of execution time (msec)", "default": 10000 }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs to use for computation. 0 means to use all available GPUs", "default": 1 }, "duplicate_solutions": { "type": "boolean", "title": "Duplicate Solutions", "description": "Whether to include duplicate solutions in response", "default": false }, "sparse_objective": { "$ref": "#/components/schemas/PolynomialV1", "description": "Objective function in polynomial form" }, "penalties": { "items": { "$ref": "#/components/schemas/PenaltyV1" }, "type": "array", "title": "Penalties", "description": "List of penalty functions" }, "penalty_weight_calibration": { "type": "boolean", "title": "Penalty Weight Calibration", "description": "Whether to calibrate penalty weights automatically", "default": true } }, "type": "object", "required": [ "sparse_objective", "penalties" ], "title": "PUBO mode (sparse)" }, "ResponseHealth": { "properties": { "status": { "type": "string", "title": "Status", "description": "Service status" }, "version": { "type": "string", "title": "Version", "description": "Service version" } }, "type": "object", "required": [ "status", "version" ], "title": "ResponseHealth" }, "ResponseJobsError": { "properties": { "status": { "type": "string", "const": "Error", "title": "Status", "description": "Job status" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission datetime" }, "error": { "type": "string", "title": "Error", "description": "Error message" } }, "type": "object", "required": [ "status", "submitted_at", "error" ], "title": "ResponseJobsError" }, "ResponseJobsInProgress": { "properties": { "status": { "type": "string", "const": "InProgress", "title": "Status", "description": "Job status" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission datetime" }, "started_at": { "type": "string", "format": "date-time", "title": "Started At", "description": "Start datetime" } }, "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": "Job status" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission datetime" } }, "type": "object", "required": [ "status", "submitted_at" ], "title": "ResponseJobsSubmittedOrWaiting" }, "ResponseOnError": { "properties": { "error": { "type": "string", "title": "Error", "description": "Error message" } }, "type": "object", "required": [ "error" ], "title": "ResponseOnError" }, "ResponseV0AsyncSolve": { "properties": { "status": { "type": "string", "const": "Submitted", "title": "Status", "description": "Job status" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission time" }, "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": "Location URI to check the job status" } }, "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": "Execution time information (msec)" }, "energies": { "items": { "type": "number" }, "type": "array", "title": "Energies", "description": "Energy values of the annealing solutions" }, "spins": { "items": { "items": { "type": "integer", "enum": [ 0, 1 ] }, "type": "array" }, "type": "array", "title": "Spins", "description": "Spin configurations of the annealing solutions" }, "feasibilities": { "items": { "type": "boolean" }, "type": "array", "title": "Feasibilities", "description": "Feasibility of the annealing solutions" }, "execution_parameters": { "$ref": "#/components/schemas/ExecutionParametersV0", "description": "Execution parameters used in the annealing" }, "message": { "type": "string", "title": "Message", "description": "Warning message" } }, "type": "object", "required": [ "execution_time", "energies", "spins", "feasibilities", "execution_parameters", "message" ], "title": "ResponseV0SyncSolve" }, "ResponseV1AsyncSolve": { "properties": { "status": { "type": "string", "const": "Submitted", "title": "Status", "description": "Job status" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission time" }, "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": "Location URI to check the job status" } }, "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": "List of solutions" }, "execution_time_ms": { "type": "number", "minimum": 0, "title": "Execution Time Ms", "description": "Execution time (msec)" }, "queue_time_ms": { "type": "number", "minimum": 0, "title": "Queue Time Ms", "description": "Queue waiting time (msec)" }, "submitted_at": { "type": "string", "format": "date-time", "title": "Submitted At", "description": "Submission datetime" }, "started_at": { "type": "string", "format": "date-time", "title": "Started At", "description": "Start datetime" }, "num_gpus": { "type": "integer", "minimum": 0, "title": "Num Gpus", "description": "Number of GPUs used" }, "num_samplings": { "type": "integer", "minimum": 0, "title": "Num Samplings", "description": "Number of samplings" }, "num_flips": { "type": "integer", "minimum": 0, "title": "Num Flips", "description": "Number of flips" }, "warnings": { "items": { "type": "string" }, "type": "array", "title": "Warnings", "description": "List of warnings" }, "version": { "type": "string", "pattern": "(^\\d+\\.\\d+\\.\\d+(\\-.*)?(\\+.*)?$)", "title": "Version", "description": "The executed version of 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": "Time when the solution was obtained (msec)" }, "objective": { "type": "number", "title": "Objective", "description": "Objective value" }, "values": { "items": { "type": "integer", "enum": [ 0, 1 ] }, "type": "array", "title": "Values", "description": "Values of variables" }, "status": { "type": "string", "enum": [ "Infeasible", "Feasible", "Optimal" ], "title": "Status", "description": "Status of the solution" } }, "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 The Amplify SDK provides features for researching and validating combinatorial optimization using quantum computers. **πŸ”±οΈ Multiple device and algorithm support** Supports numerous devices β€” including quantum computers provided by IBM Quantum, Amazon Braket, and others β€” together with multiple quantum algorithms, making it easy to compare across devices and algorithms. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#multiple-solvers) **πŸ¦– Powerful interface** The Amplify SDK provides a powerful interface for working with quantum computers. It offers end-to-end support β€” from intuitive formulation, through conversion to a quantum circuit, all the way to execution on a quantum computer. [Learn more Β»](https://amplify.fixstars.com/en/docs/amplify/v1/features.md#easy-to-use) [Learn more about Amplify SDK features](https://amplify.fixstars.com/en/docs/amplify/v1/features.md) ## What is a Quantum Computer? A quantum computer is a computing machine that processes information based on the principles of quantum mechanics. Whereas a classical computer uses the **bit** β€” which takes either the value $0$ or $1$ β€” as its fundamental unit of information, a quantum computer uses the **quantum bit (qubit)**, which can be in a superposition of $0$ and $1$. Leveraging this superposition is expected to make it possible to efficiently handle problems that are intractable on classical computers. **Quantum algorithms** exploit these properties of quantum computers and are known to be applicable to combinatorial optimization. In this class of algorithms, the quantum computer handles circuit execution and measurement, while the classical computer drives the optimization using those results. They are actively researched and developed as methods that aim to run practically even on today’s quantum computers (NISQ devices). ## Optimization with Quantum Computers By using Amplify Quantum β€” an extension package of the Amplify SDK β€” you can run combinatorial optimization on quantum computers. > [!WARNING] > > **Caution** > > For combinatorial optimization with quantum annealing machines, see [D-Wave Systems](https://amplify.fixstars.com/en/docs/amplify/v1/clients/dwave.md). With Amplify Quantum, a single call to [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) automatically handles the conversion from model to quantum circuit, the classical optimization loop, and communication with the backend. You can easily run optimization with any combination of the supported quantum computers and quantum algorithms. The following illustrates how Amplify Quantum works internally when running [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md). The **algorithm class**, which handles the conversion from a mathematical optimization model to a quantum circuit and the classical optimization loop, cooperates with the **client class**, which handles quantum circuit execution by communicating with the quantum computer or simulator. Together they run optimization in your local Python environment. ```mermaid sequenceDiagram box rgba(90, 100, 120, 0.20) Inside Amplify Quantum participant Solve as solve() participant Algo as Algorithm class (QAOA) participant Client as Client class end participant Backend as Quantum computer / simulator Solve->>Algo: Mathematical optimization model Algo->>Algo: Convert to quantum circuit loop Repeat until convergence Algo->>Algo: Update parameters ΞΈ (classical optimization) Algo->>Client: Circuit for ΞΈ Client->>Backend: Execute the quantum circuit (cloud API / local) Backend-->>Client: Sampling results Client-->>Algo: Measurement results (Ising sequences, counts) end Algo-->>Solve: Optimal solution ``` ### Supported Devices The following quantum computers and simulators are available. They can be switched just by replacing the client class. #### Quantum Computer Providers IBM Quantum Superconducting AQT Trapped ion IonQ Trapped ion \* IQM Superconducting Rigetti Superconducting QUDORA Trapped ion \*\* #### Quantum Circuit Simulators Both local simulators that run on the user’s machine and simulators offered as cloud services are supported. Qulacs Simulator Local Qiskit Aer Simulator Local Amazon Braket Simulator Local / Cloud #### Other OQTOPUS Cloud \*\*\* Quantum computing platform For details on authentication and parameter configuration for each client, see the [list of supported devices](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/index.md). \* : In addition to real quantum computers, cloud simulators are also available. \*\* : Only the cloud emulator is available. \*\*\* : This includes β€œSystem F”, a quantum computer of Fujitsu Limited that AIST ABCI-Q provides. ### Supported Algorithms The following quantum optimization algorithms are available. Specify the algorithm when initializing the client class you use. The supported polynomial degree and constraint types depend on the chosen algorithm. QAOA Ising polynomial of arbitrary degree (unconstrained) Constrained QAOA Ising polynomial of arbitrary degree + N-HOT constraints Recursive QAOA Ising polynomial of arbitrary degree (unconstrained) For details on each algorithm and its execution parameters, see the [list of supported algorithms](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/index.md). --- # Quickstart ## Installation Quantum computing features are provided as an add-on to the Amplify SDK. To use them, install the package with the extra dependencies using the following command. ```bash $ python3 -m pip install -U 'amplify[quantum]' ``` Once installed correctly, you can use the quantum computing features as follows. ```python >>> from amplify import QAOA ``` The following environments have been verified. **Python versions** * 3.10 * 3.11 * 3.12 * 3.13 **Supported OS** * Windows 10/11 * Linux * Ubuntu 22.04/24.04/26.04, Rocky Linux 9.6/10.0 * x86_64 * macOS * ARM64 (Monterey or later) Installation of dependency packages may fail depending on your Python version and OS. > [!WARNING] > > **Caution** > > Unlike the [verified environments for the Amplify SDK](https://amplify.fixstars.com/en/docs/amplify/v1/quickstart.md#how-to-install), the following environments may not work. > > **Python versions** > > * 3.14 > > **Supported OS** > > * Linux > > * ARM64 > * macOS > > * x86_64 (Monterey or later) ## Solving with Quantum Computers > [!WARNING] > > **Caution** > > For solving with quantum annealing machines, see [D-Wave Systems](https://amplify.fixstars.com/en/docs/amplify/v1/clients/dwave.md). You can solve combinatorial optimization problems using various quantum computers offered as cloud services, as well as local simulators. Here, we use the [Qiskit Aer Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aer.md) β€” a local simulator β€” to execute the quantum circuit, together with [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) as the quantum optimization algorithm. ### 1. Creating the combinatorial optimization model Consider the following sample problem. For an explanation of how to formulate problems with the Amplify SDK, see the [Amplify SDK Quickstart](https://amplify.fixstars.com/en/docs/amplify/v1/quickstart.md#run-sample-code). **Sample QUBO Problem** **The objective function** $$ \text{minimize:} \quad f = q_0 q_1 + q_0 - q_1 + 1 $$ **The decision variables** $$ q_0, q_1 \in \{0, 1\} $$ **The constraints** $$ \text{None} $$ ```pycon >>> from amplify import Model, VariableGenerator >>> g = VariableGenerator() # Create a generator for decision variables >>> q = g.array("Binary", 2) # Define the decision variables >>> f = q[0] * q[1] + q[0] - q[1] + 1 # Define the objective function >>> model = Model(f) # Create the model ``` ### 2. Creating the solver client To run optimization with QAOA on the Qiskit Aer Simulator, we create the solver client using the Qiskit Aer Simulator client class ([`AerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient)) together with the QAOA algorithm class ([`QAOA`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA)). ```pycon >>> from amplify import QAOA, AerClient >>> client = AerClient(QAOA) # Combine QAOA with the Qiskit Aer Simulator ``` We also set the QAOA circuit depth to 2 and the number of measurements per optimization step to 1000. ```pycon >>> client.parameters.reps = 2 # Set the QAOA ansatz circuit depth to 2 >>> client.parameters.shots = 1000 # Set the number of measurements per optimization step to 1000 ``` As with other clients, run the solver via the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function to perform optimization with QAOA. ```pycon >>> from amplify import solve >>> result = solve(model, client) # Run QAOA ``` ### 3. Checking the results The result is returned as an instance of the [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class. This instance contains the result of the solver run and information about the model conversions performed. Calling the [`best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) property returns the best of the solutions obtained. For details on retrieving results, see [7. Solving combinatorial optimization problems - Retrieving the result](https://amplify.fixstars.com/en/docs/amplify/v1/solve.md#solver-result). ```pycon >>> result.best.objective # Value of the objective function 0.0 >>> result.best.values # Values of the variables Values({Poly(q_0): 0, Poly(q_1): 1}) ``` **Retrieving the quantum circuit**: The quantum circuit executed at each classical optimization step can be obtained via [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history). ```python >>> # Display the quantum circuit used for sampling >>> print(result.client_result.history[0].sampling_meta.circuit) ... ``` The type of the circuit object depends on the backend. With AerClient, it is a [`qiskit.circuit.QuantumCircuit`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit). For details, see [each client’s page](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md). **Retrieving the final measurement results**: The results of the final measurement performed with the optimized parameters $\boldsymbol{\theta}^{\textup{opt}}$ can be obtained via [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts). Each element is a tuple of β€œIsing sequence ($\{-1, 1\}$ valued) and count”; Ising sequences with higher counts are stronger candidates for the optimal solution. ```python >>> # Display measurement results at the optimal parameters, sorted by count (descending) >>> for ising_seq, freq in sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True): >>> print(f"Ising sequence: {ising_seq}, Count: {freq}") ``` For how to convert Ising sequences back to the original decision variable array and how to interpret the distribution, see [Measurement Results at Best Parameters](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-best-count). ## Next steps For details on connecting to quantum computers, see [Quantum computers](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md). For solving with each algorithm and retrieving detailed results, see [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) and [Recursive QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md). --- # List of Supported Devices A list of quantum computers and their simulators supported by the Amplify SDK. All clients share a common interface, and you can switch the optimization method simply by specifying one of the [supported algorithms](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/index.md) at initialization. For how to use each client and its authentication procedure, see [Quantum computers](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md), or the page for each individual client. * **Local simulators** (no registration required): Evaluate quantum circuits on your own machine. * [Qulacs Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qulacs.md) β€” [`QulacsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) * [Qiskit Aer Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aer.md) β€” [`AerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) * [Amazon Braket Simulator](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aws.md) β€” [`BraketSimulatorClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) (supports both local and cloud) * **Cloud QPUs**: Use quantum computers from each vendor. An account contract and API authentication are required for each vendor. * [IBM Quantum](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ibm.md) β€” [`IBMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) * [AQT](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/aqt.md) β€” [`AQTClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) * [IonQ](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/ionq.md) β€” [`IonQClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) * [IQM](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/iqm.md) β€” [`IQMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) * [Rigetti](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/rigetti.md) β€” [`RigettiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) * [QUDORA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/qudora.md) β€” [`QUDORAClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) * [OQTOPUS Cloud](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/samplers/oqtopus.md) β€” [`OqtopusClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) > [!TIP] > > **Hint** > > For quantum annealing machines, see [D-Wave Systems](https://amplify.fixstars.com/en/docs/amplify/v1/clients/dwave.md). --- # IBM Quantum Uses [IBM Quantum](https://quantum.cloud.ibm.com/) QPUs for circuit evaluation. Available as [`IBMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient). > [!NOTE] > > **Note** > > Requires an IBM Quantum API key obtained from your IBM Cloud account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.IBMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, superconducting qubits | | API method | REST API ([IBM Quantum](https://quantum.cloud.ibm.com/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/en/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 key. Used for authentication with [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service). | | [`url`](https://amplify.fixstars.com/en/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) | The connection URL for [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service). | | [`device`](https://amplify.fixstars.com/en/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) | The IBM Quantum device name for circuit execution. Default: the device selected automatically by [least_busy()](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#least_busy). | | [`channel`](https://amplify.fixstars.com/en/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) | The [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) channel. `"ibm_quantum_platform"`, `"ibm_cloud"`, `"local"`, etc. | | [`proxy`](https://amplify.fixstars.com/en/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) | Proxy server for connecting to [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service). | | [`verify`](https://amplify.fixstars.com/en/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) | Whether to verify the server’s TLS certificate. | | [`qiskit_pass_manager`](https://amplify.fixstars.com/en/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) | The Qiskit [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) used for circuit transpilation. The default (`...`) auto-generates one via [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) to skip transpilation. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`QiskitJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta). ```python meta = client_result.history[0].sampling_meta meta.job_id # Job ID meta.circuit # The executed Qiskit circuit object meta.transpiled_circuit # The circuit after transpilation (None if not transpiled) meta.metadata # Raw metadata from the job result meta.metrics # Metrics data such as execution time from the job result ``` **Configuration example**: ```python from amplify import QAOA, IBMClient # Create the client client = IBMClient(QAOA) # Set the API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Specify the execution device client.device = "ibm_fez" # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # Qiskit Aer Simulator Uses the [Qiskit Aer Simulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) for circuit evaluation. Available as [`AerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient). > [!TIP] > > **Tip** > > No setup required. > > By setting an IBM Quantum API key obtained from your IBM Cloud account, you can also use noise models that emulate real IBM Quantum devices. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.AerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based simulator | | API method | Local simulation ([Qiskit Aer](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: The client class has the following attributes and methods. | Attribute | Data type | Details | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The device on which the Aer Simulator runs. One of `"CPU"`, `"GPU"`, or `"Thrust"`. Default: `"CPU"`. See [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) for details. | | [`method`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.method) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The simulation method. `"automatic"`, `"statevector"`, `"density_matrix"`, etc. Default: `"automatic"`. See [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) for details. | | [`qiskit_pass_manager`](https://amplify.fixstars.com/en/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) | The Qiskit [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) used for circuit transpilation. The default (`...`) auto-generates one via [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) to skip transpilation. | | [`token`](https://amplify.fixstars.com/en/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 key. When set, IBM Quantum noise models can be downloaded and used. | | [`url`](https://amplify.fixstars.com/en/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) | The connection URL for [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service). | | [`proxy`](https://amplify.fixstars.com/en/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) | Proxy server for connecting to [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service). | | [`verify`](https://amplify.fixstars.com/en/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) | Whether to verify the server’s TLS certificate. | | [`noise_model`](https://amplify.fixstars.com/en/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) | The name of the IBM Quantum device to emulate with AerSimulator. [`None`](https://docs.python.org/3/library/constants.html#None) runs without noise. Valid names include those available from [FakeProviderForBackendV2](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/fake-provider-fake-provider-for-backend-v2). If a valid `token` is set, names retrievable via [QiskitRuntimeService.backend()](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#backend) are also available. | | [`channel`](https://amplify.fixstars.com/en/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) | The [QiskitRuntimeService](https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service) channel. `"ibm_quantum_platform"`, `"ibm_cloud"`, `"local"`, etc. | | Method | Arguments | Return type | Details | | --- | --- | --- | --- | | [`get_options()`](https://amplify.fixstars.com/en/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)] | Returns the Aer Simulator options that have been explicitly set via `set_options`. | | [`set_options()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md#amplify.AerClient.set_options) | Arbitrary keyword arguments | | Sets execution options for the Aer Simulator. See the [AerSimulator](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html) documentation for available options. Examples: `seed_simulator`, `noise_model`, `precision`, `fusion_enable`, etc. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`QiskitJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta). ```python meta = client_result.history[0].sampling_meta meta.job_id # Job ID meta.circuit # The executed Qiskit circuit object meta.transpiled_circuit # The circuit after transpilation (None if not transpiled) meta.metadata # Raw metadata from the job result meta.metrics # Metrics data such as execution time from the job result ``` **Configuration example**: ```python from amplify import QAOA, AerClient # Create the client client = AerClient(QAOA) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 # To use a noise model client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" client.noise_model = "fake_fez" # Set the simulation device client.device = "CPU" client.method = "automatic" ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() '0.17.2' ``` Check and set Aer Simulator options: ```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 A local simulator that uses [Qulacs](http://docs.qulacs.org/) for circuit evaluation. Available as [`QulacsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient). > [!TIP] > > **Tip** > > No setup required. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.QulacsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based simulator | | API method | Local simulation ([Qulacs](http://docs.qulacs.org/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: No client-specific attributes or methods. **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`QulacsJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed Qulacs circuit object ``` **Configuration example**: ```python from amplify import QAOA, QulacsClient # Create the client client = QulacsClient(QAOA) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # Amazon Braket Simulator Uses [Amazon Braket](https://aws.amazon.com/braket/) simulators for circuit evaluation. Both local and cloud simulators are supported. Available as [`BraketSimulatorClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient). > [!TIP] > > **Tip** > > No setup required. > > By authenticating with your own AWS account, you can also use cloud simulators (`SV1`, `DM1`). **Solver specification**: | | | | --- | --- | | Client class | [`amplify.BraketSimulatorClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based simulator | | API method | Local simulation / REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The simulator name or cloud simulator device ARN to use. Default: `"braket_sv"` Local simulators: * [braket_sv](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-sv) (state vector) * [braket_dm](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-dm) (density matrix) Cloud simulators: * [SV1](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-sv1) (state vector) * [DM1](https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-tasks-simulators.html#braket-simulator-dm1) (density matrix) | | [`provider`](https://amplify.fixstars.com/en/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) | Specifies the provider used to connect to the device. Currently, only [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) is supported. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object meta.metadata # Amazon Braket task metadata (task_id, created_at, ended_at) ``` **Configuration example**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, BraketSimulatorClient # Using a local simulator client = BraketSimulatorClient(QAOA) client.device = "braket_sv" # Using a cloud simulator client = BraketSimulatorClient(QAOA, device="SV1") boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # AQT Uses [AQT (Alpine Quantum Technologies)](https://www.aqt.eu/) trapped-ion quantum computers for circuit evaluation via [Amazon Braket](https://aws.amazon.com/braket/). > [!NOTE] > > **Note** > > Requires authentication with your own AWS account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.AQTClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, trapped-ion | | API method | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md#amplify.AQTClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The [AQT device](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html) name or device ARN to use. Default: `"IbexQ1"` | | [`provider`](https://amplify.fixstars.com/en/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) | Specifies the provider used to connect to the device. Currently, only [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) is supported. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object meta.metadata # Amazon Braket task metadata (task_id, created_at, ended_at) ``` **Configuration example**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, AQTClient # Create the client client = AQTClient(QAOA) # Specify the device client.device = "Ibex-Q1" # Set up AWS authentication (build AwsSession from an AWS profile) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # IonQ Uses [IonQ](https://ionq.com/)’s trapped-ion quantum computers for circuit evaluation. Available as [`IonQClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient). > [!NOTE] > > **Note** > > The following two methods are available for using IonQ. > > 1. Using an API token: Obtain an API token either by [registering as a Fixstars Amplify user](https://amplify.fixstars.com/en/register), or from your own IonQ account. > 2. Using [Amazon Braket](https://aws.amazon.com/braket/): Prepare your own AWS account credentials. Note that Python 3.11 or later may be required for authentication and communication. > [!TIP] > > **Hint** > > Amplify Quantum v1.2 added API token authentication support for [`IonQClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient). > If you are using an older version of the package, run the following command to upgrade to the latest version. > > ```bash > $ pip install -U 'amplify[quantum]' > ``` **Solver specification**: | | | | --- | --- | | Client class | [`amplify.IonQClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, trapped-ion | | API method | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes and methods. | Attribute | Data type | Details | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/en/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) | The API token used for authentication. | | [`url`](https://amplify.fixstars.com/en/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) | The endpoint URL to connect to. | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The [IonQ device](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html) name or device ARN to use. Default: `"Forte1"` | | [`provider`](https://amplify.fixstars.com/en/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) | Specifies the provider used to connect to the device. Currently, only [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) is supported. | | Method | Return type | Details | | --- | --- | --- | | [`get_options()`](https://amplify.fixstars.com/en/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)] | Gets the execution options explicitly set by `set_options`. | | [`set_options()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient.set_options) | [`None`](https://docs.python.org/3/library/constants.html#None) | Sets execution options. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object ``` **Configuration example**: ```python from amplify import QAOA, IonQClient # Create the client client = IonQClient(QAOA) # Specify the simulator (the simulator is only available via API token) client.device = "simulator" # client.set_options(noise_model="forte-1") # The noise model of the simulator # Specify the QPU (the QPU is available via a paid token or via Amazon Braket) # client.device = "qpu.forte-1" # When using the Forte-1 QPU # Set the API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` If you use Amazon Braket, replace the API token configuration with the following. ```python import boto3 from braket.aws import AwsSession session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=session) ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # IQM Uses [IQM](https://www.meetiqm.com/) superconducting quantum computers for circuit evaluation via [Amazon Braket](https://aws.amazon.com/braket/). Available as [`IQMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient). > [!NOTE] > > **Note** > > Requires authentication with your own AWS account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.IQMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, superconducting qubits | | API method | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md#amplify.IQMClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The [IQM device](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html) name or device ARN to use. Default: `"Garnet"` | | [`provider`](https://amplify.fixstars.com/en/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) | Specifies the provider used to connect to the device. Currently, only [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) is supported. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object meta.metadata # Amazon Braket task metadata (task_id, created_at, ended_at) ``` **Configuration example**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, IQMClient # Create the client client = IQMClient(QAOA) # Specify the device client.device = "Garnet" # Set up AWS authentication (build AwsSession from an AWS profile) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # Rigetti Uses [Rigetti](https://www.rigetti.com/) superconducting quantum computers for circuit evaluation via [Amazon Braket](https://aws.amazon.com/braket/). Available as [`RigettiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient). > [!NOTE] > > **Note** > > Requires authentication with your own AWS account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.RigettiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, superconducting qubits | | API method | REST API ([Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), the client class has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`device`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md#amplify.RigettiClient.device) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | The [Rigetti device](https://docs.aws.amazon.com/braket/latest/developerguide/braket-devices.html) name or device ARN to use. Default: `"Cepheus1108Q"` | | [`provider`](https://amplify.fixstars.com/en/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) | Specifies the provider used to connect to the device. Currently, only [Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/) is supported. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). Uses [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object meta.metadata # Amazon Braket task metadata (task_id, created_at, ended_at) ``` **Configuration example**: ```python import boto3 from braket.aws import AwsSession from amplify import QAOA, RigettiClient # Create the client client = RigettiClient(QAOA) # Specify the device client.device = "Cepheus-1-108Q" # Set up AWS authentication (build AwsSession from an AWS profile) boto_session = boto3.Session(profile_name="my-profile") client.provider = AwsSession(boto_session=boto_session) # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # QUDORA Uses [QUDORA](https://qudora.com/) trapped-ion quantum computers and their cloud simulators for circuit evaluation. Available as [`QUDORAClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient). > [!TIP] > > **Hint** > > [`QUDORAClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) was added in Amplify Quantum v1.1. > If you are using an older package version, run the following command to upgrade to the latest version. > > ```bash > $ pip install -U 'amplify[quantum]' > ``` > [!NOTE] > > **Note** > > An API token is required. > > Either obtain a free trial API token by [registering with Fixstars Amplify](https://amplify.fixstars.com/register), or obtain an API token from your own QUDORA Cloud account. **Solver specification**: | | | | --- | --- | | Client class | [`amplify.QUDORAClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based, trapped-ion | | API method | REST API (JSON) | | API reference | [πŸ“– API Reference](https://api.qudora.com/docs) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: The client class has the following attributes and methods. | Attribute | Data type | Details | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/en/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) | The API token used for authentication. | | [`url`](https://amplify.fixstars.com/en/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) | The endpoint URL to connect to. | | [`device`](https://amplify.fixstars.com/en/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) | The QUDORA device name on which the circuit will be executed. Default: [`"Qamelion"`](https://qudora.com/news/qudora-launches-qamelion-quantum-emulator-with-adaptive-noise-modeling/) | | [`qiskit_pass_manager`](https://amplify.fixstars.com/en/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) | The Qiskit [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) used to transpile the circuit. With the default (`...`), one is generated automatically by [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager). Set this to [`None`](https://docs.python.org/3/library/constants.html#None) to skip transpilation. | | Method | Return type | Details | | --- | --- | --- | | [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.solve) | Depends on the algorithm | Directly runs the solver API. Usually, use the [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) function instead. | | [`version()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient.version) | [`str`](https://docs.python.org/3/library/stdtypes.html#str) | Gets backend version information. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed circuit object ``` **Configuration example**: ```python from amplify import QAOA, QUDORAClient # Create the client client = QUDORAClient(QAOA) # Specify the device client.device = "Qamelion" # When using the Qamelion emulator (default) # Set the API token client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version: ```python >>> client.version() ``` --- # OQTOPUS Cloud Uses cloud quantum computers and simulators available via [OQTOPUS Cloud](https://oqtopus-cloud.readthedocs.io) for circuit evaluation. Available as [`OqtopusClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient). > [!NOTE] > > **Note** > > Only OQTOPUS Cloud instances reachable with `quri-parts-oqtopus==1.0.3` are supported. > > An OQTOPUS Cloud API token and endpoint URL are required. > [!TIP] > > **Hint** > > [`OqtopusClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) was added in Amplify Quantum v1.3. > If you are using an older package version, run the following command to upgrade to the latest version. > > ```bash > $ pip install -U 'amplify[quantum]' > ``` **Solver specification**: | | | | --- | --- | | Client class | [`amplify.OqtopusClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) | | [Execution parameters](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient.parameters) | Depends on the algorithm | | [Execution result](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | [Execution time](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) | Depends on the algorithm | | Quantum computer type | Gate-based | | API method | REST API ([OQTOPUS Cloud](https://oqtopus-cloud.readthedocs.io)) | The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. **Client class**: In addition to the [common client interface](https://amplify.fixstars.com/en/docs/amplify/v1/solvers.md#client-common-interface), it has the following attributes. | Attribute | Data type | Details | | --- | --- | --- | | [`token`](https://amplify.fixstars.com/en/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) | The OQTOPUS API token. | | [`url`](https://amplify.fixstars.com/en/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) | The endpoint URL of the OQTOPUS service. | | [`proxy`](https://amplify.fixstars.com/en/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) | The proxy server URL used when connecting. | | [`provider`](https://amplify.fixstars.com/en/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) | Use a `quri_parts_oqtopus.backend.OqtopusConfig` to set authentication information instead of the `token` / `url` / `proxy` attributes. The `provider` attribute takes precedence over the others. | | [`device`](https://amplify.fixstars.com/en/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) | The OQTOPUS device name on which the circuit will be executed. If [`None`](https://docs.python.org/3/library/constants.html#None), a device is chosen automatically from those available that satisfy the circuit’s qubit count. | | [`qiskit_pass_manager`](https://amplify.fixstars.com/en/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) | The Qiskit [`qiskit.transpiler.PassManager`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.PassManager) used to transpile the circuit. With the default (`...`), one is generated automatically by [generate_preset_pass_manager](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.transpiler.generate_preset_pass_manager). Set this to [`None`](https://docs.python.org/3/library/constants.html#None) to skip transpilation. | | [`name`](https://amplify.fixstars.com/en/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) | The name attached to the job submitted to OQTOPUS. | | [`description`](https://amplify.fixstars.com/en/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) | The description attached to the job submitted to OQTOPUS. | | [`transpiler_info`](https://amplify.fixstars.com/en/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) | Transpiler information forwarded to OQTOPUS. | | [`simulator_info`](https://amplify.fixstars.com/en/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) | Simulator information forwarded to OQTOPUS. | | [`mitigation_info`](https://amplify.fixstars.com/en/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) | Error mitigation settings forwarded to OQTOPUS. | | [`job_type`](https://amplify.fixstars.com/en/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) | The job type forwarded to OQTOPUS. | **Backend-specific metadata**: Detailed sampling information is available via [QAOA’s sampling_meta](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-sampling-meta). ```python meta = client_result.history[0].sampling_meta meta.circuit # The executed Qiskit circuit object (before transpilation) meta.transpiled_circuit # The circuit after transpilation (None if not transpiled) ``` **Configuration example**: ```python from amplify import QAOA, OqtopusClient # Create the client client = OqtopusClient(QAOA) # Set the endpoint URL and API token client.url = "" client.token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Set QAOA parameters client.parameters.reps = 1 client.parameters.shots = 100 ``` A `quri_parts_oqtopus.backend.OqtopusConfig` can also be passed directly. In this case, authentication is performed using only the value of `provider`. ```python from quri_parts_oqtopus.backend import OqtopusConfig client = OqtopusClient(QAOA) client.provider = OqtopusConfig.from_file() ``` **Execution example**: ```python from amplify import Model, VariableGenerator, solve # Create decision variables and the objective function g = VariableGenerator() q = g.array("Binary", 2) f = q[0] * q[1] + q[0] - q[1] + 1 # Create a model model = Model(f) # Run the solver result = solve(model, client) ``` Obtain the backend version ([quri-parts-oqtopus](https://pypi.org/project/quri-parts-oqtopus/) version): ```python >>> client.version() ``` --- # List of Supported Algorithms A list of algorithms that use quantum computers supported by the Amplify SDK. Clients that handle quantum computers are used by specifying one of the algorithm classes listed here at initialization. * [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md): The [`QAOA`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) class. It repeatedly optimizes and measures a parametric quantum circuit (ansatz) of depth $p$, and derives a solution from the measurement results at the best parameters. By configuring `QAOAType`, you can switch between the standard ansatz and an ansatz that takes N-HOT constraints into account. * [Recursive QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md): The [`RQAOA`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) class. It repeats shallow QAOA runs, eliminating one variable at a time at each step to reduce the problem size. Once the number of variables becomes small enough, it obtains the exact solution by brute force. Each page describes parameter configuration, how to obtain detailed information about the solution, and how to make use of the algorithm. For the mathematical framework of the quantum optimization algorithms themselves, see [Algorithm details](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/index.md). > [!NOTE] > > **Note** > > More algorithms are planned to be added in the future. --- # QAOA / Constrained QAOA QAOA (Quantum Approximate Optimization Algorithm) is a quantum-classical hybrid algorithm that alternates between quantum circuit operations on a quantum computer and classical optimization. It can solve optimization problems whose objective function is an $N$-th degree polynomial in Ising variables. To use QAOA, specify [`QAOA`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) as the algorithm when constructing a quantum computer client. This page covers how to configure QAOA parameters and retrieve detailed results, and make practical use of them. For algorithm details, see [QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md) and [Constrained QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md). The following example runs QAOA using [`QulacsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) and retrieves the execution results: ```python from amplify import QAOA, QulacsClient, VariableGenerator, Model, equal_to, solve # Generate an array of decision variables gen = VariableGenerator() q = gen.array("Binary", 5) # Create objective function and constraint objective = q[0] * q[1] - q[2] constraint = equal_to(q[0] + q[1] + q[2], 1) # Define the model model = Model(objective, constraint) client = QulacsClient(QAOA) result = solve(model, client) ``` ## Evaluating Execution Results For quantum computer solvers, the [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) and [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) attributes of the [`amplify.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class returned by [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) correspond to the communication time and circuit execution time with the quantum computer (real device or simulator), rather than with the solver service itself. In QAOA, the quantum state is measured `shots` times to sample Ising sequences, and this is repeated across optimization steps. Therefore, [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) and [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) represent the cumulative totals across all sampling rounds. ```python result = solve(model, client) result.response_time # Total communication time with QPU result.execution_time # Total execution time on QPU ``` The Ising sequence most frequently observed at the optimal parameters is a strong candidate for the optimal solution. However, since the most frequently observed Ising sequence is not guaranteed to be optimal, every Ising sequence sampled across all measurements during the optimization process is recorded. Among these, [`amplify.Result.best`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.best) returns the Ising sequence that yields the smallest objective function value. ### QAOA-Specific Results The [`amplify.Result.client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) attribute has an algorithm-specific type that contains detailed solution results, including information about the execution process. For `QAOA`, the corresponding type is [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result). #### QAOA Result Attributes | Attribute | Type | Description | | --- | --- | --- | | [`durations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.durations) | [`QAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) | Breakdown of execution time | | [`num_execution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.num_execution) | `int` | Total number of cost function evaluations (classical optimization iterations) | | [`optimized_cost`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_cost) | `float` | Best cost function value $C(\boldsymbol{\theta}^{\textup{opt}})$ found | | [`optimized_parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_parameters) | `tuple[float, ...]` | Best parameters $\boldsymbol{\theta}^{\textup{opt}}$ found | | [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) | `list[tuple[list[int], int]]` | Measurement results at the best parameters: list of (Ising sequence, count) tuples | | [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) | `Sequence[`[`QAOAHistoryItem`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem)]` | History of each parameter optimization step | #### [`QAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) (Execution Time Breakdown) [`durations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.durations) provides a breakdown of the time spent in each phase of QAOA. ```python d = result.client_result.durations result.total_time # Total time for amplify.solve d.total_time # Total elapsed time for QAOA d.total_response_time # Total communication time with the backend d.total_execution_time # Total execution time on the backend d.classical_processing_time # Time spent on classical optimization (= total_time - total_response_time) ``` The following diagram illustrates the relationship between each metric during QAOA execution. Sampling on the quantum computer is performed at each classical optimization iteration, with a final measurement to extract the solution. [![../../_images/sampling_timing.en.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/sampling_timing.en.svg)](https://amplify.fixstars.com/en/docs/amplify/v1/_images/sampling_timing.en.svg) * [`total_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_time): Total elapsed time including parameter optimization and final measurement * [`total_response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_response_time): Total time spent communicating with the quantum computer (real device or simulator) across all steps, including queue wait time * [`total_execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.total_execution_time): Total time the quantum computer (real device or simulator) was actually executing circuits * [`classical_processing_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations.classical_processing_time): Total time spent running the classical optimization algorithm (e.g., scipy.optimize.minimize), calculated as `total_time - total_response_time` #### [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) (QAOA Optimization History) [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.history) is a list of each parameter optimization step ([`QAOAHistoryItem`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem)). One entry is added each time the classical optimizer evaluates the cost function. ```python for step in result.client_result.history: print(step.timestamp) # Elapsed time from QAOA start to completion of this step print(step.parameters) # Parameter values theta for this step print(step.objective) # Cost function value C(theta) print(step.counts) # Measurement results (Ising sequence, count) print(step.sampling_durations) # Time spent on sampling print(step.sampling_meta) # Backend-specific metadata ``` #### [`sampling_meta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem.sampling_meta) (Backend-Specific Metadata) The contents of [`sampling_meta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAHistoryItem.md#amplify.QAOAHistoryItem.sampling_meta) vary by backend. **For Qiskit-based backends (AerClient / IBMClient)**: ```python meta = result.client_result.history[0].sampling_meta meta.job_id # Job ID meta.circuit # Executed Qiskit circuit object ``` For details on each client, see [quantum computer clients](https://amplify.fixstars.com/en/docs/amplify/v1/clients/quantum_algorithm.md). #### [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) (Measurement Results at Best Parameters) [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) contains the measurement results at the best parameters $\boldsymbol{\theta}^{\textup{opt}}$. Each element is a tuple of `(Ising sequence, count)`. Ising sequences with higher counts are stronger candidates for the optimal solution. ```python for ising_seq, freq in sorted(result.client_result.optimized_counts, key=lambda x: x[1], reverse=True): print(f"Ising sequence: {ising_seq}, Count: {freq}") ``` ##### Converting optimized_counts Ising Sequences to Variables The Ising sequences in [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) are raw measurement values of internal qubits expressed as Ising values ($\{-1, 1\}$). You can convert them to the original variable array using the `mapping` from [`amplify.Result.intermediate`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.intermediate). ```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"Solution: {values}, Count: {freq}") ``` ##### Distribution of optimized_counts and Optimization Quality The distribution of [`optimized_counts`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Result.optimized_counts) serves as an indicator of how well the QAOA parameter optimization performed. * **When results are concentrated on a few Ising sequences**: The quantum state has converged to specific solutions, indicating successful optimization. The most frequent Ising sequence is a strong candidate for the optimal solution. * **When results are spread across many Ising sequences**: The quantum state is distributed over a wide state space, indicating insufficient optimization. Consider increasing the [ansatz circuit depth](#qaoa-reps), adjusting the [classical optimizer](#qaoa-minimize), or changing the [QAOA type](#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"Unique Ising sequences: {len(bc)} / {total} shots") print(f"Most frequent Ising sequence count: {top_freq} ({100 * top_freq / total:.1f}%)") ``` ## Parameter Configuration Parameters for the specified algorithm are configured via `client.parameters`. All parameters have default values, so the algorithm works without explicit configuration. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | [`reps`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.reps) | `int` | `10` | [Ansatz circuit depth](#qaoa-reps) (number of layers $p$). Higher values increase expressiveness but deepen the circuit | | [`shots`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.shots) | `int` | `1024` | [Number of measurements](#qaoa-shots). Higher values improve statistical accuracy but increase execution time | | [`alpha`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.alpha) | `float` | `1.0` | [Cost function adjustment](#qaoa-alpha). Lower values place more weight on lower-energy solutions | | [`qaoa_type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.qaoa_type) | [`QAOAType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) | `AUTO` | [QAOA type](#qaoa-qaoatype). Changes the circuit structure and supported polynomial degree | | [`minimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) | [`MinimizeProtocol`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol) | [`ScipyMinimize()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) | [Classical optimization method](#qaoa-minimize). Defaults to scipy’s COBYLA | QAOA performance is heavily influenced by the ansatz circuit configuration and classical optimization settings. The following sections explain the role of each parameter and tips for tuning them. ### Ansatz Circuit Depth (reps) `reps` specifies the number of layers $p$ in the ansatz circuit. * Higher values increase the expressiveness of the quantum state, theoretically allowing the algorithm to approach better solutions. * However, deeper circuits increase the number of parameters proportionally to `reps`, which also affects the convergence of classical optimization. * On real hardware, deeper circuits are also more susceptible to noise. * Default: `10` **Example**: ```python client.parameters.reps = 5 ``` ### Number of Measurements (shots) `shots` specifies the number of measurements performed at each parameter optimization step and during final solution extraction. * Higher values improve the estimation accuracy of the cost function, yielding more stable results. * However, they increase the execution time per optimization step and the cost of QPU usage. * Default: `1024` **Example**: ```python client.parameters.shots = 2048 ``` ### Cost Function Adjustment (alpha) In QAOA, the objective function’s expectation value is typically computed from the sampled quantum states and used as the cost for classical minimization. With the default $\alpha = 1.0$, the expectation value is used as the cost, just as before, but setting $0 < \alpha < 1.0$ allows the Conditional Value-at-Risk (CVaR) to be used as the cost instead. [[1]](#id2) With CVaR, the energy values obtained from measurements are sorted in ascending order, and the cost is the average of the lowest $\text{ceil}(\alpha \times \text{shots})$ of them. Therefore, at $\alpha = 1.0$, CVaR reduces to the average over all measurement results, coinciding with the expectation value. Decreasing $\alpha$ places more weight on lower-energy samples, which can guide the optimization toward sampling good solutions more frequently. However, decreasing $\alpha$ also reduces the number of samples used to estimate the cost, so a larger `shots` value is needed to maintain estimation accuracy. ### QAOA Type (qaoa_type) `qaoa_type` specifies which QAOA ansatz variant to use. | QAOAType | Accepted polynomial degree | Description | | --- | --- | --- | | [`AUTO`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.AUTO) (default) | Ising: arbitrary degree | Automatically selects between ORIGINAL and NHOT depending on whether constraints are present | | [`ORIGINAL`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.ORIGINAL) | Ising: arbitrary degree | Uses the standard QAOA ansatz | | [`NHOT`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.NHOT) | Ising: arbitrary degree | Uses an ansatz that accounts for N-HOT constraints (constraints where exactly $n$ variables in an Ising variable sequence take the value $-1$) | | [`AUTO_QUADRATIC`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.AUTO_QUADRATIC) / [`ORIGINAL_QUADRATIC`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.ORIGINAL_QUADRATIC) / [`NHOT_QUADRATIC`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType.NHOT_QUADRATIC) | Ising: degree 2 | Handles problems only up to quadratic degree for each corresponding QAOA variant | > [!NOTE] > > **Note** > > For types with the `_QUADRATIC` suffix, the Amplify SDK automatically reduces higher-order objective functions to quadratic or lower. This degree reduction may introduce auxiliary variables, increasing the number of qubits. For algorithm details, see [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md) and [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md). **Example**: ```python from amplify import QAOAType client.parameters.qaoa_type = QAOAType.AUTO # Default ``` ### Classical Optimization Method (minimize) `minimize` specifies the classical optimization method used for parameter optimization. The default is [`ScipyMinimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize). #### ScipyMinimize [`ScipyMinimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) is an optimization method that wraps `scipy.optimize.minimize`. You can pass `scipy.optimize.minimize` parameters through the object’s properties. For details on each parameter, see the [SciPy documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | [`method`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.method) | `str` | `"COBYLA"` | Classical optimization algorithm name | | [`tol`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.tol) | `float | None` | `None` | Convergence tolerance. `None` uses scipy’s default | | [`x0`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.x0) | `list[float] | None` | `None` | Initial parameter values. `None` for random initialization | | [`options`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize.options) | `dict | None` | `None` | Additional options passed to scipy (`maxiter`, `disp`, etc.) | > [!TIP] > > **Tip** > > The choice of `method` depends on the problem and situation, but gradient-free `"COBYLA"` is commonly used for optimization on quantum computers. **Example**: ```python from amplify import ScipyMinimize client.parameters.minimize.method = "COBYLA" # Optimization algorithm client.parameters.minimize.tol = None # Convergence tolerance client.parameters.minimize.x0 = None # Initial parameter values (None for random) client.parameters.minimize.options = {"maxiter": 100, "disp": True} ``` #### NoOpMinimize (Skip Optimization) [`NoOpMinimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) skips classical optimization and directly performs measurement with the specified parameters. Use this when you want to re-measure with already-optimized parameters. By reusing optimized parameters with an increased `shots` value, you can improve statistical accuracy. **Example**: ```python from amplify import NoOpMinimize # First run: normal QAOA (parameter optimization + measurement) result = solve(model, client) best_params = result.client_result.optimized_parameters # Second run: re-measure with optimized parameters (increased shots for better accuracy) client.parameters.shots = 4096 client.parameters.minimize = NoOpMinimize(best_params) result2 = solve(model, client) ``` In this case, `result2.client_result.num_execution` will be `1`, confirming that only a single measurement was performed. --- [[1](#id1)] 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 Recursive QAOA is a quantum-classical hybrid algorithm that repeatedly executes QAOA as a subroutine, progressively reducing the problem size to identify the optimal solution. At each step, variables to eliminate are determined from the measurement results of a shallow-circuit QAOA, and once the problem is small enough, an exact solution is found by brute force. This approach relaxes the circuit depth constraints that are challenging in standard QAOA, aiming for applicability to larger-scale problems. It can solve optimization problems with objective functions expressed as $N$-th degree polynomials in Ising variables. To use RQAOA, specify [`RQAOA`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) as the algorithm when constructing a quantum computer client. This page covers how to configure RQAOA parameters and retrieve detailed results, and make practical use of them. For algorithm details, see [RQAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md). The following example runs RQAOA using [`QulacsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) and retrieves the execution results: ```python from amplify import RQAOA, QulacsClient, VariableGenerator, Model, solve # Generate an array of decision variables gen = VariableGenerator() q = gen.array("Binary", 5) # Create objective function objective = q[0] * q[1] - q[2] # Define the model model = Model(objective) client = QulacsClient(RQAOA) result = solve(model, client) ``` > [!NOTE] > > **Note** > > RQAOA does not support constrained problems. If constraints are present, the SDK automatically converts the problem to an unconstrained one by introducing penalty terms. ## Evaluating Execution Results For quantum computer solvers, the [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) and [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) attributes of the [`amplify.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) class returned by [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) correspond to the communication time and circuit execution time with the quantum computer (real device or simulator), rather than with the solver service itself. In RQAOA, QAOA is called multiple times as a subroutine to perform optimization. Therefore, [`amplify.Result.response_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.response_time) and [`amplify.Result.execution_time`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.execution_time) represent the cumulative totals across all QAOA invocations. ```python result = solve(model, client) result.response_time # Total communication time with QPU result.execution_time # Total execution time on QPU ``` In RQAOA, the optimal solution is uniquely determined by brute-force search on the reduced problem. The corresponding unique solution to the original (pre-reduction) problem is then recovered from this reduced solution. Therefore, [`amplify.Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) contains only this single solution. ### RQAOA-Specific Results The [`amplify.Result.client_result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result.client_result) attribute has an algorithm-specific type that contains detailed solution results, including information about the execution process. For `RQAOA`, the corresponding type is [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result). #### RQAOA Result Attributes | Attribute | Type | Description | | --- | --- | --- | | [`durations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.durations) | [`RQAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) | Breakdown of execution time | | [`num_execution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.num_execution) | `int` | Total number of cost function evaluations by QAOA at each step (number of classical optimization iterations) | | [`optimized_objective`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.optimized_objective) | `float` | Best cost function value $C(\boldsymbol{\theta}^{\textup{opt}})$ found | | [`optimized_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.optimized_solution) | `tuple[int, ...]` | Best solution | | [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) | `Sequence[`[`RQAOAHistoryItem`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem)]` | History of each QAOA variable-reduction step | ##### [`RQAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) (Execution Time Breakdown) `durations` provides a breakdown of the time spent in each phase of RQAOA. ```python d = result.client_result.durations result.total_time # Total time for amplify.solve d.total_time # Total elapsed time for RQAOA d.total_response_time # Total communication time with the backend d.total_execution_time # Total execution time on the backend d.classical_processing_time # Time spent on classical optimization (= total_time - total_response_time) ``` #### [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) (RQAOA Optimization History) [`history`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Result.history) is a list of each QAOA step ([`RQAOAHistoryItem`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem)) performed for variable reduction. ```python for step in result.client_result.history: print(step.timestamp) # Elapsed time from RQAOA start to completion of this step print(step.model) # Objective function at this step after variable reduction print(step.qaoa_result) # QAOAResult print(step.elimination_info) # Variable elimination information chosen from this step's results ``` ## Parameter Configuration | Parameter | Type | Default | Description | | --- | --- | --- | --- | | [`reps`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.reps) | `int` | `10` | [Ansatz circuit depth](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-reps) (number of layers $p$). Higher values increase expressiveness but deepen the circuit | | [`shots`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.shots) | `int` | `1024` | [Number of measurements](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-shots). Higher values improve statistical accuracy but increase execution time | | [`alpha`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.alpha) | `float` | `1.0` | [Cost function adjustment](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-alpha). Lower values place more weight on lower-energy solutions | | [`qaoa_type`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.qaoa_type) | [`RQAOAType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) | `ORIGINAL` | [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype). Choose from `ORIGINAL_QUADRATIC` or `ORIGINAL` | | [`minimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.minimize) | [`MinimizeProtocol`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md#amplify.MinimizeProtocol) | [`ScipyMinimize()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) | [Classical optimization method](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-minimize). Defaults to scipy’s COBYLA | | [`min_size`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.min_size) | `int` | `2` | Variable reduction continues until the number of variables reaches this value | | [`max_degree`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.max_degree) | `int|None` | `None` | Limits the maximum degree of terms targeted for variable reduction. `None` means no limit | | [`min_corr`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA.Parameters.min_corr) | `float` | `0` | Only terms whose absolute expectation value exceeds this threshold are targeted for variable reduction | ### Target Variable Count (min_size) `min_size` specifies how far RQAOA should reduce the number of variables in the problem. For details, see [RQAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md). Depending on the values of `max_degree` and `min_corr` described below, variable reduction may not always be possible; in such cases, reduction is halted and the algorithm proceeds to brute-force search for the optimal solution. * Each reduction step eliminates one variable. The number of QAOA executions equals the difference between the original variable count and `min_size`. * Since brute force is used to identify the optimal solution, larger `min_size` values increase the time needed for exact solution identification. * Default: `2` **Example**: ```python client.parameters.min_size = 2 ``` ### Maximum Term Degree for Reduction (max_degree) `max_degree` limits the degree of terms from which variables are selected for elimination in RQAOA. For details, see [RQAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md). * For values of `3` or higher, be aware that variable reduction may increase the degree of the problem. * If all terms in the objective function have degree lower than `max_degree`, reduction is halted and the algorithm proceeds to optimal solution search. * Default: `None` **Example**: ```python client.parameters.max_degree = 2 ``` ### Minimum Expectation Value Threshold (min_corr) `min_corr` sets the minimum expectation value that a term must exceed to be targeted for variable reduction in RQAOA. For details, see [RQAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md). * If the expectation values of all terms in the objective function fall below `min_corr`, reduction is halted and the algorithm proceeds to optimal solution search. * Default: `0` **Example**: ```python client.parameters.min_corr = 0 ``` --- # Algorithm Details This section introduces the theoretical framework of the quantum optimization algorithms supported by the Amplify SDK. Each algorithm’s page explains the details of the algorithm and its underlying theory. * [QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md): A representative variational quantum algorithm that combines a quantum computer with classical optimization to solve combinatorial optimization problems (PUBO). It constructs a Hamiltonian corresponding to the problem and approximately searches for its ground state using a parametric quantum circuit (ansatz). * [Constrained QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md): A QAOA that uses an ansatz accounting for N-HOT constraints (equality constraints where exactly $n$ variables take the value $-1$). By optimizing within the subspace of quantum states restricted by the constraints, it is expected to handle constrained problems more efficiently than the penalty method. * [Recursive QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/RQAOA_algo.md): A method that repeatedly executes shallow QAOA, progressively reducing the problem’s variables before identifying the optimal solution. It aims to apply QAOA to larger-scale problems while keeping the circuit depth low. --- # QAOA Algorithm This page describes the mathematical framework of QAOA (Quantum Approximate Optimization Algorithm) [[1]](#id4). ## The Optimization Problem Solved by QAOA QAOA is an algorithm that solves combinatorial optimization problems using quantum computers and classical optimization. Specifically, QAOA handles the class of problems known as Polynomial Unconstrained Binary Optimization (PUBO). As the name suggests, PUBO involves minimizing an objective function expressed as a polynomial of binary variables $x = (x_1, x_2, \ldots, x_n) \quad (x_i \in \{0,1\},\ i=1,2,\ldots,n)$ without constraints (unconstrained). Formally, with $f$ as a polynomial in $x$: $$ \mathrm{minimize}_{x \in \{0,1\}^n} \quad f(x) $$ In quantum computing, it is generally more convenient to work with Ising variables $z = (z_1, z_2, \ldots, z_n), \quad z_i \in \{-1,1\}$ rather than binary variables $x \in \{0,1\}^n$. Therefore, given a binary function $f(x)$ to optimize, we apply the variable transformation $z_i = 2x_i - 1$ and define an equivalent Ising function $\tilde f$ such that $\tilde f(z) = f(x)$. In what follows, we consider the minimization of this Ising function $\tilde f(z)$. > [!IMPORTANT] > > **Important** > > In the Amplify SDK, binary variables $x \in \{0,1\}$ and Ising variables $z \in \{-1,1\}$ satisfy the following relationship: > > > $$ > z = 2x - 1, \qquad x = \frac{1 + z}{2} > $$ > Since $z$ is defined in terms of $x$, and $f(x)$ is a polynomial in $x$, it follows that $\tilde f(z)$ is also a polynomial in $z$. In the following, we denote each monomial composing the polynomial $\tilde f(z)$ as $\tilde f_{\alpha}(z)$, and write: $$ \tilde f(z) = \sum_{\alpha}\tilde f_{\alpha}(z) $$ ## Quantum States Before describing QAOA itself, let us briefly review how information is represented in quantum computers. In classical computing, information is represented as sequences of β€œbits” consisting of $0$ and $1$. In the quantum computing world, the analog of a bit is called a **qubit**, which is represented as a complex-valued 2-dimensional vector normalized to unit length β€” a **quantum state**. While a classical bit takes only one of two values, $0$ or $1$, a qubit can exist in a richer variety of quantum states. Mathematically, a quantum state $\ket{\psi}$ is represented as a column vector $(\alpha,\beta)^T$ with complex numbers $\alpha, \beta$ satisfying $|\alpha|^2 + |\beta|^2 = 1$. In quantum information, one typically defines an orthonormal basis $\{\ket{0}, \ket{1}\}$ with $\ket{0} = (1,0)^{T},\quad \ket{1} = (0,1)^{T}$ and writes: $$ \ket{\psi} = \alpha \ket{0} + \beta \ket{1} $$ This orthonormal basis is called the **computational basis**. Throughout this document, all matrix representations of quantum states are given in the computational basis. In general, an $n$-qubit quantum state is represented by a $2^n$-dimensional complex vector. The basic principles are the same as in the single-qubit case. ## Hamiltonians In QAOA, the given objective function is converted into a Hermitian operator acting on qubits, and its value is evaluated on the quantum computer. This operator corresponding to the objective function is called the **Hamiltonian**. Mathematically, a Hermitian operator is a linear operator whose conjugate transpose (transpose combined with complex conjugation) equals itself. As an example, consider the matrix representation for a single qubit (2-dimensional complex vector space). A linear operator expressed using complex numbers $a,b,c,d$: $$ A = \begin{pmatrix} a & b \\ c & d \end{pmatrix} $$ is Hermitian if and only if its conjugate transpose $$ A^\dagger = \begin{pmatrix} a^* & c^* \\ b^* & d^* \end{pmatrix} $$ satisfies $A^\dagger = A$. From this condition, any single-qubit Hermitian operator $A$ can be expressed using real numbers $x,y$ and a complex number $z$ as: $$ A = \begin{pmatrix} x & z \\ z^* & y \end{pmatrix} $$ Important examples of single-qubit Hermitian operators are the Pauli operators. In matrix form: $$ 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} $$ These are called the identity operator $I$, Pauli $X$ operator, Pauli $Y$ operator, and Pauli $Z$ operator, respectively. As described in [Hamiltonian Construction](#hamiltonian-construction), QAOA constructs the Hamiltonian by replacing the Ising variables in the objective function with Pauli $Z$ operators. From the definition of the Pauli $Z$ operator, the computational basis $\{\ket{0}, \ket{1}\}$ consists of eigenvectors of the Pauli $Z$ operator. In particular: $$ Z\ket{0} &= \ket{0} \\ Z\ket{1} &= -\ket{1} $$ That is, the Pauli $Z$ operator takes the value $Z = 1$ when the qubit is in $\ket{0}$ and $Z = -1$ when the qubit is in $\ket{1}$, showing that in the computational basis the Pauli $Z$ operator behaves like an Ising variable. In this sense, a Hamiltonian built from Pauli $Z$ operators corresponds to the objective function originally defined in terms of Ising variables. This relationship also shows that the quantum state $\ket{0}$ corresponds to the Ising value $1$, and $\ket{1}$ corresponds to the Ising value $-1$. ## Quantum Measurement **Quantum measurement** extracts classical bit information from the state of qubits in a quantum computer. Here we discuss the most fundamental type: **measurement in the computational basis**. Since all measurements required in QAOA are computational basis measurements, we simply refer to this as β€œquantum measurement” unless stated otherwise. A quantum measurement on the single-qubit state $$ \ket{\psi} = \alpha\ket{0} + \beta\ket{1} $$ is understood as **an operation that yields the value β€œ0” with probability $|\alpha|^2$ and β€œ1” with probability $|\beta|^2$**. A crucial point is that **performing a quantum measurement destroys the state $\ket{\psi}$**. Specifically, if the measurement yields β€œ0”, the state collapses to $\ket{0}$; if it yields β€œ1”, the state collapses to $\ket{1}$. Since some quantum hardware may not preserve the post-measurement state due to physical constraints, this document treats the state as destroyed and unusable after measurement. ## Evaluating Expectation Values of Hermitian Operators The expectation value of a physical quantity represented by a Hermitian operator $H$ in state $\ket{\psi}$ is: $$ \braket{\psi|H|\psi} $$ Here $\bra{\psi}$ is defined as the adjoint (conjugate transpose) of the quantum state (complex column vector) $\ket{\psi}$. For example, in the single-qubit case, if $\ket{\psi} = (a,b)^T$ then $\bra{\psi} = (a^*, b^*)$. The same definition applies to $n$ qubits. In QAOA, evaluating the expectation value of the Pauli $Z$ operator is required. Here we explain how to evaluate this expectation value using quantum measurement. Given the quantum state $$ \ket{\psi} = \alpha\ket{0} + \beta\ket{1} $$ the expectation value of the Pauli $Z$ operator in state $\ket{\psi}$ can be computed using the computational basis matrix representation: $$ \braket{\psi|Z|\psi} = (\alpha^*, \beta^*) \begin{pmatrix} 1 & 0\\ 0 & -1 \end{pmatrix} \begin{pmatrix} \alpha\\ \beta \end{pmatrix} = |\alpha|^2 - |\beta|^2 $$ When the state $\ket{\psi}$ is unknown (i.e., the values of $\alpha$ and $\beta$ are unknown), the expectation value cannot be computed directly. However, by preparing sufficiently many copies of the unknown quantum state $\ket{\psi}$ and performing repeated measurements, the expectation value can be estimated approximately. Consider preparing $N$ copies of the quantum state $\ket{\psi}$ and measuring each one. Suppose this yields β€œ0” a total of $N_{\alpha}$ times and β€œ1” a total of $N_{\beta}$ times (where $N = N_{\alpha} + N_{\beta}$). For sufficiently large $N$: $$ |\alpha|^2 \approx \frac{N_{\alpha}}{N} \ ,\ |\beta|^2 \approx \frac{N_{\beta}}{N} $$ Using this approximation, the expectation value of the Pauli $Z$ operator can be estimated as: $$ \braket{\psi|Z|\psi} = |\alpha|^2 - |\beta|^2 \approx \frac{N_{\alpha} - N_{\beta}}{N} $$ Although we considered the single-qubit case here, the same approach applies to evaluating Pauli $Z$ operator expectation values for general $n$-qubit systems. > [!IMPORTANT] > > **Important** > > As mentioned in the [section on quantum measurement](#quantum-measurement), performing a quantum measurement destroys the state $\ket{\psi}$. Therefore, to perform $N$ measurements of $\ket{\psi}$, $N$ copies of $\ket{\psi}$ must be prepared. This value is called the **number of shots** or **number of samples**. > > Increasing the number of shots is expected to improve computational accuracy, but at the cost of increased computation time. Therefore, choosing an appropriate number of shots is essential in QAOA. ## QAOA Procedure QAOA solves optimization problems through the following steps: 1. Construct a Hamiltonian $H$ corresponding to the objective function from the given Ising function $\tilde f$. The minimum eigenvalue of $H$ corresponds to the minimum value of $\tilde f$. 2. To search for the minimum eigenvalue (and corresponding eigenstate) of $H$, construct a parametric quantum circuit (ansatz circuit) characterized by real parameters $\boldsymbol{\theta} = (\theta_1,\theta_2,\ldots,\theta_k)$. The quantum state corresponding to parameters $\boldsymbol{\theta}$ is written as $\ket{\psi(\boldsymbol{\theta})}$ and called the ansatz state. 3. Define the cost function as $C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})}$. 4. Alternate between evaluating $C(\boldsymbol{\theta})$ on the quantum computer and updating parameters $\boldsymbol{\theta}$ using a classical optimization algorithm until a convergence criterion is met. Each step is explained in detail below. ### 1. Hamiltonian Construction Assume the Ising function serving as the QAOA objective function is given as: $$ \tilde f(z) = \sum_{\alpha} \tilde{f}_{\alpha}(z) $$ The goal is to find the Ising variable sequence $z = (z_1,\ldots,z_n) \in \{-1,1\}^n$ that minimizes $\tilde f(z)$. To perform optimization on a quantum computer, this Ising function is transformed into a Hermitian operator (**Hamiltonian**) acting on qubits. Specifically, the Hamiltonian $H = \sum_{\alpha} H_{\alpha}$ corresponding to the objective function is defined by **replacing each Ising variable $z_i$ appearing in each monomial $\tilde f_\alpha(z)$ with the corresponding Pauli $Z$ operator $Z_i$**. Here are concrete examples: * When $\tilde f_{\alpha}(z) = 2z_1z_2$: $$ H_{\alpha} = 2 Z_1 Z_2 $$ * When $\tilde f_{\alpha}(z) = -3 z_3$: $$ H_{\alpha} = -3 Z_3 $$ * A constant term like $\tilde f_{\alpha}(z) = 5$ corresponds to a coefficient of the identity operator $I$: $$ H_{\alpha} = 5 I $$ Such constant terms only shift the entire spectrum by a fixed amount without changing the ground state, so they can often be ignored (though they are retained when absolute energy values are needed). Here $Z_i$ denotes β€œthe Pauli $Z$ operator acting on the $i$-th qubit.” In this document, tensor products $\otimes$ are omitted, writing $Z_1 \otimes Z_2$ as $Z_1 Z_2$. From the above, optimizing an Ising function $\tilde f$ with $n$ variables via QAOA requires a Hamiltonian $H$ defined on $n$ qubits. Consequently, a quantum computer with at least $n$ qubits is needed. ### 2. Ansatz State Preparation To solve the given problem, a parameterized quantum state (ansatz state) is defined. The ansatz state is **the state obtained by applying a parameterized quantum circuit to an initial state**. QAOA uses a specifically structured QAOA ansatz. The circuit that creates the QAOA ansatz is: ![../../_images/qaoa_circuit.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/qaoa_circuit.svg) #### Initial State In QAOA, the initial state is typically the $+$ state. The single-qubit $+$ state is defined as: $$ \ket{+} = \frac{\ket{0} + \ket{1}}{\sqrt{2}} $$ > [!TIP] > > **Hint** > > The $+$ state is obtained by applying the Hadamard gate > > > $$ > \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1 & 1 \\ > 1 & -1 > \end{pmatrix} > $$ > > > to the $0$ state $\ket{0}$. The QAOA initial state is $\ket{+}^{\otimes n}$, where all $n$ qubits are in the $+$ state. #### Definition of the QAOA Ansatz The QAOA ansatz is a quantum state characterized by a sequence of real parameters: $$ \boldsymbol{\theta} = (\boldsymbol{\beta},\boldsymbol{\gamma}) = (\beta_1,\ldots,\beta_p,\gamma_1,\ldots,\gamma_p) $$ Here $p$ is the β€œdepth” (number of layers) of QAOA. In this document, the entire set of parameters is denoted collectively as $\boldsymbol{\theta}$. The quantum circuit $U(\boldsymbol{\theta})$ generating the QAOA ansatz is defined as: $$ 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] $$ Here $H$ is the cost Hamiltonian defined above, and $X_k$ is the Pauli $X$ operator acting on the $k$-th qubit. The product $\prod_{j=1}^{p}$ is interpreted as **applying sequentially from the rightmost layer $j=1$ to the leftmost layer $j=p$**. In this document, $\gamma_j$ is the parameter associated with the cost Hamiltonian $H$, and $\beta_j$ is the parameter associated with $X$-mixing. Intuitively: * $\exp(-i \gamma_j H)$ evolves the state along the Pauli $Z$ direction (cost function), and * $\exp\left(-i \beta_j \sum_k X_k\right)$ mixes the state along the Pauli $X$ direction, enabling the representation of diverse quantum states. Thus, the QAOA ansatz state corresponding to parameters $\boldsymbol{\theta}$ is defined as: $$ \ket{\psi(\boldsymbol{\theta})} = U(\boldsymbol{\theta}) \ket{+}^{\otimes n} $$ ### 3. Cost Function Definition The cost function $C(\boldsymbol{\theta})$ is defined as the expectation value of the Hamiltonian $H$ in the ansatz state $\ket{\psi(\boldsymbol{\theta})}$: $$ C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})} $$ As [mentioned earlier](#hermitian-evaluation), in the computational basis representation, a quantum state $\ket{\psi}$ is a complex column vector and $\bra{\psi}$ is its adjoint. If the minimum eigenvalue of the Hamiltonian $H$ is $\lambda_{\min}$ with eigenvector $\ket{\psi_{\min}}$, then $C(\boldsymbol{\theta})$ attains its minimum value $\lambda_{\min}$ when $\ket{\psi(\boldsymbol{\theta})}$ coincides with $\ket{\psi_{\min}}$. QAOA operates under the premise that the $\ket{\psi(\boldsymbol{\theta})}$ minimizing $C(\boldsymbol{\theta})$ should be a good approximation to the ground state of $H$, and uses classical optimization to search for the parameters $\boldsymbol{\theta}$ that minimize $C(\boldsymbol{\theta})$. ### 4. Classical Optimization Parameter Update Cycle This is the core step of QAOA. Here, the following are repeated: * Evaluating the cost function $C(\boldsymbol{\theta})$ on the quantum computer * Updating the parameters $\boldsymbol{\theta}$ on the classical computer to find $\boldsymbol{\theta}^{\textup{opt}}$ that minimizes $C(\boldsymbol{\theta})$. #### Evaluating the Cost Function $C(\boldsymbol{\theta})$ Evaluating the cost function $C(\boldsymbol{\theta})$ is the quantum computer’s task. From its [construction method](#hamiltonian-construction), the Hamiltonian $H$ built from the objective function can be written as: $$ H = \sum_{\alpha} H_{\alpha} = \sum_{\alpha} c_{\alpha} Z_{\alpha} $$ Here, $c_{\alpha}$ is the coefficient of monomial $\tilde{f}_{\alpha}(z)$, and $Z_{\alpha}$ is the Pauli $Z$ operator corresponding to its variable part. Using this expression, the cost function $C(\boldsymbol{\theta})$ becomes: $$ 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})} $$ Each $\bra{\psi(\boldsymbol{\theta})} Z_{\alpha} \ket{\psi(\boldsymbol{\theta})}$ can be evaluated using the measurement results of $\ket{\psi(\boldsymbol{\theta})}$, as explained in the [section on expectation value evaluation](#hermitian-evaluation). Substituting each value into the equation above yields the cost function value $C(\boldsymbol{\theta})$. #### Updating Parameters $\boldsymbol{\theta}$ Based on the cost function value evaluated by the quantum computer, the classical computer updates the parameters $\boldsymbol{\theta}$ to find the optimal values. The parameter update cycle can be summarized as: 1. Execute the QAOA circuit $U(\boldsymbol{\theta})$ with given parameters $\boldsymbol{\theta}$, 2. Estimate the expectation value $C(\boldsymbol{\theta})$ of Hamiltonian $H$ for state $\ket{\psi(\boldsymbol{\theta})}$ through measurement, 3. Use a classical optimization algorithm (gradient methods, gradient-free optimization, Bayesian optimization, etc.) to determine the next $\boldsymbol{\theta}$, repeating these steps until a convergence criterion is satisfied. ## QAOA Summary Finally, let us summarize the typical steps of QAOA. ```mermaid flowchart TD S1["Step 1: Define Hamiltonian"] S2["Step 2: Construct ansatz circuit"] S3["Step 3: Define cost function"] S4["Step 4: Optimize parameters"] S5["Step 5: Extract solution"] S1 --> S2 --> S3 --> S4 S4 -->|"Not converged"| S4 S4 -->|"Converged"| S5 ``` **Step 1: Define Hamiltonian** Write the classical cost function to optimize as $f(z) = \sum_{\alpha} c_{\alpha} f_{\alpha}(z)$, where $z = (z_1,\ldots,z_n)$ is a sequence of Ising variables with $z_i \in \{-1,1\}$, $c_{\alpha}$ are real coefficients, and $f_{\alpha}$ are monomials. Replace each Ising variable $z_i$ in each monomial $f_{\alpha}(z)$ with the corresponding Pauli $Z$ operator $Z_i$, using the identity operator $I$ as needed, to construct the Hamiltonian $H = \sum_{\alpha} H_{\alpha}$ on the qubit space. The goal of QAOA is to approximately find the minimum eigenvalue/eigenvector of $H$, thereby obtaining the Ising variable sequence $z$ that minimizes $f(z)$. **Step 2: Prepare Ansatz State** To search for the minimum eigenvalue of Hamiltonian $H$ constructed above, build the QAOA ansatz circuit $U(\boldsymbol{\theta})$ characterized by real parameter sequence $\boldsymbol{\theta} = (\boldsymbol{\gamma},\boldsymbol{\beta})$. Define $\ket{\psi(\boldsymbol{\theta})} = U(\boldsymbol{\theta}) \ket{+}^{\otimes n}$ with initial state $\ket{+}^{\otimes n}$, and call $\ket{\psi(\boldsymbol{\theta})}$ the ansatz state. **Step 3: Define Cost Function** Define the cost function as $C(\boldsymbol{\theta}) = \bra{\psi(\boldsymbol{\theta})} H \ket{\psi(\boldsymbol{\theta})}$. $C(\boldsymbol{\theta})$ is the expectation value of Hamiltonian $H$ in the ansatz state $\ket{\psi(\boldsymbol{\theta})}$ corresponding to parameters $\boldsymbol{\theta}$. **Step 4: Update Parameters** Evaluate $C(\boldsymbol{\theta})$ on the quantum computer and update parameters $\boldsymbol{\theta}$ using a classical optimization algorithm based on the result. Repeat this β€œevaluation (quantum side)” and β€œupdate (classical side)” cycle until the prescribed convergence criterion is met. **Step 5: Extract Solution** Denote the parameters at convergence as $\boldsymbol{\theta}^{\textup{opt}}$. At this point, $C(\boldsymbol{\theta}^{\textup{opt}})$ and $\ket{\psi(\boldsymbol{\theta}^{\textup{opt}})}$ are expected to be good approximations to the minimum eigenvalue/eigenvector of Hamiltonian $H$. From the measurement results on the state $\ket{\psi(\boldsymbol{\theta}^{\textup{opt}})}$, compute the objective function $\tilde{f}(z)$ for each obtained Ising variable sequence $z$, and select the one minimizing $\tilde{f}(z)$ as the candidate solution. The most frequently observed Ising variable sequence $z^{\textup{opt}}$ is expected to yield the minimum (or near-minimum) value of $\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) --- # Constrained QAOA Algorithm Some optimization problems require finding the optimum subject to certain constraints on the variables. For example, consider minimizing the objective function ${f}(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ in Ising variables $z$, subject to the constraint β€œexactly 1 of $z_0$, $z_1$, $z_2$ takes the value $-1$.” Without any constraint, the function ${f}(z)$ attains its minimum value ${f}(z) = -5$ at $(z_0, z_1, z_2) = (-1, -1, 1)$. However, this solution violates the constraint. Under the constraint, the minimum is ${f}(z) = -3$ at $(z_0, z_1, z_2) = (1, -1, 1)$. While many types of variable constraints exist, the kind illustrated above is widely used. In the case of binary variables $\{0,1\}$, the constraint that exactly N variable equals $1$ is often called an N-HOT constraint. For more on N-HOT constraints, see [Wikipedia: One-hot](https://en.wikipedia.org/wiki/One-hot). > [!NOTE] > > **Note** > > Here, we also use the term N-HOT to refer to the constraint that exactly $n$ variables in a sequence of Ising variables take the value $-1$. > > Note that the [`one_hot()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) function in the Amplify SDK is implemented as `poly == 1`. Therefore, to define a one-hot constraint with Ising variables, you need to express it as an equality constraint using the [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) function. In the following, β€œconstraint” refers to this type of condition. When running QAOA, Amplify automatically detects optimization problems with N-HOT constraints and performs variable grouping according to the given constraints, reducing the search space for more efficient optimization. Automatic detection can also be disabled. For details, see [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype). ## N-HOT QAOA This section explains how variable grouping based on given constraints enables finding optimal solutions. When solving a constrained optimization problem with a solver that cannot handle constraints directly, a (relaxation) polynomial ${g}$ whose optimal solution satisfies the constraint is introduced along with a penalty coefficient $\lambda$, and the problem ${f}' = {f} + \lambda {g}$ is solved to obtain the constrained optimum. For example, to minimize the objective function ${f}(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ subject to the equality constraint β€œ$z_0 + z_1 + z_2 = 1$”, one can set ${g}(z) = (z_0+z_1+z_2 - 1)^2$ and choose an appropriate $\lambda$ to obtain the desired solution. For details, see [Penalty method](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md#penalty-definition). In contrast, N-HOT QAOA uses a constraint-aware ansatz, reducing the given optimization problem to β€œfinding the minimum eigenvalue and eigenvector of the Hamiltonian within the parameter space restricted by the constraints.” This approach is expected to be more efficient. Suppose the optimization problem has $k$ independent equality constraints (constraints whose variable sets do not overlap). Under these constraints, the variables $z$ are partitioned into $k+1$ groups: $z = (z^{(1)},z^{(2)},\ldots,z^{(k)},{z})$, where $z^{(1)}, \ldots, z^{(k)}$ are the groups corresponding to the independent equality constraints, and ${z}$ is the group of unconstrained variables. The ansatz is defined so that independent quantum circuits act on each group: $\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}})}$. For the unconstrained part $\ket{\psi_{\mathrm{ungroup}}(\boldsymbol{{\theta}})}$, independent Pauli $X$ rotation gates $R_X(\theta)=\mathrm{e}^{i\frac{\theta}{2} X}$ are applied. The circuit structure is outlined in the following diagram: ![grouping_ansatz](https://amplify.fixstars.com/en/docs/amplify/v1/_images/grouping_ansatz.drawio.svg) ### Group Ansatz Circuit For each group $i = 1,2,\ldots,k$, the ansatz circuit $U(\boldsymbol{\theta}^{(i)})$ is constructed as follows: ![grouping_ansatz_component](https://amplify.fixstars.com/en/docs/amplify/v1/_images/grouping_ansatz_component.drawio.en.svg) In the circuit diagram, the 2-qubit gate $A(\theta)$ is realized using a CNOT gate and a Pauli $Y$ rotation gate $R_Y(\theta) = \mathrm{e}^{-i\frac{\theta}{2} Y}$ as shown below: ![gateA](https://amplify.fixstars.com/en/docs/amplify/v1/_images/gateA.drawio.svg) The matrix representation of gate $A(\theta)$ is: $$ 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]](#id3) [[2]](#id4). Examining the action of $A(\theta)$ on the computational basis states, we obtain: $$ \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} $$ This shows that when the input is a computational basis state, the output preserves the number of β€œ1”s present in the input. ### Group Initial State For each group $i = 1,2,\ldots,k$, the initial state $\ket{\psi_{\mathrm{init}, i}}$ is set to β€œa quantum state with as many β€˜1’s as the number of $-1$s required by the constraint.” > [!NOTE] > > **Note** > > As noted in the [QAOA theory](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md), the single-qubit computational basis $\{\ket{0}, \ket{1}\}$ consists of eigenvectors of the Pauli $Z$ operator, and its eigenvalues correspond to Ising variables. Specifically: > > > $$ > \braket{0|Z|0} &= 1 \\ > \braket{1|Z|1} &= -1 > $$ > > > so $\ket{0}$ corresponds to $1$ and $\ket{1}$ corresponds to $-1$. > > Keeping in mind that the qubit label β€œ1” corresponds to the Ising value $-1$, the phrase β€œa quantum state with as many β€˜1’s as the number of $-1$s required by the constraint” can be interpreted as the quantum state obtained by embedding the constraint on the Ising variables into the qubits. Let us give a more mathematical description. Let $n_i$ be the number of qubits in group $i$, and $l_i$ be the number of $-1$s required by the constraint. Define the Hamming weight of a bit string $x^n \in \{0,1\}^n$ as $w(x^n)$ (the number of β€œ1”s in the string), and consider the subset of computational basis states $\{\ket{x^{n_i}}: w(x^{n_i}) = l_i\}$. This is the set of computational basis states containing exactly $l_i$ ones. β€œA quantum state with as many β€˜1’s as the number of $-1$s required by the constraint” refers to any superposition of elements from this subset, i.e., a state expressed using complex numbers $c_{x^{n_i}}$ satisfying $$ \sum_{x^{n_i}:w(x^{n_i}) = l_i} |c_{x^{n_i}}|^2 = 1 $$ as: $$ \sum_{x^{n_i}:w(x^{n_i}) = l_i} c_{x^{n_i}}\ket{x^{n_i}} $$ In Amplify, the initial state is set to: $$ \ket{\psi_{\mathrm{init}, i}} = \ket{\underbrace{1\dots1}_{l_i \text{ ones}}\underbrace{0\dots0}_{(n_i -l_i) \text{ zeros}}} $$ ### Why the Constraint is Preserved Given the construction of the ansatz circuit $U(\boldsymbol{\theta}^{(i)})$ and the initial state $\ket{\psi_{\mathrm{init}, i}}$, the state obtained by applying $U(\boldsymbol{\theta}^{(i)})$ to $\ket{\psi_{\mathrm{init}, i}}$ also takes the form: $$ 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}} $$ Let us verify with an example. In the following, we write the gate $A$ acting on qubits $i$ and $j$ as $A_{(i,j)}$. Consider applying gate $A(\theta_1)_{(1,2)}$ to the initial state $\ket{\psi_{\mathrm{init}}} = \ket{100}$. The result is: $$ A(\theta_1)_{(1,2)}\ket{\psi_{\mathrm{init}}} = \cos\theta_1\ket{010} - \sin\theta_1\ket{100} $$ Applying gate $A(\theta_2)_{(2,3)}$ to this state gives: $$ 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} $$ No matter how many times this operation is repeated, the output state always contains exactly one β€œ1” β€” that is, it always remains β€œa quantum state with as many β€˜1’s as the number of $-1$s required by the constraint.” As shown above, the state $U(\boldsymbol{\theta}^{(i)})\ket{\psi_{\mathrm{init}, i}}$ preserves the number of β€œ1”s in the initial state. By using this ansatz state, it becomes possible to find the optimal solution while maintaining the constraint. ### Example Here we examine the circuit construction of constrained QAOA using a simple example. Define the problem as $f(z) = 2 z_1 z_2 + z_0 + z_1 - z_2$ and consider: $$ \min_{z: z_0 + z_1 = 0} {f}(z) $$ For simplicity, we set the ansatz circuit depth (reps) to $1$. In this problem, variables $z_0$ and $z_1$ belong to the group constrained by $z_0 + z_1 = 0$, while $z_2$ is unconstrained. This constraint requires exactly one of $z_0$ and $z_1$ to be $-1$. Following the procedure described above, Amplify sets the initial state for $z_0$ and $z_1$ to $\ket{10}$ and the initial state for $z_2$ to $\ket{0}$, resulting in the following constrained QAOA circuit diagram: ![grouping_ansatz_example](https://amplify.fixstars.com/en/docs/amplify/v1/_images/grouping_ansatz_example.drawio.svg) Indeed, in the portion of the circuit involving $z_0$ and $z_1$, the number of β€œ1”s in the input state equals the number of β€œ1”s in the output state. As demonstrated above, the ansatz state $\ket{\psi(\boldsymbol{\theta})}$ introduced on this page is restricted to states satisfying the $k$ independent constraints, and is expected to find solutions more efficiently compared to the standard approach of relaxing constraints and searching. --- [[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 Algorithm Recursive QAOA [[1]](#id3) (hereafter RQAOA) is a method that repeatedly executes QAOA with shallow ansatz circuits, progressively reducing the problem size to identify the optimal solution. It aims to relax the circuit depth constraints that are problematic in standard QAOA, enabling its use on larger-scale problems. For a detailed explanation of standard QAOA theory, see [QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md). > [!NOTE] > > **Note** > > RQAOA does not support constrained problems. If constraints are present, the Amplify SDK automatically converts the problem to an unconstrained one by introducing penalty terms. For details, see [Constraints and penalty functions](https://amplify.fixstars.com/en/docs/amplify/v1/penalty.md). ## RQAOA Procedure RQAOA is executed through the following procedure: * Step 1: Variable reduction cycle using shallow-circuit QAOA * Procedure 1: Run QAOA with a shallow circuit * Procedure 2: Determine which variable to eliminate based on the QAOA results * Procedure 3: Reduce a variable and construct a new problem * Step 2: Find the optimal solution for the sufficiently reduced problem * Step 3: Derive the optimal solution for the original problem from the reduced problem’s solution ![../../_images/rqaoa_flowchart.drawio.en.svg](https://amplify.fixstars.com/en/docs/amplify/v1/_images/rqaoa_flowchart.drawio.en.svg) ## RQAOA in Detail Below, we examine the procedures performed at each step in more detail. To illustrate each step, we use the following simple example: minimizing the Ising function $$ f(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ ### Step 1. Variable Reduction Cycle This is the core step of RQAOA. The variable reduction cycle repeats the following procedures until the problem size (number of variables) is sufficiently small. 1. For the objective function ${f}(z)$ composed of Ising variables, run QAOA using a shallow ansatz state $\ket{\psi(\boldsymbol{\theta})}$ (e.g., with depth $p = 1$), and measure its final state $\ket{\psi}$ in the computational basis. 2. From the measurement results, compute the expectation value of each term in the objective function ${f}(z)$, and identify the term with the largest absolute expectation value. Based on the sign of that expectation value, define $\sigma = 1$ or $\sigma = -1$. 3. For the identified term, introduce the relation ${\rm term}_{\mathrm{max}}= \sigma$. Use this relation to eliminate a variable and define a new objective function ${f}_{\mathrm{new}}(z)$. Each procedure is explained in more detail below. #### 1. Running QAOA with a Shallow Circuit The first step in the RQAOA iteration uses QAOA with a shallow circuit to approximately solve the given optimization problem and obtain measurement results from the final state $\ket{\psi}$. The measurement results are only used to determine which variable to eliminate in subsequent steps, so **an exact optimal solution is not required**. This is why the use of shallow ansatz circuits is acceptable. #### 2. Determining Which Variable to Eliminate From the measurement results obtained in Procedure 1, the term in the objective function with the β€œmost certain value” is identified by computing the expectation value of each term. Consider the example $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ In this case, after converting the objective function to a Hamiltonian, the expectation values of the Pauli $Z$ operators corresponding to each term’s variable part are computed: $\braket{\psi|Z_0Z_1|\psi}$, $\braket{\psi|Z_1Z_2|\psi}$, $\braket{\psi| Z_0 |\psi}$, $\braket{\psi| Z_2 |\psi}$. For details on the conversion, see [QAOA Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/QAOA_algo.md). Let $Z_{\mathrm{max}}$ denote the Pauli operator with the largest absolute expectation value. The corresponding term is denoted ${\rm term}_{\mathrm{max}}$, and its value is fixed as ${\rm term}_{\mathrm{max}} = \sigma \in \{-1,1\}$: if $\langle \psi|Z_{\mathrm{max}}|\psi\rangle$ is positive, $\sigma = 1$; if negative, $\sigma = -1$. By definition, $-1 \leq \langle \psi|Z_{\mathrm{max}}|\psi\rangle \leq 1$. For the polynomial $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ suppose the expectation value computation yields: $$ \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} $$ In this case, $Z_{\mathrm{max}} = Z_1Z_2$, and ${\rm term}_{\mathrm{max}} = z_1z_2$. Since $\braket{\psi|Z_1Z_2|\psi} = -0.6 < 0$, we set $\sigma = -1$, giving the relation ${\rm term}_{\mathrm{max}} = \sigma$, i.e., $z_1z_2 = -1$. The meaning of this operation is as follows: the fact that $Z_{\mathrm{max}}$ has the largest absolute expectation value means that the corresponding variable term ${\rm term}_{\mathrm{max}}$ was closest to taking a definite value of $+1$ or $-1$. In other words, **if we must fix the value of exactly one term in the objective function, ${\rm term}_{\mathrm{max}}$ is the most plausible choice**. Based on the sign of the expectation value of $Z_{\mathrm{max}}$, the term’s value is fixed to ${\rm term}_{\mathrm{max}} = 1$ or ${\rm term}_{\mathrm{max}} = -1$, progressively reducing the problem size. #### 3. Variable Reduction Variable reduction is performed using the relation ${\rm term}_{\mathrm{max}} = \sigma$ introduced in Procedure 2. ##### When ${\rm term}_{\mathrm{max}}$ is Linear In this case, for some non-negative integer $i$, ${\rm term}_{\mathrm{max}} = z_i$, meaning β€œthe value of $z_i$ is most likely $\sigma$.” The variable is substituted as $z_i = \sigma$ in the original Hamiltonian $H$ to obtain a new objective function ${f}_{\mathrm{new}}$. ##### When ${\rm term}_{\mathrm{max}}$ is Quadratic or Higher Consider the example again: $$ {f}(z)= 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ Suppose, as established in Procedure 2, $z_1z_2 = -1$. This implies the relation $z_1 = -z_2$ between $z_1$ and $z_2$. Substituting $z_1 = -z_2$ into the original objective function ${f}(z)$ yields: $$ {f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3 $$ Note that for Ising variables $z \in \{-1,1\}$, $z^2 = 1$. As a result, a new objective function with one fewer variable is obtained. This example deals with a quadratic problem, but the same procedure applies when targeting higher-order terms for variable reduction. For the general case, see Appendix C of the [reference](https://arxiv.org/abs/1910.08980). After Procedures 1-3, if the new objective function ${f}_{\mathrm{new}}(z)$ has sufficiently few variables, the cycle exits. Otherwise, the reduction process returns to Procedure 1 using ${f}_{\mathrm{new}}(z)$. ### Step 2. Solving the Reduced Problem Once the problem size has been sufficiently reduced through repeated variable reduction cycles, the optimal solution is found by brute force. Let us continue the example. As shown in Step 1, starting from $$ {f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2 $$ the relation $z_1z_2 = -1$ led to the new objective function: $$ {f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3 $$ Brute-force evaluation yields the values minimizing ${f}_{\mathrm{new}}(z)$: $$ (z_0, z_2) = (-1,-1) $$ ### Step 3. Deriving the Original Problem’s Optimal Solution In the final step of RQAOA, the solution to the reduced problem from Step 2 is used to reconstruct the optimal solution for the original optimization problem ${f}(z)$. This is done by tracing back the variable reduction relations ${\rm term}_{\mathrm{max}} = \sigma$ obtained in Step 1, Procedure 3. In Step 2, the optimal solution $(z_0, z_2) = (-1,-1)$ for the reduced problem ${f}_{\mathrm{new}}(z) = -4z_0z_2 + 2z_0 + z_2 -3$ was obtained. In this step, the value of $z_1$ is derived using the relation: $$ z_1 = -z_2 $$ established during variable reduction. In this case: $$ z_1 = 1 $$ Thus, the optimal solution for the original optimization problem ${f}(z) = 4z_0z_1 +3z_1z_2 + 2z_0 + z_2$ is: $$ z = (z_0,z_1,z_2) = (-1,1,-1) $$ ## Summary As described above, RQAOA is a method that repeatedly leverages QAOA to progressively reduce the optimization problem size, ultimately computing the optimal solution. Since QAOA within the algorithm is used not to compute the optimal solution itself but merely to determine which variable to eliminate, shallower circuits can be expected to suffice compared to computing the optimal solution directly. In standard QAOA, solving large-scale problems requires deep circuits, which increases computation time. In addition, circuit size and hardware noise are known to hinder effective parameter updates in QAOA (the latter phenomenon has been studied under the name β€œBarren Plateau” [[2]](#id4)). RQAOA uses quantum computers only for shallow-circuit QAOA, and is therefore expected to avoid these issues while obtaining more accurate and efficient solutions to optimization problems. --- [[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](#id2)] 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 An extension library for performing **Black-Box Optimization (BBO)** using the features of the Amplify SDK. > [!TIP] > > **Tip** > > Black-box optimization is an optimization technique for finding optimal parameters for problems where the mathematical expression of the objective function is unknown or too complex. Amplify-BBOpt is effective for optimizing functions that cannot be expressed with the Amplify SDK, such as experiments and simulations. Specifically, it is used in the following use cases: **πŸ“ Structural Design & Topology Optimization** Optimizing building shapes and equipment placement to maximize HVAC performance, adjusting member placement and load conditions to minimize structural displacement, etc. **βš—οΈ Materials & Chemistry** Optimizing the composition of synthetic materials to maximize a performance metric, maximizing production in chemical plants, etc. **🌊 CAE & Simulation** Searching for stirring conditions to achieve more uniform substance concentration, optimizing shape parameters of fluidic devices, etc. **πŸ”¬ Experiments** Searching for conditions to achieve a desired experimental result, etc. Since you can use the Amplify SDK’s [solver clients](https://amplify.fixstars.com/en/docs/amplify/v1/clients.md), API tokens, and constraint helper functions as-is, you can leverage your usual Amplify SDK development experience when working on black-box optimization. ```python from amplify import AmplifyAEClient, less_equal from amplify_bbopt import KMTrainer, Optimizer, RealVariable, blackbox # Define the function to optimize @blackbox def func( x: float = RealVariable(bounds=(0, 2.5)), y: float = RealVariable(bounds=(1.0, 5.0)), ) -> float: ... # Configure the solver client client = AmplifyAEClient() client.token = "YOUR_TOKEN" # Set constraints constraints = less_equal(func.variables.x + func.variables.y, 5) # Run optimization optimizer = Optimizer( blackbox=func, trainer=KMTrainer(), client=client, constraints=constraints ) optimizer.add_random_training_data(num_data=5) optimizer.optimize(num_iterations=10) ``` For installation instructions and usage details, please refer to the link below. [**Go to Amplify-BBOpt Documentation**](https://amplify.fixstars.com/en/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/en/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/en/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/en/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/en/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/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient). * Change default degree reduction algorithm to [`Substitute`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadratizationMethod.md#amplify.QuadratizationMethod.Substitute) from [`IshikawaKZFD`](https://amplify.fixstars.com/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) and [`sum()`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) now correctly handles integer NumPy arrays. * Fix: [`FujitsuDA4Client`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) operation on an unassigned [`PolyArray`](https://amplify.fixstars.com/en/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/en/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/en/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/en/docs/amplify/v1/penalty.md#penalty-function-auto-generation) in constraint construction. * Change advanced parameters of [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve), [`parallel_solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.parallel_solve.md#amplify.parallel_solve), [`equal_to()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to), [`less_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), [`greater_equal()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.greater_equal.md#amplify.greater_equal) and [`clamp()`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) to [`Poly`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) can be used as a mapping key for [`substitute()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.substitute), [`substitute()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.substitute) and [`is_satisfied()`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient), [`LeapHybridSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) and [`LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model.get_variables) or [`variables`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.domain_wall.md#amplify.domain_wall) and [`array`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client). * Improve the efficiency of the [`Substitute`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/algebra.md) * [Algebraic classes and numerics](https://amplify.fixstars.com/en/docs/amplify/v1/reference/algebra.md#algebraic-classes-and-numerics) * [Constraint](https://amplify.fixstars.com/en/docs/amplify/v1/reference/constraint.md) * [Constraint classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/constraint.md#constraint-classes-and-functions) * [Model](https://amplify.fixstars.com/en/docs/amplify/v1/reference/model.md) * [Model classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/model.md#model-classes-and-functions) * [Graph Embedding](https://amplify.fixstars.com/en/docs/amplify/v1/reference/graph.md) * [Graph classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/graph.md#graph-classes-and-functions) * [Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/client.md) * [Client classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/client.md#client-classes-and-functions) * [Solve](https://amplify.fixstars.com/en/docs/amplify/v1/reference/solve.md) * [Solve classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/solve.md#solve-classes-and-functions) * [Misc.](https://amplify.fixstars.com/en/docs/amplify/v1/reference/misc.md) * [Function](https://amplify.fixstars.com/en/docs/amplify/v1/reference/misc.md#function) * [Attribute](https://amplify.fixstars.com/en/docs/amplify/v1/reference/misc.md#attribute) * [Quantum](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/index.md) * [Client](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/client.md) * [Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md) * [Minimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/minimize.md) * [Sampler](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/sampler.md) * [Circuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/circuit.md) * [Misc.](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/misc.md) * [Deprecated](https://amplify.fixstars.com/en/docs/amplify/v1/reference/deprecated.md) * [Deprecated classes and functions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/deprecated.md#deprecated-classes-and-functions) --- # Algebra ## Algebraic classes and numerics ### Class | | | | --- | --- | | [`amplify.Poly`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) | A NumPy-like multidimensional array of polynomials. | | [`amplify.Matrix`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) | Class for variable information. | | [`amplify.VariableGenerator`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) | Einstein summation for polynomial arrays and NumPy arrays. | | [`amplify.dot`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.newaxis.md#amplify.newaxis) | | ### Enum | | | | --- | --- | | [`amplify.VariableType`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) | Base class for PolyArray dimension types. | | [`amplify.Dim0`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim0.md#amplify.Dim0) | A 0D PolyArray. | | [`amplify.Dim1`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1) | A 1D PolyArray. | | [`amplify.Dim2`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim2.md#amplify.Dim2) | A 2D PolyArray. | | [`amplify.Dim3`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim3.md#amplify.Dim3) | A 3D PolyArray. | | [`amplify.Dim4`](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](#amplify.Poly.Iterator) **`__next__(self) β†’ tuple[tuple[Poly, ...], float]`** **Return type:** [*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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](#amplify.Poly) **`__imul__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](#amplify.Poly) **`__index__(self) β†’ int`** Cast a polynomial to an integer. Only valid for constant polynomials. **Return type:** [*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. **Return type:** [*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`. **Return type:** [*Poly*](#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](#amplify.Poly) **`__ipow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Poly*](#amplify.Poly) **`__isub__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*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)`. **Return type:** [*Iterator*](#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) β†’ Poly`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](#amplify.Poly) **`__len__(self) β†’ int`** Return the number of terms in the polynomial. **Return type:** [*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`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) β†’ Poly`** **Return type:** [*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`** **Return type:** [*Poly*](#amplify.Poly) **`__pow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*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`** **Return type:** [*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`** **Return type:** [*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}`. **Return type:** [*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. **Return type:** [*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) β†’ dict[tuple[int, ...], float]`** alias of [`as_dict()`](#amplify.Poly.as_dict) **Return type:** [*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. **Return type:** [*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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) β†’ bool`** Return `True` if the polynomial is a constant polynomial. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) β†’ bool`** Return `True` if the polynomial is quadratic. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) β†’ bool`** Return `True` if the polynomial represents a single variable. **Return type:** [*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. **Parameters:** **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/en/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. **Return type:** [*Poly*](#amplify.Poly) **`property id`** Variable ID. Only valid for polynomials that represent a single variable. **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **Return type:** [*VariableType*](https://amplify.fixstars.com/en/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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/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`** **Return type:** 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. **Return type:** [*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). **Return type:** [*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). **Parameters:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **Return type:** [*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. **Return type:** [*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] > > **Example** > > ```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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) β†’ None`** **Parameters:** **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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) β†’ PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **Return type:** [*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]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*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. **Return type:** [*Iterator*](#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) β†’ PolyArray[_Dim]`** **Parameters:** **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*) **Return type:** [*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. **Return type:** [*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. **Parameters:** **arg** ([*PolyArray*](#amplify.PolyArray) *| ndarray*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*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. **Return type:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) β†’ PolyArray[_Dim]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) β†’ Poly | PolyArray[__Dim]`** **Parameters:** **arg** (*NDArray |* [*PolyArray*](#amplify.PolyArray)*[__Dim]*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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. **Parameters:** * **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/en/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. **Raises:** * [**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`** **Return type:** [*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. **Returns:** Copy of the array. **Return type:** [*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. **Parameters:** **value** ([*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Flattened copy. **Return type:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) β†’ tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **Returns:** Tuple of index arrays, one for each dimension. **Return type:** [*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. **Returns:** Flattened view when possible. **Return type:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/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. **Parameters:** * **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`. **Returns:** Array with rolled elements. **Return type:** [*PolyArray*](#amplify.PolyArray)[_Dim] **Raises:** [**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. **Parameters:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Array after substitution. **Return type:** [*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. **Parameters:** * **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. **Returns:** Array with the two axes swapped. **Return type:** [*PolyArray*](#amplify.PolyArray)[_Dim] **Raises:** [**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. **Returns:** Converted NumPy array. **Return type:** [*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). **Returns:** Converted NumPy array. **Return type:** [*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. **Returns:** View of the same underlying data. **Return type:** [*PolyArray*](#amplify.PolyArray)[_Dim] **`property T`** A transposed view of the array. Equivalent to [`transpose()`](#amplify.PolyArray.transpose) with default axis order. **Return type:** [*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. **Return type:** [*PolyArray*](#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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/en/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/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) β†’ Model`** Create a [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) β†’ str`** Return a developer-friendly string representation of the matrix form. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** Return a human-readable string representation of the matrix form. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **Returns:** Polynomial converted from this matrix form. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property constant`** Constant term `c`. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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. **Returns:** Variable array used in this representation. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_variable) or [`variables`](https://amplify.fixstars.com/en/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`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__repr__(self) β†’ str`** Return a developer-friendly string representation of the variable. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** Return a human-readable string representation of the variable. **Return type:** [*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. **Return type:** [*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$. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. **Returns:** Corresponding value in [`VariableType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType). **Return type:** [*VariableType*](https://amplify.fixstars.com/en/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$. **Return type:** [*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). **Parameters:** * **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 `''`. **Returns:** Generated variable. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property variables`** List of all variables created. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray), this function is equivalent to the [`sum()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.sum) method of [`PolyArray`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) or [`Poly`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint), or [`ConstraintList`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) or the total number of elements in a [`ConstraintList`](https://amplify.fixstars.com/en/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`. **Parameters:** * **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/en/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`). **Returns:** Computed result for `subscripts`. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] **Raises:** [**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/en/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`** Bases: [`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`** Bases: [`Dim`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 0D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim1 **`class Dim1`** Bases: [`Dim`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 1D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim2 **`class Dim2`** Bases: [`Dim`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 2D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim3 **`class Dim3`** Bases: [`Dim`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim) A 3D PolyArray. **`__init__(*args, **kwargs)`** **`__new__(**kwargs)`** --- # Dim4 **`class Dim4`** Bases: [`Dim`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) | List-like container of [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) objects. | ### Functions | | | | --- | --- | | [`amplify.equal_to`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.equal_to.md#amplify.equal_to) | Create an equality constraint. | | [`amplify.one_hot`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.one_hot.md#amplify.one_hot) | Create a one-hot constraint. | | [`amplify.less_equal`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.clamp.md#amplify.clamp) | Create a range constraint. | | [`amplify.domain_wall`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList). **Parameters:** **arg** ([*Constraint*](#amplify.Constraint)) **Returns:** A new [`ConstraintList`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) containing both constraints. **Return type:** [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__imul__(self, arg: float, /) β†’ Constraint`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*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`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Constraint*](#amplify.Constraint) **`__mul__(self, arg: float, /) β†’ Constraint`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Constraint*](#amplify.Constraint) **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: int, /) β†’ Constraint`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Constraint*](#amplify.Constraint) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) β†’ Constraint`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Constraint*](#amplify.Constraint) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__truediv__(self, arg: float, /) β†’ Constraint`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*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. **Returns:** Left polynomial, operator literal, and right-hand side value(s). **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property penalty`** Penalty polynomial associated with this constraint. **Returns:** Penalty expression used for this constraint. **Return type:** [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) --- # ConstraintList **`class ConstraintList`** List-like container of [`Constraint`](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](#amplify.ConstraintList.Iterator) **`__next__(self) β†’ Constraint`** **Return type:** [*Constraint*](https://amplify.fixstars.com/en/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`** **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`__deepcopy__(self, memo: object | None = None) β†’ ConstraintList`** **Parameters:** **memo** ([*object*](https://docs.python.org/3/library/functions.html#object) *| None*) – Defaults to `None`. **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) β†’ Constraint`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Constraint*](https://amplify.fixstars.com/en/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`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*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`** **Return type:** [*Iterator*](#amplify.ConstraintList.Iterator) **`__itruediv__(self, arg: float, /) β†’ ConstraintList`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`__len__(self) β†’ int`** Number of constraints in the list. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__mul__(self, arg: float, /) β†’ ConstraintList`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmul__(self, arg: float, /) β†’ ConstraintList`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`__setitem__(self, key: int, value: Constraint) β†’ None`** **Parameters:** * **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) * **value** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__truediv__(self, arg: float, /) β†’ ConstraintList`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`append(self, value: Constraint) β†’ None`** Append a constraint to the end of the list. **Parameters:** **value** ([*Constraint*](https://amplify.fixstars.com/en/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. **Return type:** [*ConstraintList*](#amplify.ConstraintList) **`count(self, value: Constraint) β†’ int`** Return the number of occurrences of a constraint in the list. **Parameters:** **value** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) – Constraint to count. **Returns:** Number of occurrences. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`extend(self, sequence: Sequence[Constraint]) β†’ None`** Extend the list with constraints from a sequence. **Parameters:** **sequence** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Constraint*](https://amplify.fixstars.com/en/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. **Parameters:** * **index** ([*int*](https://docs.python.org/3/library/functions.html#int)) * **value** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint)) **`pop(self, index: int | None = None) β†’ Constraint`** Remove and return a constraint. **Parameters:** **index** ([*int*](https://docs.python.org/3/library/functions.html#int) *| None*) – Index to pop. If omitted, pop the last item. Defaults to `None`. **Returns:** Popped constraint. **Return type:** [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) **`remove(self, value: Constraint) β†’ None`** Remove the first matching constraint from the list. **Parameters:** **value** ([*Constraint*](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.less_equal.md#amplify.less_equal), `(lower, None)` to [`greater_equal()`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) if all axes are reduced, or a [`ConstraintList`](https://amplify.fixstars.com/en/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`** Bases: [`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/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) | Combinatorial optimization model containing objective and constraints. | ### Enum | | | | --- | --- | | [`amplify.IntegerEncodingMethod`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IntegerEncodingMethod.md#amplify.IntegerEncodingMethod) | Encoding method for integer variables during model conversion. | | [`amplify.RealEncodingMethod`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RealEncodingMethod.md#amplify.RealEncodingMethod) | Encoding method for real variables during model conversion. | | [`amplify.QuadratizationMethod`](https://amplify.fixstars.com/en/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`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **Return type:** [*Model*](#amplify.Model) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__iadd__(self, arg: Poly | Constraint | ConstraintList, /) β†’ Model`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **Return type:** [*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`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **Return type:** [*Model*](#amplify.Model) **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Poly | Constraint | ConstraintList, /) β†’ Model`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) **Return type:** [*Model*](#amplify.Model) **`__repr__(self) β†’ str`** Return a developer-friendly string representation of the model. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** Return a human-readable string representation of the model. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__sub__(self, arg: Poly, /) β†’ Model`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **Return type:** [*Model*](#amplify.Model) **`copy(self) β†’ Model`** Return a copy of the model. **Returns:** Copy of the model. **Return type:** [*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. **Parameters:** **with_penalty** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – Whether to include auxiliary variables introduced by penalty formulation. Defaults to `False`. **Returns:** Variables that appear in the model. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/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. **Parameters:** * **acceptable_degrees** ([*AcceptableDegrees*](https://amplify.fixstars.com/en/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`. **Returns:** Converted model and mapping information. **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](#amplify.Model), [*IntermediateMapping*](https://amplify.fixstars.com/en/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. **Returns:** Unconstrained objective polynomial. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property constraints`** Constraints held by the model. **Return type:** [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList) **`property objective`** Objective function held by the model. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*Matrix*](https://amplify.fixstars.com/en/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`. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # IntegerEncodingMethod **`class IntegerEncodingMethod`** Bases: [`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`** Bases: [`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`** Bases: [`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/en/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/en/docs/amplify/v1/reference/generated/amplify.embed.md#amplify.embed) | Perform graph embedding and return embedding information. | | [`amplify.to_edges`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) and `"Kings"` for [`HitachiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient). | **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property adjacency`** List of neighbor nodes for each node. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) and `"Kings"` for [`HitachiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient). **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) and a [`Graph`](https://amplify.fixstars.com/en/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. **Parameters:** * **poly** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) – Polynomial to embed. * **client_graph** ([*Graph*](https://amplify.fixstars.com/en/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`. **Returns:** Embedded polynomial, embedding chains, and graph representation of the input polynomial. **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/en/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. **Parameters:** **poly** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) – Polynomial to convert. **Returns:** Edges represented by node ID pairs. **Return type:** [*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`** Bases: [`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/en/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/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient) | | | [`amplify.FixstarsClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FixstarsClient.md#amplify.FixstarsClient) | | | [`amplify.DWaveSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.DWaveSamplerClient.md#amplify.DWaveSamplerClient) | | | [`amplify.LeapHybridSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridSamplerClient.md#amplify.LeapHybridSamplerClient) | | | [`amplify.LeapHybridCQMSamplerClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.LeapHybridCQMSamplerClient.md#amplify.LeapHybridCQMSamplerClient) | | | [`amplify.FujitsuDA4Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client) | | | [`amplify.FujitsuDA3cClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA3cClient.md#amplify.FujitsuDA3cClient) | | | [`amplify.ToshibaSQBM2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client) | | | [`amplify.GurobiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient) | | | [`amplify.NECVA2Client`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client) | | | [`amplify.HitachiClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.HitachiClient.md#amplify.HitachiClient) | | ### Class | | | | --- | --- | | [`amplify.AcceptableDegrees`](https://amplify.fixstars.com/en/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/en/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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`Feasible = 1`** **`Infeasible = 0`** **`Optimal = 2`** **`__nb_enum__ = `** **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__nb_enum__ = `** **`histogram = 0`** **`raw = 1`** **`class Parameters`** **`__init__(self) β†’ None`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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. **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property readout_thermalization`** The value in microseconds. Fractional values are preserved. **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property code`** Returns: int: **`property message`** Returns: str: **`property title`** Returns: str: **`class JobStatus`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** alias of [`Result`](#amplify.FujitsuDA4Client.Result) **`class QuboSolution`** **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*JobStatus*](#amplify.FujitsuDA4Client.JobStatus) **`delete_job_result(self, job_id: str) β†’ Result`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*Result*](#amplify.FujitsuDA4Client.Result) **`get_job_result(self, job_id: str) β†’ Result`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*Result*](#amplify.FujitsuDA4Client.Result) **`get_jobs(self) β†’ list[JobStatusInfo]`** **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*JobStatusInfo*](#amplify.FujitsuDA4Client.JobStatusInfo)] **`health_check(self) β†’ CommonError | None`** **Return type:** [*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`** Bases: [`FujitsuDA4Client`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property code`** Returns: int: **`property message`** Returns: str: **`property title`** Returns: str: **`class JobStatus`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** alias of [`Result`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) **`class QuboSolution`** **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*JobStatus*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatus) **`delete_job_result(self, job_id: str) β†’ Result`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) **`get_job_result(self, job_id: str) β†’ Result`** **Parameters:** **job_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **Return type:** [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) **`get_jobs(self) β†’ list[JobStatusInfo]`** **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*JobStatusInfo*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.JobStatusInfo)] **`health_check(self) β†’ CommonError | None`** **Return type:** [*CommonError*](https://amplify.fixstars.com/en/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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Solution`](#amplify.ToshibaSQBM2Client.Solution) **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`health_check(self) β†’ bool`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** **library_path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** Bases: [`BaseClient`](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Parameters:** * **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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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. **Parameters:** * **objective** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*[*[*VariableType*](https://amplify.fixstars.com/en/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/en/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/en/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. **Return type:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] **`property inequality_constraints`** Acceptable degrees for inequality constraints. **Return type:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] **`property objective`** Acceptable degrees for objective terms. **Return type:** [*dict*](https://docs.python.org/3/library/stdtypes.html#dict)[[*VariableType*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.VariableType.md#amplify.VariableType), [*Degree*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Degree.md#amplify.Degree)] --- # Degree **`class Degree`** Bases: [`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/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | Container of optimization solutions and conversion/runtime metadata. | | [`amplify.Values`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve) | Solve a combinatorial optimization problem. | | [`amplify.parallel_solve`](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](#amplify.Result.GraphConversion.ChainBreakFractions.Iterator) **`__next__(self) β†’ float`** **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__bool__(self) β†’ bool`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) β†’ float`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ Iterator`** **Return type:** [*Iterator*](#amplify.Result.GraphConversion.ChainBreakFractions.Iterator) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property chain_break_fractions`** Chain break fraction for each solve. **Return type:** [*ChainBreakFractions*](#amplify.Result.GraphConversion.ChainBreakFractions) **`property chains`** Embedding chains for each logical variable. **Return type:** [*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. **Return type:** [*Graph*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Graph.md#amplify.Graph) **`property num_variables`** Number of physical variables used after embedding. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property poly`** Embedded polynomial. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`property src_graph`** Source (input polynomial) graph for embedding. **Return type:** [*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. **Return type:** [*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`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ ItemsView`** **Return type:** [*ItemsView*](#amplify.Result.ModelConversion.IntermediateMapping.ItemsView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ tuple[Poly, Poly]`** **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly), [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)] **`class KeysView`** View of keys in [`IntermediateMapping`](#amplify.Result.ModelConversion.IntermediateMapping). **`__bool__(self) β†’ bool`** **Return type:** [*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`** **Return type:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ Poly`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`class ValuesView`** View of values in [`IntermediateMapping`](#amplify.Result.ModelConversion.IntermediateMapping). **`__bool__(self) β†’ bool`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ ValuesView`** **Return type:** [*ValuesView*](#amplify.Result.ModelConversion.IntermediateMapping.ValuesView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ Poly`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__bool__(self) β†’ bool`** **Return type:** [*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`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ KeysView`** **Return type:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`items(self) β†’ ItemsView`** **Return type:** [*ItemsView*](#amplify.Result.ModelConversion.IntermediateMapping.ItemsView) **`keys(self) β†’ KeysView`** **Return type:** [*KeysView*](#amplify.Result.ModelConversion.IntermediateMapping.KeysView) **`values(self) β†’ ValuesView`** **Return type:** [*ValuesView*](#amplify.Result.ModelConversion.IntermediateMapping.ValuesView) **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property mapping`** Mapping from input variables to intermediate expressions. **Return type:** [*IntermediateMapping*](#amplify.Result.ModelConversion.IntermediateMapping) **`property model`** Intermediate model. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`property num_variables`** Number of variables in the intermediate model. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`property values_list`** Intermediate variable assignments for each solve. **Return type:** [*ValuesList*](#amplify.Result.ValuesList) **`class Solution`** Single solution entry in [`Result`](#amplify.Result). **`__init__(*args, **kwargs)`** **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property feasible`** Whether all constraints are satisfied. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`property objective`** Objective function value. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`property time`** Time at which the solver found this solution. **Return type:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property values`** Variable assignments of the solution. **Return type:** [*Values*](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__next__(self) β†’ Solution`** **Return type:** [*Solution*](#amplify.Result.Solution) **`__bool__(self) β†’ bool`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) β†’ Solution`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Solution*](#amplify.Result.Solution) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ Iterator`** **Return type:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) β†’ Result`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Result*](#amplify.Result) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ SplitView`** **Return type:** [*SplitView*](#amplify.Result.SplitView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ Result`** **Return type:** [*Result*](#amplify.Result) **`class ValuesList`** List-like view of value mappings for solutions. **`class Iterator`** **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ Iterator`** **Return type:** [*Iterator*](#amplify.Result.ValuesList.Iterator) **`__next__(self) β†’ Values`** **Return type:** [*Values*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) **`__bool__(self) β†’ bool`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__getitem__(self, key: int) β†’ Values`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Values*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Values.md#amplify.Values) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ Iterator`** **Return type:** [*Iterator*](#amplify.Result.ValuesList.Iterator) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__getitem__(self, key: int) β†’ Solution`** **Parameters:** **key** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Solution*](#amplify.Result.Solution) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ Iterator`** **Return type:** [*Iterator*](#amplify.Result.SolutionList.Iterator) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*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. **Return type:** [*Solution*](#amplify.Result.Solution) **`property client_result`** Solver/client result. **Return type:** [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AmplifyAEClient.md#amplify.AmplifyAEClient.Result) | [*Result*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.FujitsuDA4Client.md#amplify.FujitsuDA4Client.Result) | [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ToshibaSQBM2Client.md#amplify.ToshibaSQBM2Client.Result) | [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.GurobiClient.md#amplify.GurobiClient.Result) | [*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NECVA2Client.md#amplify.NECVA2Client.Result) | amplify.DASClient.Result | [*Result*](https://amplify.fixstars.com/en/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. **Return type:** [*GraphConversion*](#amplify.Result.GraphConversion) | *None* **`property execution_time`** The time the solver used to solve the problem. **Return type:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property filter_solution`** Whether to filter out infeasible solutions. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`property intermediate`** Model conversion information. **Return type:** [*ModelConversion*](#amplify.Result.ModelConversion) **`property num_solves`** Number of solve executions aggregated. **Return type:** [*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. **Return type:** [*timedelta*](https://docs.python.org/3/library/datetime.html#datetime.timedelta) **`property solutions`** View of all solutions. **Return type:** [*SolutionList*](#amplify.Result.SolutionList) **`property split`** Split view for each independent solve. **Return type:** [*SplitView*](#amplify.Result.SplitView) **`property total_time`** Total time including conversion and solve. **Return type:** [*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`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ ItemsView`** **Return type:** [*ItemsView*](#amplify.Values.ItemsView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ tuple[Poly, float]`** **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Poly*](https://amplify.fixstars.com/en/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`** **Return type:** [*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`** **Return type:** [*KeysView*](#amplify.Values.KeysView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ Poly`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`class ValuesView`** View of values in [`Values`](#amplify.Values). **`__bool__(self) β†’ bool`** **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ ValuesView`** **Return type:** [*ValuesView*](#amplify.Values.ValuesView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__next__(self) β†’ float`** **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__bool__(self) β†’ bool`** **Return type:** [*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`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)) **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__init__(*args, **kwargs)`** **`__iter__(self) β†’ KeysView`** **Return type:** [*KeysView*](#amplify.Values.KeysView) **`__len__(self) β†’ int`** **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__repr__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`items(self) β†’ ItemsView`** **Return type:** [*ItemsView*](#amplify.Values.ItemsView) **`keys(self) β†’ KeysView`** **Return type:** [*KeysView*](#amplify.Values.KeysView) **`values(self) β†’ ValuesView`** **Return type:** [*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/en/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/en/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. **Parameters:** * **model** ([*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)*[*[*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) *|* [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) *|* [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)*] |* [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) *|* [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix) *|* [*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Problems to solve. * **client** ([*BaseClient*](https://amplify.fixstars.com/en/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/en/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/en/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`. **Returns:** Results for each job. An entry can be `None` if all solves in that job failed. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Result*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Result.md#amplify.Result) | *None*] --- # Misc. ## Function | | | | --- | --- | | [`amplify.set_num_threads`](https://amplify.fixstars.com/en/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/en/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/en/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/en/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/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.einsum.md#amplify.einsum) and graph embedding when [`Minor`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.EmbeddingMethod.md#amplify.EmbeddingMethod.Minor) is used. In parallel solving with [`parallel_solve()`](https://amplify.fixstars.com/en/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. **Parameters:** **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. **Parameters:** * **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`. **Returns:** Loaded model and its associated variable generator. **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [*VariableGenerator*](https://amplify.fixstars.com/en/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. **Parameters:** * **model** ([*Model*](https://amplify.fixstars.com/en/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. **Parameters:** * **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`. **Returns:** Loaded model and its associated variable generator. **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[[*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model), [*VariableGenerator*](https://amplify.fixstars.com/en/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. **Parameters:** * **model** ([*Model*](https://amplify.fixstars.com/en/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. **Parameters:** **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/en/docs/amplify/v1/reference/quantum/client.md) * [QuantumBaseClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md) * [AerClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerClient.md) * [AQTClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AQTClient.md) * [BraketSimulatorClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md) * [IBMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md) * [IonQClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md) * [IQMClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IQMClient.md) * [QulacsClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md) * [RigettiClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RigettiClient.md) * [QUDORAClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md) * [OqtopusClient](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md) * [Algorithm](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md) * [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md#module-amplify) * [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md#rqaoa) * [Common](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/algorithm.md#common) * [Minimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/minimize.md) * [ScipyMinimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md) * [ScipyMinimizeOptions](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeOptions.md) * [ScipyMinimizeResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md) * [NoOpMinimize](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md) * [NoOpMinimizeResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md) * [MinimizeProtocol](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeProtocol.md) * [MinimizeResult](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md) * [Sampler](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/sampler.md) * [SamplerProtocol](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md) * [SamplingDurations](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md) * [AerDeviceType](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md) * [QiskitJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md) * [QulacsJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md) * [BraketJobMeta](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md) * [Circuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/circuit.md) * [QiskitCircuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md) * [QulacsCircuit](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsCircuit.md) * [Misc.](https://amplify.fixstars.com/en/docs/amplify/v1/reference/quantum/misc.md) * [IsingSeqFreqList](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md) --- # Client | | | | --- | --- | | [`QuantumBaseClient`](https://amplify.fixstars.com/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.BraketSimulatorClient.md#amplify.BraketSimulatorClient) | Client that executes quantum circuits on Amazon Braket simulators. | | [`IBMClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IBMClient.md#amplify.IBMClient) | Client that executes quantum circuits on IBM Quantum hardware. | | [`IonQClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IonQClient.md#amplify.IonQClient) | Client that executes quantum circuits on IonQ hardware. | | [`IQMClient`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) | Client that executes quantum circuits using the Qulacs simulator. | | [`RigettiClient`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.QUDORAClient.md#amplify.QUDORAClient) | Client that executes quantum circuits on QUDORA hardware. | | [`OqtopusClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.OqtopusClient.md#amplify.OqtopusClient) | Client that executes quantum circuits on OQTOPUS Cloud. | --- # QuantumBaseClient **`class QuantumBaseClient`** Bases: `_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/en/docs/amplify/v1/reference/generated/amplify.QulacsClient.md#amplify.QulacsClient) or [`IBMClient`](https://amplify.fixstars.com/en/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. **Parameters:** **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/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). --- # AerClient **`class AerClient`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QiskitJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** `**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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QiskitJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** CustomClientResultProtocol | *None* **`version() β†’ str`** Return the IBM Quantum backend version. **Raises:** [**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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta) | `IonQJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`QulacsJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta), [`QulacsCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** **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/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.solve.md#amplify.solve). --- # RigettiClient **`class RigettiClient`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta), [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, `_QudoraJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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`** Bases: [`QuantumBaseClient`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuantumBaseClient.md#amplify.QuantumBaseClient)[`AlgoType`, `OqtopusJobMeta`, [`QiskitCircuit`](https://amplify.fixstars.com/en/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/en/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. **Parameters:** * **algo** ([*type*](https://docs.python.org/3/library/functions.html#type)*[AlgoType]*) – The algorithm class to use (e.g., [`QAOA`](https://amplify.fixstars.com/en/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. **Parameters:** * **objective** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*Matrix*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Matrix.md#amplify.Matrix)) – The objective function to minimize. * **constraints** ([*ConstraintList*](https://amplify.fixstars.com/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) this is [`QAOA.Parameters`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters). Modify this to configure the algorithm before calling [`solve()`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA) | Quantum Approximate Optimization Algorithm (QAOA). | | [`QAOAType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) | Selects the QAOA circuit construction strategy. | | [`QAOAResult`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAResult.md#amplify.QAOAResult) | Raw result produced by a single QAOA run. | | [`QAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOADurations.md#amplify.QAOADurations) | Total timing breakdown for a QAOA run. | | [`QAOAHistoryItem`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.RQAOA.md#amplify.RQAOA) | Recursive Quantum Approximate Optimization Algorithm (RQAOA). | | [`RQAOAType`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.RQAOAResult.md#amplify.RQAOAResult) | Raw result produced by a single RQAOA run. | | [`RQAOADurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOADurations.md#amplify.RQAOADurations) | Total timing breakdown for an RQAOA run. | | [`RQAOAHistoryItem`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAHistoryItem.md#amplify.RQAOAHistoryItem) | Record of a single iteration during RQAOA optimization. | | [`NormalElimination`](https://amplify.fixstars.com/en/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/en/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/en/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/en/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/en/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/en/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`** Bases: [`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** ([*Parameters*](#amplify.QAOA.Parameters)) – QAOA configuration from which the [`qaoa_type`](#amplify.QAOA.Parameters.qaoa_type) is read. **Returns:** The degree constraints for the objective polynomial, determined by the chosen [`QAOAType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QAOAType.md#amplify.QAOAType) or custom implementation tuple. **Return type:** [*AcceptableDegrees*](https://amplify.fixstars.com/en/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. **Parameters:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/en/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/en/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`. **Returns:** The QAOA result, or `None` if *dry_run* is `True`. **Return type:** [*Result*](#amplify.QAOA.Result)[SamplingMeta_co] | *None* --- # QAOAType **`class QAOAType`** Bases: [`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/en/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`** Bases: [`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/en/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`** Bases: [`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/en/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/en/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/en/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`** Bases: [`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** ([*Parameters*](#amplify.RQAOA.Parameters)) – RQAOA configuration from which the [`qaoa_type`](#amplify.RQAOA.Parameters.qaoa_type) is read. **Returns:** The degree constraints for the objective polynomial, determined by the chosen [`RQAOAType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.RQAOAType.md#amplify.RQAOAType) or custom implementation tuple. **Return type:** [*AcceptableDegrees*](https://amplify.fixstars.com/en/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. **Parameters:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/en/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/en/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`. **Returns:** The RQAOA result, or `None` if *dry_run* is `True`. **Return type:** [*Result*](#amplify.RQAOA.Result)[SamplingMeta_co] | *None* --- # RQAOAType **`class RQAOAType`** Bases: [`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/en/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`** Bases: [`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/en/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`** Bases: [`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`** Bases: [`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/en/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. **Parameters:** * **sampler** ([*SamplerProtocol*](https://amplify.fixstars.com/en/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/en/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/en/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`. **Returns:** The algorithm result, or `None` if *dry_run* is `True`. **Return type:** 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/en/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/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimizeResult.md#amplify.ScipyMinimizeResult) | Result of a [`ScipyMinimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ScipyMinimize.md#amplify.ScipyMinimize) optimization run. | | [`NoOpMinimize`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md#amplify.NoOpMinimizeResult) | Result of a [`NoOpMinimize`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimize.md#amplify.NoOpMinimize) run. | | [`MinimizeProtocol`](https://amplify.fixstars.com/en/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/en/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/en/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. **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)) – 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`. **Returns:** The optimization result, or `None` if *dry_run* is `True`. **Return type:** [*ScipyMinimizeResult*](https://amplify.fixstars.com/en/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. **Parameters:** * **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/en/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`** Bases: `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/en/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/en/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. **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`. **Returns:** The evaluation result, or `None` if *dry_run* is `True`. **Return type:** [*NoOpMinimizeResult*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.NoOpMinimizeResult.md#amplify.NoOpMinimizeResult) | *None* **Raises:** [**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:** **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/en/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`** Bases: [`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/en/docs/amplify/v1/reference/generated/amplify.QAOA.md#amplify.QAOA.Parameters.minimize) to replace the default [`ScipyMinimize`](https://amplify.fixstars.com/en/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. **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)) – 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`. **Returns:** The optimization result, or `None` if *dry_run* is `True`. **Return type:** [*MinimizeResult*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.MinimizeResult.md#amplify.MinimizeResult) | *None* **`__init__(*args, **kwargs)`** --- # MinimizeResult **`class MinimizeResult`** Bases: [`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/en/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/en/docs/amplify/v1/reference/generated/amplify.SamplerProtocol.md#amplify.SamplerProtocol) | Protocol for quantum circuit samplers. | | [`SamplingDurations`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SamplingDurations.md#amplify.SamplingDurations) | Timing breakdown for a single quantum circuit sampling call. | | [`AerDeviceType`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.AerDeviceType.md#amplify.AerDeviceType) | alias of [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)['CPU', 'GPU', 'Thrust'] | | [`QiskitJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QiskitJobMeta.md#amplify.QiskitJobMeta) | Metadata for a single Qiskit quantum job. | | [`QulacsJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QulacsJobMeta.md#amplify.QulacsJobMeta) | Metadata for a single Qulacs simulation run. | | [`BraketJobMeta`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BraketJobMeta.md#amplify.BraketJobMeta) | Metadata for a single Braket quantum job. | --- # SamplerProtocol **`class SamplerProtocol`** Bases: [`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. **Parameters:** * **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. **Returns:** 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. **Return type:** [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple)[IsingSeqFreqList, [*SamplingDurations*](https://amplify.fixstars.com/en/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/en/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`** alias of [`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/en/docs/amplify/v1/reference/generated/amplify.QiskitCircuit.md#amplify.QiskitCircuit) | Qiskit-based quantum circuit implementation. | | [`QulacsCircuit`](https://amplify.fixstars.com/en/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). **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** 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). **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`static construct_observable( num_qubits: int, ) β†’ SparsePauliOp`** Return a zero-initialized `SparsePauliOp`. **Parameters:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Number of qubits in the observable. **Returns:** Zero operator over *num_qubits* qubits. **Return type:** SparsePauliOp **`get_raw() β†’ SparsePauliOp`** Return the underlying [`SparsePauliOp`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.quantum_info.SparsePauliOp). **`T_circuit`** alias of [`QuantumCircuit`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit) **`T_obs`** alias of [`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*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_h_gate(i: int) β†’ Self`** Apply a Hadamard gate to qubit *i*. **Parameters:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Target qubit index. **Returns:** This instance, for chaining. **Return type:** 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. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_rx_gate(i: int, value: float) β†’ Self`** Apply an Rx rotation gate to qubit *i*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_ry_gate(i: int, value: float) β†’ Self`** Apply an Ry rotation gate to qubit *i*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_x_gate(i: int) β†’ Self`** Apply a Pauli-X gate to qubit *i*. **Parameters:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Target qubit index. **Returns:** This instance, for chaining. **Return type:** Self **`static construct_quantum_circuit(num_qubits: int) β†’ QuantumCircuit`** Create a new `QuantumCircuit` with *num_qubits* qubits. **Parameters:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Number of qubits. **Returns:** An empty circuit with a single quantum register. **Return type:** 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). **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** 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). **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`static construct_observable(num_qubits: int) β†’ Observable`** Return an empty `Observable` over *num_qubits* qubits. **Parameters:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Number of qubits in the observable. **Returns:** An empty Qulacs `Observable` over *num_qubits* qubits. **Return type:** Observable **`get_raw() β†’ Observable`** Return the underlying Qulacs `Observable`. **`T_circuit`** alias of `QuantumCircuit` **`T_obs`** alias of `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*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_h_gate(i: int) β†’ Self`** Apply a Hadamard gate to qubit *i*. **Parameters:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Target qubit index. **Returns:** This instance, for chaining. **Return type:** 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)`. **Parameters:** * **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). **Returns:** This instance, for chaining. **Return type:** Self **`add_rx_gate(i: int, value: float) β†’ Self`** Apply an Rx rotation gate to qubit *i*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_ry_gate(i: int, value: float) β†’ Self`** Apply an Ry rotation gate to qubit *i*. **Parameters:** * **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. **Returns:** This instance, for chaining. **Return type:** Self **`add_x_gate(i: int) β†’ Self`** Apply a Pauli-X gate to qubit *i*. **Parameters:** **i** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Target qubit index. **Returns:** This instance, for chaining. **Return type:** Self **`static construct_quantum_circuit(num_qubits: int) β†’ QuantumCircuit`** Create a new Qulacs `QuantumCircuit` with *num_qubits* qubits. **Parameters:** **num_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Number of qubits. **Returns:** An empty Qulacs `QuantumCircuit` over *num_qubits* qubits. **Return type:** 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/en/docs/amplify/v1/reference/generated/amplify.IsingSeqFreqList.md#amplify.IsingSeqFreqList) | alias of [`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`** alias of [`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/en/docs/amplify/v1/reference/generated/amplify.BinaryPoly.md#amplify.BinaryPoly) | alias of [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | | [`amplify.IsingPoly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPoly.md#amplify.IsingPoly) | alias of [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | | [`amplify.BinaryPolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryPolyArray.md#amplify.BinaryPolyArray) | | | [`amplify.IsingPolyArray`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingPolyArray.md#amplify.IsingPolyArray) | | | [`amplify.BinarySymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinarySymbolGenerator.md#amplify.BinarySymbolGenerator) | | | [`amplify.IsingSymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | | | [`amplify.IsingSymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingSymbolGenerator.md#amplify.IsingSymbolGenerator) | | | [`amplify.BinaryMatrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryMatrix.md#amplify.BinaryMatrix) | | | [`amplify.IsingMatrix`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingMatrix.md#amplify.IsingMatrix) | | | [`amplify.QuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.QuadraticModel.md#amplify.QuadraticModel) | | | [`amplify.BinaryQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.BinaryQuadraticModel.md#amplify.BinaryQuadraticModel) | | | [`amplify.IsingQuadraticModel`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.IsingQuadraticModel.md#amplify.IsingQuadraticModel) | | | [`amplify.Solver`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Solver.md#amplify.Solver) | | | [`amplify.SolverResult`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverResult.md#amplify.SolverResult) | | | [`amplify.SolverSolution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SolverSolution.md#amplify.SolverSolution) | | ### Function | | | | --- | --- | | [`amplify.SymbolGenerator`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.SymbolGenerator.md#amplify.SymbolGenerator) | | | [`amplify.sum_poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.sum_poly.md#amplify.sum_poly) | | | [`amplify.decode_solution`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.decode_solution.md#amplify.decode_solution) | | | [`amplify.constraint.penalty`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.constraint.penalty.md#amplify.constraint.penalty) | alias of constructor of [`Constraint`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) | ### Enum | | | | --- | --- | | [`amplify.InequalityFormulation`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.InequalityFormulation.md#amplify.InequalityFormulation) | An enumeration. | --- # BinaryPoly **`class BinaryPoly`** Bases: [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) alias of [`Poly`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) | | [`decode`](#amplify.BinaryPoly.decode) | Equivalent to [`evaluate()`](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__next__(self) β†’ tuple[tuple[Poly, ...], float]`** **Return type:** [*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/en/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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__imul__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__index__(self) β†’ int`** Cast a polynomial to an integer. Only valid for constant polynomials. **Return type:** [*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. **Return type:** [*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`. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ipow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__isub__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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)`. **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) β†’ Poly`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__len__(self) β†’ int`** Return the number of terms in the polynomial. **Return type:** [*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`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) β†’ Poly`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__pow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`** **Return type:** [*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`** **Return type:** [*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}`. **Return type:** [*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. **Return type:** [*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) β†’ dict[tuple[int, ...], float]`** alias of [`as_dict()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) **Return type:** [*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/en/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. **Return type:** [*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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) β†’ bool`** Return `True` if the polynomial is a constant polynomial. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) β†’ bool`** Return `True` if the polynomial is quadratic. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) β†’ bool`** Return `True` if the polynomial represents a single variable. **Return type:** [*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. **Parameters:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **Return type:** [*VariableType*](https://amplify.fixstars.com/en/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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # IsingPoly **`class IsingPoly`** Bases: [`Poly`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) alias of [`Poly`](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) | | [`decode`](#amplify.IsingPoly.decode) | Equivalent to [`evaluate()`](https://amplify.fixstars.com/en/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`** **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__next__(self) β†’ tuple[tuple[Poly, ...], float]`** **Return type:** [*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/en/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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) **`__iadd__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__iand__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__imul__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__index__(self) β†’ int`** Cast a polynomial to an integer. Only valid for constant polynomials. **Return type:** [*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. **Return type:** [*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`. **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ior__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ipow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__isub__(self, arg: Poly | float, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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)`. **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.Iterator) **`__itruediv__(self, arg: float, /) β†’ Poly`** **Parameters:** **arg** ([*float*](https://docs.python.org/3/library/functions.html#float)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__ixor__(self, arg: Poly | bool, /) β†’ Poly`** **Parameters:** **arg** ([*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) *|* [*bool*](https://docs.python.org/3/library/functions.html#bool)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__len__(self) β†’ int`** Return the number of terms in the polynomial. **Return type:** [*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`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__neg__(self) β†’ Poly`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`** **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) **`__pow__(self, arg: int, /) β†’ Poly`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`** **Return type:** [*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`** **Return type:** [*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}`. **Return type:** [*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. **Return type:** [*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable) **`asdict(self) β†’ dict[tuple[int, ...], float]`** alias of [`as_dict()`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly.as_dict) **Return type:** [*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/en/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. **Return type:** [*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. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_number(self) β†’ bool`** Return `True` if the polynomial is a constant polynomial. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_quadratic(self) β†’ bool`** Return `True` if the polynomial is quadratic. **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`is_variable(self) β†’ bool`** Return `True` if the polynomial represents a single variable. **Return type:** [*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. **Parameters:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*Poly*](https://amplify.fixstars.com/en/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. **Return type:** [*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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property name`** Variable name. Only valid for polynomials that represent a single variable. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`property type`** Variable type. Only valid for polynomials that represent a single variable. **Return type:** [*VariableType*](https://amplify.fixstars.com/en/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. **Return type:** [*float*](https://docs.python.org/3/library/functions.html#float) | *None* **`property variables`** List of all variables in the polynomial. **Return type:** [*list*](https://docs.python.org/3/library/stdtypes.html#list)[[*Variable*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)] --- # BinaryPolyArray **`class BinaryPolyArray`** Bases: [`PolyArray`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). | | [`tonumpy`](#amplify.BinaryPolyArray.tonumpy) | Alias of [`to_numpy()`](https://amplify.fixstars.com/en/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`** **Return type:** 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. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **Parameters:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*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] > > **Example** > > ```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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) β†’ None`** **Parameters:** **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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) β†’ PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) β†’ PolyArray[_Dim]`** **Parameters:** **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*) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*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. **Parameters:** **arg** ([*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) *| ndarray*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) β†’ PolyArray[_Dim]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) β†’ Poly | PolyArray[__Dim]`** **Parameters:** **arg** (*NDArray |* [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)*[__Dim]*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/en/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. **Parameters:** * **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/en/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. **Raises:** * [**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`** **Return type:** [*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. **Returns:** Copy of the array. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/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/en/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. **Parameters:** **value** ([*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Flattened copy. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) β†’ tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **Returns:** Tuple of index arrays, one for each dimension. **Return type:** [*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. **Returns:** Flattened view when possible. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/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. **Parameters:** * **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`. **Returns:** Array with rolled elements. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **Raises:** [**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. **Parameters:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Array after substitution. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Parameters:** * **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. **Returns:** Array with the two axes swapped. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **Raises:** [**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. **Returns:** Converted NumPy array. **Return type:** [*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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). **Returns:** Converted NumPy array. **Return type:** [*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. **Returns:** View of the same underlying data. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) with default axis order. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.flatten), this property is a view. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **Return type:** [*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. **Return type:** [*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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) --- # IsingPolyArray **`class IsingPolyArray`** Bases: [`PolyArray`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_list). | | [`tonumpy`](#amplify.IsingPolyArray.tonumpy) | Alias of [`to_numpy()`](https://amplify.fixstars.com/en/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`** **Return type:** 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. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.copy). **Parameters:** **arg** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*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] > > **Example** > > ```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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__init__(self, object: ndarray[] | list | amplify.Poly) β†’ None`** **Parameters:** **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. **Return type:** [*int*](https://docs.python.org/3/library/functions.html#int) **`__invert__(self) β†’ PolyArray[_Dim]`** Perform an element-wise arithmetic operation. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*Iterator*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.Iterator)[_Dim] **`__itruediv__(self, arg: float | int | list | ndarray[], /) β†’ PolyArray[_Dim]`** **Parameters:** **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*) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*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. **Parameters:** **arg** ([*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray) *| ndarray*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **`__pow__(self, arg: int, /) β†’ PolyArray[_Dim]`** **Parameters:** **arg** ([*int*](https://docs.python.org/3/library/functions.html#int)) **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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`** **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__rmatmul__(self, arg: NDArray | PolyArray[__Dim]) β†’ Poly | PolyArray[__Dim]`** **Parameters:** **arg** (*NDArray |* [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)*[__Dim]*) **Return type:** [*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly) | [*PolyArray*](https://amplify.fixstars.com/en/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. **Parameters:** * **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/en/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. **Raises:** * [**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`** **Return type:** [*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. **Returns:** Copy of the array. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/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/en/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. **Parameters:** **value** ([*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Flattened copy. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`nonzero(self) β†’ tuple[numpy.ndarray[dtype=uint64], ...]`** Return the indices of non-zero elements. **Returns:** Tuple of index arrays, one for each dimension. **Return type:** [*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. **Returns:** Flattened view when possible. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/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. **Parameters:** * **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`. **Returns:** Array with rolled elements. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **Raises:** [**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. **Parameters:** **mapping** ([*Mapping*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)*[*[*Poly*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly)*,* [*Poly*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.Variable.md#amplify.Variable)*,* [*Poly*](https://amplify.fixstars.com/en/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. **Returns:** Array after substitution. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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. **Parameters:** * **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. **Returns:** Array with the two axes swapped. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[_Dim] **Raises:** [**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. **Returns:** Converted NumPy array. **Return type:** [*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/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.to_numpy). **Returns:** Converted NumPy array. **Return type:** [*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. **Returns:** View of the same underlying data. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.transpose) with default axis order. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/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/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray.flatten), this property is a view. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim1*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim1.md#amplify.Dim1)] **`property ndim`** The number of dimensions of the array. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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`** Bases: [`Matrix`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) β†’ Model`** Create a [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) β†’ str`** Return a developer-friendly string representation of the matrix form. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** Return a human-readable string representation of the matrix form. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **Returns:** Polynomial converted from this matrix form. **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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. **Returns:** Variable array used in this representation. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] --- # IsingMatrix **`class IsingMatrix`** Bases: [`Matrix`](https://amplify.fixstars.com/en/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/en/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/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__eq__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__init__(*args, **kwargs)`** **`__ne__(self, arg: object, /) β†’ bool`** **Parameters:** **arg** ([*object*](https://docs.python.org/3/library/functions.html#object)) **Return type:** [*bool*](https://docs.python.org/3/library/functions.html#bool) **`__radd__(self, arg: Constraint | ConstraintList, /) β†’ Model`** Create a [`Model`](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) whose objective is this matrix form, with the given constraints. **Parameters:** **arg** ([*Constraint*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) *|* [*ConstraintList*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.ConstraintList.md#amplify.ConstraintList)) – Constraints to include. **Returns:** Model containing this objective and the given constraints. **Return type:** [*Model*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Model.md#amplify.Model) **`__repr__(self) β†’ str`** Return a developer-friendly string representation of the matrix form. **Return type:** [*str*](https://docs.python.org/3/library/stdtypes.html#str) **`__str__(self) β†’ str`** Return a human-readable string representation of the matrix form. **Return type:** [*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/en/docs/amplify/v1/reference/generated/amplify.Poly.md#amplify.Poly). **Returns:** Polynomial converted from this matrix form. **Return type:** [*Poly*](https://amplify.fixstars.com/en/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`. **Return type:** [*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. **Return type:** [*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. **Return type:** [*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. **Returns:** Variable array used in this representation. **Return type:** [*PolyArray*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.PolyArray.md#amplify.PolyArray)[[*Dim*](https://amplify.fixstars.com/en/docs/amplify/v1/reference/generated/amplify.Dim.md#amplify.Dim)] --- # QuadraticModel **`class QuadraticModel`** Bases: [`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`** Bases: [`QuadraticModel`](https://amplify.fixstars.com/en/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`** Bases: [`QuadraticModel`](https://amplify.fixstars.com/en/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`** Bases: [`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/en/docs/amplify/v1/reference/generated/amplify.Constraint.md#amplify.Constraint) --- # InequalityFormulation **`class InequalityFormulation`** Bases: [`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`** --- The variable types and polynomial degree accepted for the input problem depend on the chosen algorithm. * When [QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | \*\* | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase. \*\*: When [Constrained QAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/theories/NHOT_QAOA_algo.md) is selected via [QAOA type](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/QAOA.md#qaoa-qaoatype), N-HOT constraints are supported. * When [RQAOA](https://amplify.fixstars.com/en/docs/amplify/v1/quantum/algos/RQAOA.md) is specified as the client argument | | Binary | Ising | Integer | Real | | --- | --- | --- | --- | --- | | Objective function | - | Nth degree\* | - | - | | Equality constraint | - | - | - | - | | Inequality constraint | - | - | - | - | \*: Problems of arbitrary degree are supported. However, depending on the qubit connectivity of the quantum computer, the required number of qubits may increase.