Samplers

A sampler accepts a problem in binary quadratic model (BQM) or discrete quadratic model (DQM) format and returns variable assignments. Samplers generally try to find minimizing values but can also sample from distributions defined by the problem.

These samplers are non-blocking: the returned SampleSet is constructed from a Future-like object that is resolved on the first read of any of its properties; for example, by printing the results. Your code can query its status with the done() method or ensure resolution with the resolve() method.

Other Ocean packages provide additional samplers; for example, dimod provides samplers for testing your code.

DWaveSampler

class DWaveSampler(failover=False, retry_interval=- 1, **config)[source]

A class for using the D-Wave system as a sampler for binary quadratic models.

You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments. For more information, see D-Wave Cloud Client get_solvers(). By default, online D-Wave systems are returned ordered by highest number of qubits.

Inherits from dimod.Sampler and dimod.Structured.

Parameters
  • failover (bool, optional, default=False) – Switch to a new QPU in the rare event that the currently connected system goes offline. Note that different QPUs may have different hardware graphs and a failover will result in a regenerated nodelist, edgelist, properties and parameters.

  • retry_interval (number, optional, default=-1) – The amount of time (in seconds) to wait to poll for a solver in the case that no solver is found. If retry_interval is negative then it will instead propogate the SolverNotFoundError to the user.

  • **config – Keyword arguments passed to dwave.cloud.client.Client.from_config().

Note

Prior to version 1.0.0, DWaveSampler used the base client, allowing non-QPU solvers to be selected. To reproduce the old behavior, instantiate DWaveSampler with client='base'.

Examples

This example submits a two-variable Ising problem mapped directly to two adjacent qubits on a D-Wave system. qubit_a is the first qubit in the QPU’s indexed list of qubits and qubit_b is one of the qubits coupled to it. Other required parameters for communication with the system, such as its URL and an autentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to D-Wave Solvers. Given sufficient reads (here 100), the quantum computer should return the best solution, \({1, -1}\) on qubit_a and qubit_b, respectively, as its first sample (samples are ordered from lowest energy).

>>> from dwave.system import DWaveSampler
...
>>> sampler = DWaveSampler()
...
>>> qubit_a = sampler.nodelist[0]
>>> qubit_b = next(iter(sampler.adjacency[qubit_a]))
>>> sampleset = sampler.sample_ising({qubit_a: -1, qubit_b: 1},
...                                  {},
...                                  num_reads=100)
>>> sampleset.first.sample[qubit_a] == 1 and sampleset.first.sample[qubit_b] == -1
True

See Ocean Glossary for explanations of technical terms in descriptions of Ocean tools.

Properties

For parameters and properties of D-Wave systems, see D-Wave System Documentation.

DWaveSampler.properties

D-Wave solver properties as returned by a SAPI query.

DWaveSampler.parameters

D-Wave solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in properties for each key.

DWaveSampler.nodelist

List of active qubits for the D-Wave solver.

DWaveSampler.edgelist

List of active couplers for the D-Wave solver.

DWaveSampler.adjacency

Adjacency structure formatted as a dict, where keys are the nodes of the structured sampler and values are sets of all adjacent nodes for each key node.

DWaveSampler.structure

Structure of the structured sampler formatted as a namedtuple, Structure(nodelist, edgelist, adjacency), where the 3-tuple values are the nodelist, edgelist and adjacency attributes.

Methods

DWaveSampler.sample(bqm[, warnings])

Sample from the specified binary quadratic model.

DWaveSampler.sample_ising(h, *args, **kwargs)

Sample from an Ising model using the implemented sample method.

DWaveSampler.sample_qubo(Q, **parameters)

Sample from a QUBO using the implemented sample method.

DWaveSampler.validate_anneal_schedule(...)

Raise an exception if the specified schedule is invalid for the sampler.

DWaveSampler.to_networkx_graph()

Converts DWaveSampler's structure to a Chimera or Pegasus NetworkX graph.

DWaveCliqueSampler

class DWaveCliqueSampler(*, failover: bool = False, retry_interval: numbers.Number = - 1, **config)[source]

A sampler for solving clique binary quadratic models on the D-Wave system.

This sampler wraps find_clique_embedding() to generate embeddings with even chain length. These embeddings work well for dense binary quadratic models. For sparse models, using EmbeddingComposite with DWaveSampler is preferred.

Configuration such as solver selection is similar to that of DWaveSampler.

Parameters
  • failover (optional, default=False) – Switch to a new QPU in the rare event that the currently connected system goes offline. Note that different QPUs may have different hardware graphs and a failover will result in a regenerated nodelist, edgelist, properties and parameters.

  • retry_interval (optional, default=-1) – The amount of time (in seconds) to wait to poll for a solver in the case that no solver is found. If retry_interval is negative then it will instead propogate the SolverNotFoundError to the user.

  • **config – Keyword arguments, as accepted by DWaveSampler

