Reference Documentation¶
Release: 0.3.4 Date: Apr 19, 2018
Configuration¶
-
dwave.cloud.config.load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None)¶ Load D-Wave cloud client configuration from
config_file(either explicitly specified, or auto-detected) forprofile, but override the values from config file with values defined in process environment, and override those with values specified with keyword arguments.Config file uses the standard Windows INI format, with one profile per section. A section providing default values for all other sections is called
defaults.If the location of
config_fileis not specified, an auto-detection is performed (looking first fordwave.confin process’ current working directory, then in user-local config directories, and finally in system-wide config dirs). For details on format and location detection, seeload_config_from_file().If location of
config_fileis explicitly specified (via arguments or environment variable), but the file does not exits, or is not readable, config loading will fail withConfigFileReadError. Config loading will fail withConfigFileParseErrorif file is readable, but it’s not a valid config file.Similarly, if
profileis explicitly specified (via arguments or environment variable), config loading will fail withValueErrorif that profile is not present in the config loaded. If config file is not specified explicitly, nor detected on file system, not defined via environment, resulting in an empty config, explicit profile selection will also fail.If profile is not explicitly specified, selection of profile is described under
profileargument below.Environment variables:
DWAVE_CONFIG_FILE:- Config file path used if
config_filenot specified. DWAVE_PROFILE:- Name of config profile (section) to use if
profilenot specified. DWAVE_API_CLIENT:- API client class used (can be:
qpuorsw). Overrides values from config file, but is overridden withclient. DWAVE_API_ENDPOINT:- API endpoint URL to use instead of the URL given in config file,
if
endpointnot given. DWAVE_API_TOKEN:- API authorization token. Overrides values from config file, but is
overridden with
token. DWAVE_API_SOLVER:- Default solver. Overrides values from config file, but is overridden
with
solver. DWAVE_API_PROXY:- URL for proxy to use in connections to D-Wave API. Overrides values
from config file, but is overridden with
proxy.
Parameters: - config_file (str/None/False/True, default=None) –
Path to config file.
If undefined (set to
None), the name of the config file is taken fromDWAVE_CONFIG_FILEenvironment variable. If that env var is undefined or empty, the location of configuration files is auto-detected, as described inload_config_from_files().Config loading from files, including auto-detected ones, can be skipped if config_file is set to
False.Auto-detection is forced (disregarding
DWAVE_CONFIG_FILEenv var) by setting config_file toTrue. - profile (str, default=None) – Profile name (config file section name). If undefined (by default),
it is inferred from
DWAVE_PROFILEenvironment variable, and if that variable is not present,profilekey is looked-up in the[defaults]config section. Ifprofileis not defined under[defaults], the first section is used. If no other sections are defined besides[defaults], the[defaults]section is promoted to profile. - client (str, default=None) – Client (selected by name) to use for accessing the API. Use
qputo specify thedwave.cloud.qpu.Clientandswfordwave.cloud.sw.Client. - endpoint (str, default=None) – API endpoint URL.
- token (str, default=None) – API authorization token.
- solver (str, default=None) – Default solver to use in
get_solver(). If undefined, you’ll have to explicitly specify the solver name/id in all calls toget_solver(). - proxy (str, default=None) – URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client will connect directly to the API (unless you use a system-level proxy).
Returns: Mapping of config keys to config values, for a specific profile (section), as read from the config file, overridden with environment values, overridden with immediate keyword arguments.
A set of keys guaranteed to be present:
client,endpoint,token,solver,proxy.Example:
{ 'client': 'qpu' 'endpoint': 'https://cloud.dwavesys.com/sapi', 'token': '123', 'solver': None, 'proxy': None }
Return type: Raises: ValueError– Invalid (non-existing) profile name.ConfigFileReadError– Config file specified or detected could not be opened or read.ConfigFileParseError– Config file parse failed.
-
dwave.cloud.config.legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs)¶ Load the configured URLs and token for the SAPI server.
Warning
Included only for backward compatibility, please use
load_config()instead, or the client factoryfrom_config().This method tries to load a configuration file from
~/.dwrc, select a specified profile (or first if not specified), and then override individual keys with the values read from environment variables, and finally with values given explicitly through function arguments.The environment variables searched are:
DW_INTERNAL__HTTPLINKDW_INTERNAL__TOKENDW_INTERNAL__HTTPPROXYDW_INTERNAL__SOLVER
The configuration file format is a modified CSV where the first comma is replaced with a bar character
|. Each line encodes a single profile.The columns are:
profile_name|endpoint_url,authentication_token,proxy_url,default_solver_name
Everything after the
authentication_tokenis optional.When there are multiple connections in a file, the first one is taken to be the default. Any commas in the urls must be percent encoded.
Example
For the configuration file
./.dwrc:profile-a|https://one.com,token-one profile-b|https://two.com,token-two
Assuming the new config file
dwave.confis not found (in any of the standard locations, seeload_config_from_file()andload_config()), then:>>> client = dwave.cloud.Client.from_config() # Will try to connect with the url `https://one.com` and the token `token-one`.
>>> client = dwave.cloud.Client.from_config(profile='profile-b') # Will try to connect with the url `https://two.com` and the token `token-two`.
>>> client = dwave.cloud.Client.from_config(profile='profile-b', token='new-token') # Will try to connect with the url `https://two.com` and the token `new-token`.
Parameters: - profile (str) – The profile name in the legacy config file.
- endpoint (str, default=None) – API endpoint URL. Overrides environment/config file.
- token (str, default=None) – API authorization token. Overrides environment/config file.
- solver (str, default=None) – Default solver to use in
get_solver(). If undefined, you’ll have to explicitly specify the solver name/id in all calls toget_solver(). - proxy (str, default=None) – URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client will connect directly to the API (unless you use a system-level proxy).
Returns: endpoint, token, solver, proxy.
Return type: A dictionary with keys
-
dwave.cloud.config.load_config_from_files(filenames=None)¶ Load D-Wave cloud client configuration from a list of
filenames.The format of the config file is the standard Windows INI-like format, parsable with the Python’s
configparser.Each filename in the list (each config file loaded) progressively upgrades the final configuration (on a key by key basis, per each section).
The section containing default values inherited by other sections is called
defaults. For example:[defaults] endpoint = https://cloud.dwavesys.com/sapi client = qpu [dw2000] solver = DW_2000Q_1 token = ... [software] client = sw solver = c4-sw_sample token = ... [alpha] endpoint = https://url.to.alpha/api proxy = http://user:pass@myproxy.com:8080/ token = ...
Parameters: filenames (list[str], default=None) –
D-Wave cloud client configuration file locations.
If set to
None, a config file nameddwave.confis searched for in all system-wide config dirs, then in the user-local config dir, and finally in the current directory. For example, on Unix, we try to load the config from these paths (in order) and possibly others (depending on your Unix flavour):/usr/share/dwave/dwave.conf /usr/local/share/dwave/dwave.conf ~/.config/dwave/dwave.conf ./dwave.conf
On Windows 7+, config file should be located in:
C:\Users\<username>\AppData\Local\dwavesystem\dwave\dwave.conf, and on Mac OS X in:~/Library/Application Support/dwave/dwave.conf. For details on user/system config paths see homebase.Returns: A
dict-like mapping of config sections (profiles) to mapping of per-profile keys holding values.Return type: Raises: ConfigFileReadError– Config file specified or detected could not be opened or read.ConfigFileParseError– Config file parse failed.
-
dwave.cloud.config.detect_existing_configfile_paths()¶ Returns the list of existing config files found on disk.
Candidates examined depend on the OS, but for Linux possible list is:
dwave.confin CWD, user-local.config/dwave/, system-wide/etc/dwave/. For details, seeload_config_from_file().
Resources¶
Base Client¶
-
class
dwave.cloud.client.Client(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, **kwargs)¶ Base client for all D-Wave API clients.
Implements workers (and handles thread pools) for problem submittal, task cancellation, problem status polling and results downloading.
Parameters: -
close()¶ Perform a clean shutdown.
Wait for all the currently scheduled work to finish, kill the workers, and close the connection pool. Assumes no one is submitting more work while the connection is closing.
-
classmethod
from_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=True, **kwargs)¶ Client factory method which loads configuration from file(s), process environment variables and explicitly provided values, creating and returning the appropriate client instance (
dwave.cloud.qpu.Clientordwave.cloud.sw.Client).Note
For details on config loading from files and environment, please see
load_config().Parameters: - config_file (str/None/False/True, default=None) – Path to config file.
Nonefor auto-detect,Falseto skip loading from any file (including auto-detection), andTrueto force auto-detection, disregarding environment value for config file. - profile (str, default=None) – Profile name (config file section name). If undefined it is
taken from
DWAVE_PROFILEenvironment variable, or config file, or first section, or defaults. For details, seeload_config(). - client (str, default=None) – Client class (selected by name) to use for accessing the API.
Use
qputo specify thedwave.cloud.qpu.Clientandswfordwave.cloud.sw.Client. - endpoint (str, default=None) – API endpoint URL.
- token (str, default=None) – API authorization token.
- solver (str, default=None) – Default solver to use in
get_solver(). If undefined, you’ll have to explicitly specify the solver name/id in all calls toget_solver(). - proxy (str, default=None) – URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client will connect directly to the API (unless you use a system-level proxy).
- legacy_config_fallback (bool, default=True) – If loading from a
dwave.confconfig file fails, try loading the.dwrclegacy config. - **kwargs –
All remaining keyword arguments are passed-through as-is to the chosen Client constructor method.
A notable custom argument is permissive_ssl.
Note: all user-defined keys from config files are propagated to the Client constructor too, and can be overridden with these keyword arguments.
Example
Create
dwave.confin your current directory or~/.config/dwave/dwave.conf:[prod] endpoint = https://cloud.dwavesys.com/sapi token = DW-123123-secret solver = DW_2000Q_1
Run:
from dwave.cloud import Client with Client.from_config(profile='prod') as client: solver = client.get_solver() computation = solver.sample_ising({}, {}) samples = computation.result()
Raises: ConfigFileReadError– Config file specified or detected could not be opened or read.ConfigFileParseError– Config file parse failed.
- config_file (str/None/False/True, default=None) – Path to config file.
-
get_solver(name=None, refresh=False)¶ Load the configuration for a single solver, as publicized by the API on
{endpoint}/solvers/remote/{solver_name}/.This is a blocking web call that returns a
Solverinstance, which in turn can be used to submit sampling problems to the D-Wave API and fetch the results.Parameters: Returns:
-
get_solvers(refresh=False)¶ List all the solvers this client can provide, and load the data about the solvers.
This is a blocking web call to {endpoint}/solvers/remote/` that caches the result and populates a list of available solvers described through
Solverinstances.To submit a sampling problem to the D-Wave API, filter the list returned and execute a
sampling_*method on the solver of interest. Alternatively, if you know the solver name (or it’s defined in config), use theget_solver()method.Parameters: refresh (bool, default=False) – By default, get_solverscaches the list of solvers it receives from the API. Use this parameter to force refresh.Returns: a mapping of solver name/id to SolverReturn type: dict[id, solver]
-
static
is_solver_handled(solver)¶ Predicate function that determines if the given solver should be handled by this client.
Can be overridden in a subclass to specialize the client for a particular type of solvers.
Default implementation accepts all solvers.
-
QPU Client¶
-
class
dwave.cloud.qpu.Client(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, **kwargs)¶ D-Wave API client specialized to work with the QPU solvers (samplers).
-
static
is_solver_handled(solver)¶ Predicate function used from superclass to filter solvers. In QPU client we’re handling only QPU solvers.
-
static
Software Samplers Client¶
-
class
dwave.cloud.sw.Client(endpoint=None, token=None, solver=None, proxy=None, permissive_ssl=False, **kwargs)¶ D-Wave API client specialized to work with the remote software solvers (samplers).
-
static
is_solver_handled(solver)¶ Predicate function used from superclass to filter solvers. In the software client we’re handling only remote software solvers.
-
static
Solver¶
-
class
dwave.cloud.solver.Solver(client, data)¶ A solver enables sampling from an Ising model. It encapsulates the solver description as returned by the D-Wave cloud API.
Get solver objects by calling
get_solver()on aClientobject.The solver has responsibility for: - Encoding problems submitted - Checking the submitted parameters - Add problems to the Client’s submission queue
Parameters: - client (
Client) – Client through which the solver is accessed. - data (dict) – Data from the server describing this solver.
-
check_problem(linear, quadratic)¶ Test if an Ising model matches the graph provided by the solver.
Parameters: Returns: boolean
-
retrieve_problem(id_)¶ Resume polling for a problem previously submitted.
Parameters: id – Identification of the query. Returns: obj: Future
-
sample_ising(linear, quadratic, **params)¶ Draw samples from the provided Ising model.
To submit a problem:
POST /problems/Parameters: Returns: Future
- client (
Computation¶
-
class
dwave.cloud.computation.Future(solver, id_, return_matrix, submission_data)¶ An object for a pending SAPI call.
Waits for a request to complete and parses the message returned. The future will be block to resolve when any data value is accessed. The method
done()can be used to query for resolution without blocking.wait(), andwait_multiple()can be used to block for a variable number of jobs for a given amount of time.Note
Only constructed by
Solverobjects.Parameters: - solver – The solver that is going to fulfil this future.
- id – Identification of the query we are waiting for. (May be None and filled in later.)
- return_matrix – Request return values as numpy matrices.
-
static
as_completed(fs, timeout=None)¶ Emulate concurrent.futures.as_completed() behavior.
Returns an iterator over the list of out Future instances given by fs that yields futures as they complete (finished or were cancelled).
The concurrent.futures.TimeoutError is raised if per-future timeout is exceeded at any point.
-
cancel()¶ Try to cancel the problem corresponding to this result.
An effort will be made to prevent the execution of the corresponding problem but there are no guarantees.
-
done()¶ Test whether a response has arrived.
-
energies¶ The energy buffer, blocks if needed.
Returns: list or numpy matrix of doubles.
-
id¶ The id the server will use to identify this problem, None until the id is actually known
-
occurrences¶ The occurrences buffer, blocks if needed.
Returns: list or numpy matrix of doubles.
-
remote_status¶ Status flag most recently returned by the server
-
result()¶ Blocking call to retrieve the result.
Returns: dict with the results. Should be considered read-only.
-
samples¶ The state buffer, blocks if needed.
Returns: list of lists or numpy matrix.
-
time_received¶ datetime corresponding to the time when the problem was accepted by the server (None before then)
-
time_solved¶ datetime corresponding to the time when the problem was completed by the server (None before then)
-
timing¶ Information about the time the solver took in operation.
The response is a mapping from string keys to numeric values. The exact keys used depend on the solver.
Returns: dict
-
wait(timeout=None)¶ Wait for the results to be available.
Parameters: timeout (float) – Maximum number of seconds to wait
-
static
wait_multiple(futures, min_done=None, timeout=None)¶ Wait for multiple Future objects to complete.
Python doesn’t provide a multi-wait, but we can jury rig something reasonably efficient using an event object.
Parameters: Returns: 2-tuple of futures done and not_done, similar to concurrent.futures.wait()
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.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.UnsupportedSolverError¶ The solver we received from the API is not supported by the client.