D-Wave Cloud Client¶
D-Wave Cloud Client is a minimal implementation of the REST interface used to communicate with D-Wave Sampler API (SAPI) servers.
SAPI is an application layer built to provide resource discovery, permissions, and scheduling for quantum annealing resources at D-Wave Systems. This package provides a minimal Python interface to that layer without compromising the quality of interactions and workflow.
Example¶
This example instantiates a D-Wave Cloud Client and solver based on the local system`s auto-detected default configuration file and samples a random Ising problem tailored to fit the solver`s graph.
import random
from dwave.cloud import Client
# Connect using the default or environment connection information
with Client.from_config() as client:
# Load the default solver
solver = client.get_solver()
# Build a random Ising model to exactly fit the graph the solver supports
linear = {index: random.choice([-1, 1]) for index in solver.nodes}
quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}
# Send the problem for sampling, include solver-specific parameter 'num_reads'
computation = solver.sample_ising(linear, quad, num_reads=100)
# Print the first sample out of a hundred
print(computation.samples[0])
Documentation¶
Release: | 0.6.2 |
---|---|
Date: | Dec 24, 2019 |
Introduction¶
D-Wave Cloud Client is a minimal implementation of the REST interface used to communicate with D-Wave Sampler API (SAPI) servers.
SAPI is an application layer built to provide resource discovery, permissions, and scheduling for quantum annealing resources at D-Wave Systems. This package provides a minimal Python interface to that layer without compromising the quality of interactions and workflow.
The D-Wave Cloud Client Solver
class enables low-level control of problem
submission. It is used, for example, by the dwave-system
DWaveSampler
, which enables quick incorporation
of the D-Wave system as a sampler in your code.
Configuration¶
It’s recommended you set up your D-Wave Cloud Client configuration through the interactive CLI utility.
As described in the Using a D-Wave System section of Ocean Documentation, for your code to access remote D-Wave compute resources, you must configure communication through SAPI; for example, your code needs your API token for authentication. D-Wave Cloud Client provides multiple options for configuring the required information:
- One or more locally saved configuration files
- Environment variables
- Direct setting of key values in functions
These options can be flexibly used together.
Configuration Files¶
If a D-Wave Cloud Client configuration file is not explicitly specified when instantiating a
client or solver, auto-detection searches for candidate files in a number of standard
directories, depending on your local system’s operating system. You can see the standard
locations with the get_configfile_paths()
method.
For example, on a Unix system, depending on its flavor, these might include (in order):
/usr/share/dwave/dwave.conf
/usr/local/share/dwave/dwave.conf
~/.config/dwave/dwave.conf
./dwave.conf
On Windows 7+, configuration files are expected to be located under:
C:\\Users\\<username>\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf
On Mac OS X, configuration files are expected to be located under:
~/Library/Application Support/dwave/dwave.conf
(For details on the D-Wave API for determining platform-independent paths to user data and configuration folders see the homebase tool.)
You can check the directories searched by get_configfile_paths()
from a console using the interactive CLI utility;
for example:
$ dwave config ls -m
/etc/xdg/xdg-ubuntu/dwave/dwave.conf
/usr/share/upstart/xdg/dwave/dwave.conf
/etc/xdg/dwave/dwave.conf
/home/jane/.config/dwave/dwave.conf
./dwave.conf
A single D-Wave Cloud Client configuration file can contain multiple profiles, each defining a separate combination of communication parameters such as the URL to the remote resource, authentication token, solver, etc. Configuration files conform to a standard Windows INI-style format: profiles are defined by sections such as, [profile-a] and [profile-b]. Default values for undefined profile keys are taken from the [defaults] section.
For example, if the configuration file, ~/.config/dwave/dwave.conf, selected through auto-detection as the default configuration, contains the following profiles:
[defaults]
token = ABC-123456789123456789123456789
[first-available-qpu]
solver = {"qpu": true}
[software]
client = sw
solver = c4-sw_sample
token = DEF-987654321987654321987654321
proxy = http://user:pass@myproxy.com:8080/
[backup-dwave2000q]
endpoint = https://url.of.my.backup.dwavesystem.com/sapi
solver = {"num_qubits__gt": 2000}
You can instantiate clients for a D-Wave system and a CPU with:
>>> from dwave.cloud import Client
>>> client_qpu = Client.from_config()
>>> client_cpu = Client.from_config(profile='software')
Environment Variables¶
In addition to files, you can set configuration information through environment variables; for example:
DWAVE_CONFIG_FILE
may select the configuration file path.DWAVE_PROFILE
may select the name of a profile (section).DWAVE_API_TOKEN
may select the API token.
For details on supported environment variables and prioritizing between these and
values set explicitly or through a configuration file, see dwave.cloud.config
.
Interactive CLI Configuration¶
As part of the installation of the D-Wave Cloud Client package, a dwave executable is installed; for example, in a virtual environment it might be installed as <virtual_environment>\Scripts\dwave.exe. Running this file from your system’s console opens an interactive command line interface (CLI) that guides you through setting up a D-Wave Cloud Client configuration file. It also provides additional helpful functionality; for example:
- List and update existing configuration files on your system
- Establish a connection to (ping) a solver and return timing information
- Show information on configured solvers
Run dwave --help for information on all the CLI options.
Note
If you work in a Bash shell and want command completion for dwave, add
eval "$(_DWAVE_COMPLETE=source <path>/dwave)"
to your shell’s .bashrc configuration file, where <path> is the absolute path to the installed dwave executable, for example /home/Mary/my-quantum-app/env/bin.
Work Flow¶
A typical workflow may include the following steps:
Instantiate a
Client
to manage communication with remote solver resources, selecting and authenticating access to available solvers; for example, you can list all solvers available to a client with itsget_solvers()
method and select and return one with itsget_solver()
method.Preferred use is with a context manager—a
with Client.from_config(...) as
construct—to ensure proper closure of all resources. The following example snippet creates a client based on an auto-detected configuration file and instantiates a solver.>>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver(qpu=True)
Alternatively, the following example snippet creates a client for software resources that it later explicitly closes.
>>> client = Client.from_config(client='sw') # doctest: +SKIP >>> # code that uses client >>> client.close() # doctest: +SKIP
Instantiate a selected
Solver
, a resource for solving problems. Solvers are responsible for:- Encoding submitted problems
- Checking submitted parameters
- Adding problems to a client’s submission queue
Solvers that provide sampling for solving Ising and QUBO problems, such as a D-Wave 2000Q sampler
DWaveSampler
or software samplerSimulatedAnnealingSampler
, might be remote resources.Submit your problem, using your solver, and then process the returned
Future
, instantiated by your solver to handle remotely executed problem solving.
Terminology¶
- Ising
Traditionally used in statistical mechanics. Variables are “spin up” (\(\uparrow\)) and “spin down” (\(\downarrow\)), states that correspond to \(+1\) and \(-1\) values. Relationships between the spins, represented by couplings, are correlations or anti-correlations. The objective function expressed as an Ising model is as follows:
\[\begin{equation} \text{E}_{ising}(\pmb{s}) = \sum_{i=1}^N h_i s_i + \sum_{i=1}^N \sum_{j=i+1}^N J_{i,j} s_i s_j \end{equation}\]where the linear coefficients corresponding to qubit biases are \(h_i\), and the quadratic coefficients corresponding to coupling strengths are \(J_{i,j}\).
- model
- A collection of variables with associated linear and quadratic biases.
- QUBO
Quadratic unconstrained binary optimization. QUBO problems are traditionally used in computer science. Variables are TRUE and FALSE, states that correspond to 1 and 0 values. A QUBO problem is defined using an upper-diagonal matrix \(Q\), which is an \(N\) x \(N\) upper-triangular matrix of real weights, and \(x\), a vector of binary variables, as minimizing the function
\[\begin{equation} f(x) = \sum_{i} {Q_{i,i}}{x_i} + \sum_{i<j} {Q_{i,j}}{x_i}{x_j} \end{equation}\]where the diagonal terms \(Q_{i,i}\) are the linear coefficients and the nonzero off-diagonal terms are the quadratic coefficients \(Q_{i,j}\). This can be expressed more concisely as
\[\begin{equation} \min_{{x} \in {\{0,1\}^n}} {x}^{T} {Q}{x}. \end{equation}\]In scalar notation, the objective function expressed as a QUBO is as follows:
\[\begin{equation} \text{E}_{qubo}(a_i, b_{i,j}; q_i) = \sum_{i} a_i q_i + \sum_{i<j} b_{i,j} q_i q_j. \end{equation}\]- sampler
- A process that samples from low energy states of a problem’s objective function. A binary quadratic model (BQM) sampler samples from low energy states in models such as those defined by an Ising equation or a Quadratic Unconstrained Binary Optimization (QUBO) problem and returns an iterable of samples, in order of increasing energy. A dimod sampler provides ‘sample_qubo’ and ‘sample_ising’ methods as well as the generic BQM sampler method.
- solver
- A resource that runs a problem. Some solvers interface to the QPU; others leverage CPU and GPU resources.
Reference Documentation¶
Release: 0.6.2 Date: Dec 24, 2019 noindex:
Configuration¶
Configuration for communicating with a solver.
Communicating with a solver—submitting a problem, monitoring its progress, receiving samples—requires configuration of several parameters such as the selected solver, its URL, an API token, etc. D-Wave Cloud Client provides multiple options for configuring those parameters:
- One or more locally saved configuration files.
- Environment variables
- Direct setting of key values in functions
These options can be flexibly used together. The standard use is through
the from_config()
classmethod.
Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked):
- Values specified as keyword arguments
- Values specified as environment variables
- Values specified in the configuration file
Configuration files comply with standard Windows INI-like format,
parsable with Python’s configparser
. An optional defaults section
provides default key-value pairs for all other sections. User-defined key-value
pairs (unrecognized keys) are passed through to the client.
Typically configuration files are created, inspected, and changed using interactive
CLI commands from your system’s console, such as dwave config create
and
dwave config inspect
(run dwave --help
for information on CLI options).
Environment variables:
DWAVE_CONFIG_FILE
: Configuration file path.
DWAVE_PROFILE
: Name of profile (section).
DWAVE_API_CLIENT
: API client class. Supported values areqpu
orsw
.
DWAVE_API_ENDPOINT
: API endpoint URL.
DWAVE_API_TOKEN
: API authorization token.
DWAVE_API_SOLVER
: Default solver.
DWAVE_API_PROXY
: URL for proxy connections to D-Wave API.
DWAVE_API_HEADERS
: Optional additional HTTP headers.
Examples
The following are typical examples of using from_config()
to create a configured client.
This first example initializes Client
from an
explicitly specified configuration file, “~/jane/my_path_to_config/my_cloud_conf.conf”:
[defaults]
token = ABC-123456789123456789123456789
[first-qpu]
solver = {"qpu": true}
[feature]
endpoint = https://url.of.some.dwavesystem.com/sapi
token = DEF-987654321987654321987654321
solver = {"num_qubits__gte": 2000, "max_anneal_schedule_points__gte": 4}
The example code below creates a client object that connects to a D-Wave QPU,
using dwave.cloud.qpu.Client
and the first available online D-Wave system
at the default API endpoint URL (https://cloud.dwavesys.com/sapi).
The feature
profile specifies a solver selected based on available features,
namely we’re requesting the first solver that has at least 2000 qubits and the
anneal schedule can be described with at least 4 points.
>>> from dwave.cloud import Client
>>> client = Client.from_config(config_file='~/jane/my_path_to_config/my_cloud_conf.conf') # doctest: +SKIP
>>> # code that uses client
>>> client.close()
This second example auto-detects a configuration file on the local system following the
user/system configuration paths of get_configfile_paths()
. It passes through
to the instantiated client an unrecognized key-value pair my_param=`my_value`.
>>> from dwave.cloud import Client
>>> client = Client.from_config(my_param=`my_value`)
>>> # code that uses client
>>> client.close()
This third example instantiates two clients, for managing both QPU and software solvers. Common key-value pairs are taken from the defaults section of a shared configuration file:
[defaults]
token = ABC-123456789123456789123456789
[primary-qpu]
solver = {"qpu": true}
[sw-solver]
client = sw
solver = c4-sw_sample
endpoint = https://url.of.some.software.resource.com/my_if
token = DEF-987654321987654321987654321
[backup-qpu]
solver = {"qpu": true, "num_qubits__gte": 2000}
endpoint = https://url.of.some.dwavesystem.com/sapi
proxy = http://user:pass@myproxy.com:8080/
token = XYZ-0101010100112341234123412341234
The example code below creates client objects for two QPU solvers (at the same URL but each with its own solver ID and token) and one software solver.
>>> from dwave.cloud import Client
>>> client_qpu1 = Client.from_config(profile='primary-qpu') # doctest: +SKIP
>>> client_qpu1 = Client.from_config(profile='backup-qpu') # doctest: +SKIP
>>> client_sw1 = Client.from_config(profile='sw-solver') # doctest: +SKIP
>>> client_qpu1.default_solver # doctest: +SKIP
u'EXAMPLE_2000Q_SYSTEM_A'
>>> client_qpu2.endpoint # doctest: +SKIP
u'https://url.of.some.dwavesystem.com/sapi'
>>> # code that uses client
>>> client_qpu1.close() # doctest: +SKIP
>>> client_qpu2.close() # doctest: +SKIP
>>> client_sw1.close() # doctest: +SKIP
This fourth example loads configurations auto-detected in more than one configuration
file, with the higher priority file (in the current working directory) supplementing
and overriding values from the lower priority user-local file. After instantiation,
an endpoint from the default section and client from the profile section is provided
from the user-local /usr/local/share/dwave/dwave.conf
file:
[defaults]
solver = {"qpu": true}
[dw2000]
endpoint = https://int.se.dwavesystems.com/sapi
token = ABC-123456789123456789123456789
A solver is supplemented from the file in the current working directory, which also
overrides the token value. ./dwave.conf
is the file in the current directory:
[dw2000]
token = DEF-987654321987654321987654321
>>> from dwave.cloud import Client
>>> client = Client.from_config()
>>> client.default_solver # doctest: +SKIP
u'EXAMPLE_2000Q_SYSTEM_A'
>>> client.endpoint # doctest: +SKIP
u'https://int.se.dwavesystems.com/sapi'
>>> client.token # doctest: +SKIP
u'DEF-987654321987654321987654321'
>>> # code that uses client
>>> client.close() # doctest: +SKIP
The next example uses load_config()
to load profile values.
Most users do not need to use this method. It loads from the following configuration
file, dwave_c.conf, located in the current working directory, and specified explicitly:
[defaults]
endpoint = https://url.of.some.dwavesystem.com/sapi
solver = {"qpu": true}
[dw2000a]
solver = {"software": true, "name": "EXAMPLE_2000Q"}
token = ABC-123456789123456789123456789
[dw2000b]
solver = {"qpu": true}
token = DEF-987654321987654321987654321
This configuration file contains two profiles in addition to the defaults section. In the following example code, first no profile is specified, and the first profile after the defaults section is loaded with the solver overridden by the environment variable. Next, the second profile is selected with the explicitly named solver overriding the environment variable setting.
>>> import dwave.cloud as dc
>>> import os
>>> os.environ['DWAVE_API_SOLVER'] = 'EXAMPLE_2000Q_SYSTEM' # doctest: +SKIP
>>> dc.config.load_config("./dwave_c.conf") # doctest: +SKIP
{'client': u'sw',
'endpoint': u'https://url.of.some.dwavesystem.com/sapi',
'proxy': None,
'headers': None,
'solver': 'EXAMPLE_2000Q_SYSTEM',
'token': u'ABC-123456789123456789123456789'}
>>> dc.config.load_config("./dwave_c.conf", profile='dw2000b', solver='Solver3') # doctest: +SKIP
{'client': u'qpu',
'endpoint': u'https://url.of.some.dwavesystem.com/sapi',
'proxy': None,
'headers': None,
'solver': 'Solver3',
'token': u'DEF-987654321987654321987654321'}
Methods¶
Most users do not need to use these methods.
Loading Configuration¶
These functions deploy D-Wave Cloud Client settings from a configuration file.
load_config ([config_file, profile, client, …]) |
Load D-Wave Cloud Client configuration based on a configuration file. |
Managing Files¶
These functions manage your D-Wave Cloud Client configuration files. It’s recommended you set up your configuration through the interactive CLI utility instead.
get_configfile_paths ([system, user, local, …]) |
Return a list of local configuration file paths. |
get_configfile_path () |
Return the highest-priority local configuration file. |
get_default_configfile_path () |
Return the default configuration-file path. |
Clients¶
The solvers that provide sampling for solving Ising and QUBO problems, such
as a D-Wave 2000Q QPU or a software sampler such as the dimod
simulated annealing sampler, are typically remote resources. The D-Wave Cloud Client
Client
class manages such remote solver resources.
Preferred use is with a context manager—a with Client.from_config(...) as
construct—to ensure proper closure of all resources. The following example snippet
creates a client based on an auto-detected configuration file and instantiates
a solver.
>>> with Client.from_config() as client: # doctest: +SKIP
... solver = client.get_solver(num_qubits__gt=2000)
Alternatively, the following example snippet creates a client for software resources that it later explicitly closes.
>>> client = Client.from_config(software=True) # doctest: +SKIP
>>> # code that uses client
>>> client.close() # doctest: +SKIP
Typically you use the Client
class. By default, it instantiates
a QPU client. You can also use the specialized QPU and CPU/GPU clients directly.
Client (Base Client)¶
D-Wave API clients handle communications with solver resources: problem submittal, monitoring, samples retrieval, etc.
Examples
This example creates a client using the local system’s default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a QUBO problem (a Boolean NOT gate represented by a penalty model), and samples 5 times.
>>> from dwave.cloud import Client
>>> Q = {(0, 0): -1, (0, 4): 0, (4, 0): 2, (4, 4): -1}
>>> with Client.from_config() as client: # doctest: +SKIP
... solver = client.get_solver()
... computation = solver.sample_qubo(Q, num_reads=5)
...
>>> for i in range(5): # doctest: +SKIP
... print(computation.samples[i][0], computation.samples[i][4])
...
(1, 0)
(1, 0)
(0, 1)
(0, 1)
(0, 1)
Class¶
-
class
dwave.cloud.client.
Client
(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, request_timeout=60, polling_timeout=None, connection_close=False, headers=None, **kwargs)¶ Base client class for all D-Wave API clients. Used by QPU and software sampler classes.
Manages workers and handles thread pools for submitting problems, cancelling tasks, polling problem status, and retrieving results.
Parameters: - endpoint (str) – D-Wave API endpoint URL.
- token (str) – Authentication token for the D-Wave API.
- solver (dict/str) – Default solver features (or simply solver name).
- proxy (str) – Proxy URL to be used for accessing the D-Wave API.
- permissive_ssl (bool, default=False) – Disables SSL verification.
- request_timeout (float, default=60) – Connect and read timeout (in seconds) for all requests to the D-Wave API.
- polling_timeout (float, default=None) – Problem status polling timeout (in seconds), after which polling is aborted.
- connection_close (bool, default=False) – Force HTTP(S) connection close after each request.
- headers (dict/str) – Additional HTTP headers.
Other Parameters: Unrecognized keys (str) – All unrecognized keys are passed through to the appropriate client class constructor as string keyword arguments.
An explicit key value overrides an identical user-defined key value loaded from a configuration file.
Examples
This example directly initializes a
Client
. Direct initialization uses class constructor arguments, the minimum being a value for token.>>> from dwave.cloud import Client >>> client = Client(token='secret') >>> # code that uses client >>> client.close()
Methods¶
client.Client.from_config ([config_file, …]) |
Client factory method to instantiate a client instance from configuration. |
client.Client.solvers ([refresh]) |
Deprecated in favor of get_solvers() . |
client.Client.get_solver ([name, refresh]) |
Load the configuration for a single solver. |
client.Client.get_solvers ([refresh, order_by]) |
Return a filtered list of solvers handled by this client. |
client.Client.is_solver_handled (solver) |
Determine if the specified solver should be handled by this client. |
client.Client.close () |
Perform a clean shutdown. |
Specialized Clients¶
Typically you use the Client
class. By default, it instantiates
a QPU client. You can also instantiate a QPU or CPU/GPU client directly.
QPU Client¶
An implementation of the REST API for D-Wave Solver API (SAPI) servers.
SAPI servers provide authentication, queuing, and scheduling services, and provide a network interface to solvers. This API enables you submit a binary quadratic (Ising or QUBO) model and receive samples from a distribution over the model as defined by a selected solver.
SAPI server workflow is roughly as follows:
- Submitted problems enter an input queue. Each user has an input queue per solver.
- Drawing from all input queues for a solver, problems are scheduled.
- Results are cached for retrieval by the client.
Class¶
-
class
dwave.cloud.qpu.
Client
(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, request_timeout=60, polling_timeout=None, connection_close=False, headers=None, **kwargs)¶ D-Wave API client specialized to work with QPU solvers.
This class is instantiated by default, or explicitly when client=qpu, with the typical base client instantiation
with Client.from_config() as client:
of a client. (You should not instantiate this class with client=sw or use it with solver feature constraint software=True.)Examples
This example explicitly instantiates a
dwave.cloud.qpu.client
based on the local system`s default D-Wave Cloud Client configuration file to sample a random Ising problem tailored to fit the client`s default solver`s graph.import random from dwave.cloud.qpu import Client # Use context manager to ensure resources (thread pools used by Client) are released with Client.from_config() as client: solver = client.get_solver() # Build problem to exactly fit the solver graph linear = {index: random.choice([-1, 1]) for index in solver.nodes} quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges} # Sample 100 times and print out the first sample computation = solver.sample_ising(linear, quad, num_reads=100) print(computation.samples[0])
Methods¶
qpu.Client.is_solver_handled (solver) |
Determine if the specified solver should be handled by this client. |
Software-Samplers Client¶
Class¶
-
class
dwave.cloud.sw.
Client
(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, request_timeout=60, polling_timeout=None, connection_close=False, headers=None, **kwargs)¶ D-Wave API client specialized to work with remote software solvers (samplers).
This class is instantiated by default, or explicitly when client=sw, with the typical base client instantiation
with Client.from_config() as client:
of a client. (You should not instantiate this class with client=qpu or use it with solver feature constraint qpu=True.)Examples
This example indirectly instantiates a
dwave.cloud.sw.client
based on the local system`s default D-Wave Cloud Client configuration file to sample a random Ising problem tailored to fit the client`s default solver`s graph.import random from dwave.cloud import Client # Use context manager to ensure resources (thread pools used by Client) are released with Client.from_config(solver={"software": True}) as client: solver = client.get_solver() # Build problem to exactly fit the solver graph linear = {index: random.choice([-1, 1]) for index in solver.nodes} quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges} # Sample 100 times and print out the first sample computation = solver.sample_ising(linear, quad, num_reads=100) print(computation.samples[0])
Methods¶
sw.Client.is_solver_handled (solver) |
Determine if the specified solver should be handled by this client. |
Solver¶
A solver is a resource for solving problems.
Solvers are responsible for:
- Encoding submitted problems
- Checking submitted parameters
- Decoding answers
- Adding problems to a client’s submission queue
You can list all solvers available to a Client
with its
get_solvers()
method and select and return one with its
get_solver()
method.
Class¶
-
dwave.cloud.solver.
Solver
¶ alias of
dwave.cloud.solver.StructuredSolver
-
class
dwave.cloud.solver.
BaseSolver
(client, data)¶ Base class for a general D-Wave solver.
This class provides Ising, QUBO and BQM sampling methods and encapsulates the solver description returned from the D-Wave cloud API.
Parameters: - client (
Client
) – Client that manages access to this solver. - data (dict) – Data from the server describing this solver.
Examples
This example creates a client using the local system’s default D-Wave Cloud Client configuration file and checks the identity of its default solver.
>>> from dwave.cloud import Client >>> with Client.from_config() as client: ... solver = client.get_solver() ... solver.id # doctest: +SKIP 'EXAMPLE_2000Q_SYSTEM'
- client (
-
class
dwave.cloud.solver.
StructuredSolver
(*args, **kwargs)¶ Class for D-Wave structured solvers.
This class provides Ising, QUBO and BQM sampling methods and encapsulates the solver description returned from the D-Wave cloud API.
Parameters: - client (
Client
) – Client that manages access to this solver. - data (dict) – Data from the server describing this solver.
- client (
-
class
dwave.cloud.solver.
UnstructuredSolver
(client, data)¶ Class for D-Wave unstructured solvers.
This class provides Ising, QUBO and BQM sampling methods and encapsulates the solver description returned from the D-Wave cloud API.
Parameters: - client (
Client
) – Client that manages access to this solver. - data (dict) – Data from the server describing this solver.
- client (
Methods¶
StructuredSolver.check_problem (linear, quadratic) |
Test if an Ising model matches the graph provided by the solver. |
StructuredSolver.sample_ising (linear, …) |
Sample from the specified Ising model. |
StructuredSolver.sample_qubo (qubo, **params) |
Sample from the specified QUBO. |
StructuredSolver.max_num_reads (**params) |
Returns the maximum number of reads for the given solver parameters. |
UnstructuredSolver.sample_ising (linear, …) |
Sample from the specified BQM. |
UnstructuredSolver.sample_qubo (qubo, **params) |
Sample from the specified QUBO. |
UnstructuredSolver.sample_bqm (bqm, **params) |
Sample from the specified BQM. |
Properties¶
BaseSolver.name |
|
BaseSolver.online |
Is this solver online (or offline)? |
BaseSolver.avg_load |
Solver’s average load, at the time of description fetch. |
BaseSolver.qpu |
Is this a QPU-based solver? |
BaseSolver.software |
Is this a software-based solver? |
StructuredSolver.num_active_qubits |
The number of active (encoding) qubits. |
StructuredSolver.num_qubits |
Nominal number of qubits on chip (includes active AND inactive). |
StructuredSolver.is_vfyc |
Is this a virtual full-yield chip? |
StructuredSolver.has_flux_biases |
Solver supports/accepts flux_biases . |
StructuredSolver.has_anneal_schedule |
Solver supports/accepts anneal_schedule . |
StructuredSolver.lower_noise |
Computation¶
Computation manages the interactions between your code and a solver, which manages interactions between the remote resource and your submitted problems.
Your solver instantiates a Future
object for its calls, via D-Wave Sampler API
(SAPI) servers, to the remote resource.
You can interact through the Future
object with pending (running) or completed
computation—sampling on a QPU or software solver—executed remotely, monitoring problem status,
waiting for and retrieving results, cancelling enqueued jobs, etc.
Some Future
methods are blocking.
Class¶
-
class
dwave.cloud.computation.
Future
(solver, id_, return_matrix=False)¶ Class for interacting with jobs submitted to SAPI.
Solver
usesFuture
to construct objects for pending SAPI calls that can wait for requests to complete and parse returned messages.Objects are blocked for the duration of any data accessed on the remote resource.
Warning
Future
objects are not intended to be directly created. Problem submittal is initiated by one of the solvers insolver
module and executed by one of the clients.Parameters: - solver (
Solver
) – Solver responsible for thisFuture
object. - id (str, optional, default=None) – Identification for a query submitted by a solver to SAPI. May be None following submission until an identification number is set.
- return_matrix (bool, optional, default=False) – Return values for this
Future
object are NumPy matrices.
Examples
This example creates a solver using the local system’s default D-Wave Cloud Client configuration file, submits a simple QUBO problem to a remote D-Wave resource for 100 samples, and checks a couple of times whether the sampling is completed.
>>> from dwave.cloud import Client >>> client = Client.from_config() >>> solver = client.get_solver() >>> u, v = next(iter(solver.edges)) >>> Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} >>> computation = solver.sample_qubo(Q, num_reads=100) # doctest: +SKIP >>> computation.done() # doctest: +SKIP False >>> computation.id # doctest: +SKIP u'1cefeb6d-ebd5-4592-87c0-4cc43ec03e27' >>> computation.done() # doctest: +SKIP True >>> client.close()
- solver (
Methods¶
Future.result () |
Results for a submitted job. |
Future.as_completed (fs[, timeout]) |
Yield Futures objects as they complete. |
Future.wait ([timeout]) |
Wait for the solver to receive a response for a submitted problem. |
Future.wait_multiple (futures[, min_done, …]) |
Wait for multiple Future objects to complete. |
Future.done () |
Check whether the solver received a response for a submitted problem. |
Future.cancel () |
Try to cancel the problem corresponding to this result. |
Properties¶
Future.samples |
State buffer for the submitted job. |
Future.variables |
List of active variables in response/answer. |
Future.energies |
Energy buffer for the submitted job. |
Future.occurrences |
Occurrences buffer for the submitted job. |
Future.sampleset |
Return SampleSet representation of the results. |
Future.problem_type |
Submitted problem type for this computation, as returned by the solver API. |
Future.timing |
Timing information about a solver operation. |
Exceptions¶
-
exception
dwave.cloud.exceptions.
CanceledFutureError
¶ An exception raised when code tries to read from a canceled future.
-
exception
dwave.cloud.exceptions.
ConfigFileError
¶ Base exception for all config file processing errors.
-
exception
dwave.cloud.exceptions.
ConfigFileParseError
¶ Invalid format of config file.
-
exception
dwave.cloud.exceptions.
ConfigFileReadError
¶ Non-existing or unreadable config file specified or implied.
-
exception
dwave.cloud.exceptions.
InvalidAPIResponseError
¶ Raised when an invalid/unexpected response from D-Wave Solver API is received.
-
exception
dwave.cloud.exceptions.
InvalidProblemError
¶ Solver cannot handle the given binary quadratic model.
-
exception
dwave.cloud.exceptions.
PollingTimeout
¶ Problem polling timed out.
-
exception
dwave.cloud.exceptions.
ProblemUploadError
¶ Problem multipart upload failed.
-
exception
dwave.cloud.exceptions.
RequestTimeout
¶ REST API request timed out.
-
exception
dwave.cloud.exceptions.
SolverAuthenticationError
¶ An exception raised when there is an authentication error.
-
exception
dwave.cloud.exceptions.
SolverError
¶ Generic base class for all solver-related errors.
-
exception
dwave.cloud.exceptions.
SolverFailureError
¶ An exception raised when there is a remote failure calling a solver.
-
exception
dwave.cloud.exceptions.
SolverNotFoundError
¶ Solver with matching feature set not found / not available.
-
exception
dwave.cloud.exceptions.
SolverOfflineError
¶ Action attempted on an offline solver.
-
exception
dwave.cloud.exceptions.
SolverPropertyMissingError
¶ The solver we received from the API does not have required properties.
-
exception
dwave.cloud.exceptions.
Timeout
¶ General timeout error.
-
exception
dwave.cloud.exceptions.
UnsupportedSolverError
¶ The solver we received from the API is not supported by the client.
Bibliography¶
Installation¶
Compatible with Python 2 and 3:
pip install dwave-cloud-client
To install from source (available on GitHub in dwavesystems/dwave-cloud-client repo):
pip install -r requirements.txt
python setup.py install
License¶
Apache LicenseVersion 2.0, January 2004
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
- You must give any other recipients of the Work or Derivative Works a copy of this License; and
- You must cause any modified files to carry prominent notices stating that You changed the files; and
- You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
- If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets “[]” replaced with your own identifying information. (Don’t include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same “printed page” as the copyright notice for easier identification within third-party archives.Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.