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 nonblocking: 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 DWave 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 DWave Cloud Client
get_solvers()
. By default, online DWave systems are returned ordered by highest number of qubits.Inherits from
dimod.Sampler
anddimod.Structured
. Parameters
failover (bool, optional, default=False) –
Signal a failover condition if a sampling error occurs. When
True
, raisesFailoverCondition
orRetryCondition
on sampleset resolve to signal failover.Actual failover, i.e. selection of a new solver, has to be handled by the user. A convenience method
trigger_failover()
is available for this. Note that hardware graphs vary between QPUs, so triggering failover results in regeneratednodelist
,edgelist
,properties
andparameters
.retry_interval (number, optional, default=1) –
Ignored, but kept for backward compatibility.
Changed in version 1.16.0: Ignored since 1.16.0. See note for
failover
parameter above.**config – Keyword arguments passed to
dwave.cloud.client.Client.from_config()
.
Note
Prior to version 1.0.0,
DWaveSampler
used thebase
client, allowing nonQPU solvers to be selected. To reproduce the old behavior, instantiateDWaveSampler
withclient='base'
.Examples
This example submits a twovariable Ising problem mapped directly to two adjacent qubits on a DWave system.
qubit_a
is the first qubit in the QPU’s indexed list of qubits andqubit_b
is one of the qubits coupled to it. Other required parameters for communication with the system, such as its URL and an authentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to DWave Solvers. Given sufficient reads (here 100), the quantum computer should return the best solution, \({1, 1}\) onqubit_a
andqubit_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 DWave systems, see DWave System Documentation.
DWave solver properties as returned by a SAPI query. 

DWave 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 

List of active qubits for the DWave solver. 

List of active couplers for the DWave solver. 

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. 

Structure of the structured sampler formatted as a 
Methods¶

Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
Raise an exception if the specified schedule is invalid for the sampler. 

Converts DWaveSampler's structure to a Chimera, Pegasus or Zephyr 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 DWave 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, usingEmbeddingComposite
withDWaveSampler
is preferred.Configuration such as solver selection is similar to that of
DWaveSampler
. Parameters
failover (bool, optional, default=False) –
Signal a failover condition if a sampling error occurs. When
True
, raisesFailoverCondition
orRetryCondition
on sampleset resolve to signal failover.Actual failover, i.e. selection of a new solver, has to be handled by the user. A convenience method
trigger_failover()
is available for this. Note that hardware graphs vary between QPUs, so triggering failover results in regeneratednodelist
,edgelist
,properties
andparameters
.retry_interval (number, optional, default=1) –
Ignored, but kept for backward compatibility.
Changed in version 1.16.0: Ignored since 1.16.0. See note for
failover
parameter above.**config – Keyword arguments, as accepted by
DWaveSampler
Examples
This example creates a BQM based on a 6node clique (complete graph), with random \(\pm 1\) values assigned to nodes, and submits it to a DWave system. Parameters for communication with the system, such as its URL and an authentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to DWave 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¶
The maximum number of variables that can be embedded. 

Range of linear biases allowed by the QPU. 

Range of quadratic biases allowed by the QPU. 

Properties as a dict containing any additional information about the sampler. 

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

The QPU topology. 
Methods¶
The clique embedding with the maximum number of source variables. 


Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
LeapHybridSampler¶
 class LeapHybridSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid BQM solvers.
Leap’s quantumclassical 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 DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=bqm
. By default, online hybrid BQM solvers are returned ordered by latestversion
.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 maximumindependent 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 throughputoptimal for heavy/batch workloads, have a higher startup 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¶
Solver properties as returned by a SAPI query. 

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 

Methods¶

Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
Return the minimum time_limit accepted for the given problem. 
LeapHybridCQMSampler¶
 class LeapHybridCQMSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid CQM solvers.
Leap’s quantumclassical 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 DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=cqm
. By default, online hybrid CQM solvers are returned ordered by latestversion
. 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 DWave 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 (lowestenergy) solution found has \(i=j=2\) as expected, a solution that is feasible because all the constraints (one in this example) are satisfied.
Properties¶
Solver properties as returned by a SAPI query. 

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 
Methods¶

Sample from the specified constrained quadratic model. 
Return the minimum time_limit accepted for the given problem. 
LeapHybridDQMSampler¶
 class LeapHybridDQMSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid DQM solvers.
Leap’s quantumclassical 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 DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=dqm
. By default, online hybrid DQM solvers are returned ordered by latestversion
.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 inLeapHybridSampler
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 rockpaperscissors. 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 variabletheir_hand
such that the former wins over the latter; for example, the interaction ofrockscissors
is set to 1 whilescissorsrock
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¶
Solver properties as returned by a SAPI query. 

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 

Methods¶

Sample from the specified discrete quadratic model. 
Return the minimum time_limit accepted for the given problem. 