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) for profile, 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_file is not specified, an auto-detection is performed (looking first for dwave.conf in process’ current working directory, then in user-local config directories, and finally in system-wide config dirs). For details on format and location detection, see load_config_from_file().

If location of config_file is explicitly specified (via arguments or environment variable), but the file does not exits, or is not readable, config loading will fail with ConfigFileReadError. Config loading will fail with ConfigFileParseError if file is readable, but it’s not a valid config file.

Similarly, if profile is explicitly specified (via arguments or environment variable), config loading will fail with ValueError if 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 profile argument below.

Environment variables:

DWAVE_CONFIG_FILE:
Config file path used if config_file not specified.
DWAVE_PROFILE:
Name of config profile (section) to use if profile not specified.
DWAVE_API_CLIENT:
API client class used (can be: qpu or sw). Overrides values from config file, but is overridden with client.
DWAVE_API_ENDPOINT:
API endpoint URL to use instead of the URL given in config file, if endpoint not 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 from DWAVE_CONFIG_FILE environment variable. If that env var is undefined or empty, the location of configuration files is auto-detected, as described in load_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_FILE env var) by setting config_file to True.

  • profile (str, default=None) – Profile name (config file section name). If undefined (by default), it is inferred from DWAVE_PROFILE environment variable, and if that variable is not present, profile key is looked-up in the [defaults] config section. If profile is 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 qpu to specify the dwave.cloud.qpu.Client and sw for dwave.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 to get_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:

dict

Raises:
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 factory from_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__HTTPLINK
  • DW_INTERNAL__TOKEN
  • DW_INTERNAL__HTTPPROXY
  • DW_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_token is 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.conf is not found (in any of the standard locations, see load_config_from_file() and load_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 to get_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 named dwave.conf is 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:

ConfigParser

Raises:
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.conf in CWD, user-local .config/dwave/, system-wide /etc/dwave/. For details, see load_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:
  • endpoint (str) – D-Wave API endpoint URL.
  • token (str) – Authentication token for the D-Wave API.
  • solver (str) – Default solver.
  • proxy (str) – Proxy URL to be used for accessing the D-Wave API.
  • permissive_ssl (bool, default=False) – Disables SSL verification.
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.Client or dwave.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. None for auto-detect, False to skip loading from any file (including auto-detection), and True to 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_PROFILE environment variable, or config file, or first section, or defaults. For details, see load_config().
  • client (str, default=None) – Client class (selected by name) to use for accessing the API. Use qpu to specify the dwave.cloud.qpu.Client and sw for dwave.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 to get_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.conf config file fails, try loading the .dwrc legacy 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.conf in 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:
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 Solver instance, which in turn can be used to submit sampling problems to the D-Wave API and fetch the results.

Parameters:
  • name (str) – Id of the requested solver. None will return the default solver.
  • refresh (bool) – Return solver from cache (if cached with get_solvers()), unless set to True.
Returns:

Solver

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 Solver instances.

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 the get_solver() method.

Parameters:refresh (bool, default=False) – By default, get_solvers caches the list of solvers it receives from the API. Use this parameter to force refresh.
Returns:a mapping of solver name/id to Solver
Return 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.

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.

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 a Client object.

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:
  • linear (list/dict) – Linear terms of the model (h).
  • quadratic (dict of (int, int) – float): Quadratic terms of the model (J).
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:
  • linear (list/dict) – Linear terms of the model (h).
  • quadratic (dict of (int, int) – float): Quadratic terms of the model (J).
  • **params – Parameters for the sampling method, specified per solver.
Returns:

Future

sample_qubo(qubo, **params)

Draw samples from the provided QUBO.

To submit a problem: POST /problems/

Parameters:
  • qubo (dict of (int, int) – float): Terms of the model.
  • **params – Parameters for the sampling method, specified per solver.
Returns:

Future

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(), and wait_multiple() can be used to block for a variable number of jobs for a given amount of time.

Note

Only constructed by Solver objects.

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:
  • futures (list of Future) – list of objects to wait on
  • min_done (int) – Stop waiting when this many results are ready
  • timeout (float) – Maximum number of seconds to wait, None for indefinite wait.
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.