Examples

This example creates a BQM based on a 6-node clique (complete graph), with random \(\pm 1\) values assigned to nodes, and submits it to a D-Wave system. Parameters for communication with the system, such as its URL and an autentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to D-Wave Solvers.

>>> from dwave.system import DWaveCliqueSampler
>>> import dimod
...
>>> bqm = dimod.generators.ran_r(1, 6)
...
>>> sampler = DWaveCliqueSampler()   
>>> sampler.largest_clique_size > 5  
True
>>> sampleset = sampler.sample(bqm, num_reads=100)   

Properties

DWaveCliqueSampler.largest_clique_size

The maximum number of variables that can be embedded.

DWaveCliqueSampler.qpu_linear_range

Range of linear biases allowed by the QPU.

DWaveCliqueSampler.qpu_quadratic_range

Range of quadratic biases allowed by the QPU.

DWaveCliqueSampler.properties

A dict containing any additional information about the sampler.

DWaveCliqueSampler.parameters

A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter.

DWaveCliqueSampler.target_graph

The QPU topology.

Methods

DWaveCliqueSampler.largest_clique()

The clique embedding with the maximum number of source variables.

DWaveCliqueSampler.sample(bqm[, chain_strength])

Sample from the specified binary quadratic model.

DWaveCliqueSampler.sample_ising(h, J, ...)

Sample from an Ising model using the implemented sample method.

DWaveCliqueSampler.sample_qubo(Q, **parameters)

Sample from a QUBO using the implemented sample method.

LeapHybridSampler

class LeapHybridSampler(**config)[source]

A class for using Leap’s cloud-based hybrid BQM solvers.

Leap’s quantum-classical hybrid BQM solvers are intended to solve arbitrary application problems formulated as binary quadratic models (BQM).

You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in D-Wave Cloud Client.

dwave-cloud-client’s get_solvers() method filters solvers you have access to by solver properties category=hybrid and supported_problem_type=bqm. By default, online hybrid BQM solvers are returned ordered by latest version.

The default specification for filtering and ordering solvers by features is available as default_solver property. Explicitly specifying a solver in a configuration file, an environment variable, or keyword arguments overrides this specification. See the example below on how to extend it instead.

Parameters

**config – Keyword arguments passed to dwave.cloud.client.Client.from_config().

Examples

This example builds a random sparse graph and uses a hybrid solver to find a maximum independent set.

>>> import dimod
>>> import networkx as nx
>>> import dwave_networkx as dnx
>>> import numpy as np
>>> from dwave.system import LeapHybridSampler
...
>>> # Create a maximum-independent set problem from a random graph
>>> problem_node_count = 300
>>> G = nx.random_geometric_graph(problem_node_count, radius=0.0005*problem_node_count)
>>> qubo = dnx.algorithms.independent_set.maximum_weighted_independent_set_qubo(G)
>>> bqm = dimod.BQM.from_qubo(qubo)
...
>>> # Find a good solution
>>> sampler = LeapHybridSampler()       
>>> sampleset = sampler.sample(bqm)     

This example specializes the default solver selection by filtering out bulk BQM solvers. (Bulk solvers are throughput-optimal for heavy/batch workloads, have a higher start-up latency, and are not well suited for live workloads. Not all Leap accounts have access to bulk solvers.)

>>> from dwave.system import LeapHybridSampler
...
>>> solver = LeapHybridSampler.default_solver
>>> solver.update(name__regex=".*(?<!bulk)$")       # name shouldn't end with "bulk"
>>> sampler = LeapHybridSampler(solver=solver)      
>>> sampler.solver        
BQMSolver(id='hybrid_binary_quadratic_model_version2')

Properties

LeapHybridSampler.properties

Solver properties as returned by a SAPI query.

LeapHybridSampler.parameters

Solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in properties for each key.

LeapHybridSampler.default_solver

Methods

LeapHybridSampler.sample(bqm[, time_limit])

Sample from the specified binary quadratic model.

LeapHybridSampler.sample_ising(h, J, ...)

Sample from an Ising model using the implemented sample method.

LeapHybridSampler.sample_qubo(Q, **parameters)

Sample from a QUBO using the implemented sample method.

LeapHybridSampler.min_time_limit(bqm)

Return the minimum time_limit accepted for the given problem.

LeapHybridCQMSampler

class LeapHybridCQMSampler(**config)[source]

A class for using Leap’s cloud-based hybrid CQM solvers.

Leap’s quantum-classical hybrid CQM solvers are intended to solve application problems formulated as constrained quadratic models (CQM).

You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in D-Wave Cloud Client.

dwave-cloud-client’s get_solvers() method filters solvers you have access to by solver properties category=hybrid and supported_problem_type=cqm. By default, online hybrid CQM solvers are returned ordered by latest version.

Parameters

**config – Keyword arguments passed to dwave.cloud.client.Client.from_config().

Examples

This example solves a simple problem of finding the rectangle with the greatest area when the perimeter is limited. In this example, the perimeter of the rectangle is set to 8 (meaning the largest area is for the \(2X2\) square).

A CQM is created that will have two integer variables, \(i, j\), each limited to half the maximum perimeter length of 8, to represent the lengths of the rectangle’s sides:

>>> from dimod import ConstrainedQuadraticModel, Integer
>>> i = Integer('i', upper_bound=4)
>>> j = Integer('j', upper_bound=4)
>>> cqm = ConstrainedQuadraticModel()

The area of the rectangle is given by the multiplication of side \(i\) by side \(j\). The goal is to maximize the area, \(i*j\). Because D-Wave samplers minimize, the objective should have its lowest value when this goal is met. Objective \(-i*j\) has its minimum value when \(i*j\), the area, is greatest:

>>> cqm.set_objective(-i*j)

Finally, the requirement that the sum of both sides must not exceed the perimeter is represented as constraint \(2i + 2j <= 8\):

>>> cqm.add_constraint(2*i+2*j <= 8, "Max perimeter")
'Max perimeter'

Instantiate a hybrid CQM sampler and submit the problem for solution by a remote solver provided by the Leap quantum cloud service:

>>> from dwave.system import LeapHybridCQMSampler   
>>> sampler = LeapHybridCQMSampler()                
>>> sampleset = sampler.sample_cqm(cqm)             
>>> print(sampleset.first)                          
Sample(sample={'i': 2.0, 'j': 2.0}, energy=-4.0, num_occurrences=1,
...            is_feasible=True, is_satisfied=array([ True]))

The best (lowest-energy) solution found has \(i=j=2\) as expected, a solution that is feasible because all the constraints (one in this example) are satisfied.

Properties

LeapHybridCQMSampler.properties

Solver properties as returned by a SAPI query.

LeapHybridCQMSampler.parameters

Solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in properties for each key.

Methods

LeapHybridCQMSampler.sample_cqm(cqm[, ...])

Sample from the specified constrained quadratic model.

LeapHybridCQMSampler.min_time_limit(cqm)

Return the minimum time_limit accepted for the given problem.

LeapHybridDQMSampler

class LeapHybridDQMSampler(**config)[source]

A class for using Leap’s cloud-based hybrid DQM solvers.

Leap’s quantum-classical hybrid DQM solvers are intended to solve arbitrary application problems formulated as discrete quadratic models (DQM).

You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in D-Wave Cloud Client.

dwave-cloud-client’s get_solvers() method filters solvers you have access to by solver properties category=hybrid and supported_problem_type=dqm. By default, online hybrid DQM solvers are returned ordered by latest version.

The default specification for filtering and ordering solvers by features is available as default_solver property. Explicitly specifying a solver in a configuration file, an environment variable, or keyword arguments overrides this specification. See the example in LeapHybridSampler on how to extend it instead.

Parameters

**config – Keyword arguments passed to dwave.cloud.client.Client.from_config().

Examples

This example solves a small, illustrative problem: a game of rock-paper-scissors. The DQM has two variables representing two hands, with cases for rock, paper, scissors. Quadratic biases are set to produce a lower value of the DQM for cases of variable my_hand interacting with cases of variable their_hand such that the former wins over the latter; for example, the interaction of rock-scissors is set to -1 while scissors-rock is set to +1.

>>> import dimod
>>> from dwave.system import LeapHybridDQMSampler
...
>>> cases = ["rock", "paper", "scissors"]
>>> win = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
...
>>> dqm = dimod.DiscreteQuadraticModel()
>>> dqm.add_variable(3, label='my_hand')
'my_hand'
>>> dqm.add_variable(3, label='their_hand')
'their_hand'
>>> for my_idx, my_case in enumerate(cases):
...    for their_idx, their_case in enumerate(cases):
...       if win[my_case] == their_case:
...          dqm.set_quadratic('my_hand', 'their_hand',
...                            {(my_idx, their_idx): -1})
...       if win[their_case] == my_case:
...          dqm.set_quadratic('my_hand', 'their_hand',
...                            {(my_idx, their_idx): 1})
...
>>> dqm_sampler = LeapHybridDQMSampler()      
...
>>> sampleset = dqm_sampler.sample_dqm(dqm)   
>>> print("{} beats {}".format(cases[sampleset.first.sample['my_hand']],
...                            cases[sampleset.first.sample['their_hand']]))   
rock beats scissors

Properties

LeapHybridDQMSampler.properties

Solver properties as returned by a SAPI query.

LeapHybridDQMSampler.parameters

Solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in properties for each key.

LeapHybridDQMSampler.default_solver

Methods

LeapHybridDQMSampler.sample_dqm(dqm[, ...])

Sample from the specified discrete quadratic model.

LeapHybridDQMSampler.min_time_limit(dqm)

Return the minimum time_limit accepted for the given problem.