Samplers#

A sampler accepts a problem in nonlinear model or quadratic model (e.g., BQM) 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.

QPU Samplers#

Samplers for using the quantum processing unit (QPU) directly.

DWaveSampler#

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

Bases: Sampler, Structured

Submits binary quadratic models directly to D-Wave quantum computers.

Linear and quadratic terms of the binary quadratic model (BQM) must map directly to qubit and coupler indices of the selected QPU. Typically this mapping (minor-embedding) is handled by software (e.g., the EmbeddingComposite class) but for small problems can be manual. 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 the get_solvers() method. By default, online QPUs are returned ordered by highest number of qubits.

Parameters:
  • failover (bool, optional, default=False) –

    Signal a failover condition if a sampling error occurs. When True, raises FailoverCondition or RetryCondition 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 regenerated nodelist, edgelist, properties and parameters.

    Changed in version 1.16.0: In the past, the sample() method was blocking and failover=True caused a solver failover and sampling retry. However, this failover implementation broke when sample() became non-blocking (asynchronous), Setting failover=True had no effect.

  • 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 from_config().

Added in version 1.29.0: Support for context manager protocol.

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'.

Note

The recommended way to use DWaveSampler is from a runtime context:

>>> with DWaveSampler() as sampler:
...     sampler.sample_ising(...)

Alternatively, call the close() method to terminate the sampler resources:

>>> sampler = DWaveSampler()
...
>>> sampler.close()

Examples

This example submits a two-variable Ising problem mapped directly to two adjacent qubits on a QPU. 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 authentication token, are implicitly set in a configuration file or as environment variables, as described in the Configuring Access to the Leap Service (Basic) section. 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
...
>>> with DWaveSampler() as sampler:
...     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)
...     print(sampleset.first.sample[qubit_a] == 1 and sampleset.first.sample[qubit_b] == -1)
True

For additional examples, see:

Properties#

edgelist

List of active couplers for the solver.

nodelist

List of active qubits for the solver.

parameters

Supported parameters.

properties

Solver properties as returned by a SAPI query.

warnings_default

Defines default behavior for warnings keyword arguments of the sample_ising() and sample_qubo() methods.

See also inherited properties of the DWaveSampler class.

Methods#

close()

Close the underlying cloud client to release system resources such as threads.

sample(bqm[, warnings])

Sample from the specified binary quadratic model.

to_networkx_graph()

Output the QPU's working graph in NetworkX format.

trigger_failover()

Trigger a failover and connect to a new solver.

validate_anneal_schedule(anneal_schedule)

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

See also inherited methods of the DWaveSampler class.

DWaveCliqueSampler#

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

Bases: Sampler

Submits clique binary quadratic models to D-Wave quantum computers.

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

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

Clique embeddings are cached for each QPU but the initial finding of embeddings can take several minutes.

Parameters:
  • failover (bool, optional, default=False) –

    Signal a failover condition if a sampling error occurs. When True, raises FailoverCondition or RetryCondition 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 regenerated nodelist, edgelist, properties and parameters.

    Changed in version 1.16.0: In the past, the sample() method was blocking and failover=True caused a solver failover and sampling retry. However, this failover implementation broke when sample() became non-blocking (asynchronous), Setting failover=True had no effect.

  • 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.

Added in version 1.29.0: Support for context manager protocol.

Note

The recommended way to use DWaveCliqueSampler is from a runtime context:

>>> with DWaveCliqueSampler() as sampler:
...     sampler.sample(...)

Alternatively, call the close() method to terminate the sampler resources:

>>> sampler = DWaveCliqueSampler()
...
>>> sampler.close()

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 authentication token, are implicitly set in a configuration file or as environment variables, as described in the Configuring Access to the Leap Service (Basic) section.

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

See also

busgraph_cache.

Properties#

largest_clique_size

Maximum number of variables that can be embedded.

parameters

Supported parameters.

properties

Solver properties as returned by a SAPI query.

qpu_linear_range

Range of linear biases allowed by the QPU.

qpu_quadratic_range

Range of quadratic biases allowed by the QPU.

target_graph

Selected QPU's working graph in NetworkX format.

See also inherited properties of the DWaveCliqueSampler class.

Methods#

clique(variables)

Return a clique embedding of the given size.

close()

Close the child sampler to release system resources such as threads.

largest_clique()

Return the clique embedding with the maximum number of variables.

sample(bqm[, chain_strength])

Sample from the specified binary quadratic model.

trigger_failover()

Trigger a failover and connect to a new solver.

See also inherited methods of the DWaveCliqueSampler class.

Stride Hybrid Solver#

The Leap service’s quantum-classical nonlinear hybrid solver for optimizing business problems.

StrideHybridSolver#

class StrideHybridSolver(**config)[source]#

Submits nonlinear models to the Stride™ hybrid solver in the Leap service.

The Leap service’s quantum-classical hybrid nonlinear model solver, also known as the Stride hybrid solver, is intended to solve arbitrary application problems formulated as nonlinear models.

You can configure your solver selection as described in the Configuration section.[1]

Parameters:

**config – Keyword arguments passed to from_config().

Examples

This example submits a model for a flow-shop-scheduling problem.

>>> from dwave.optimization.generators import flow_shop_scheduling
>>> from dwave.system import StrideHybridSolver
...
>>> with StrideHybridSolver() as sampler:
...     processing_times = [[10, 5, 7], [20, 10, 15]]
...     model = flow_shop_scheduling(processing_times=processing_times)
...     results = sampler.sample(model, label="Small FSS problem")
...     job_order = next(model.iter_decisions())
...     print(f"State 0 of {model.objective.state_size()} has an "
...           f"objective value {model.objective.state(0)} for order "
...           f"{job_order.state(0)}.")
State 0 of 8 has an objective value 50.0 for order [1. 2. 0.].

Added in version 1.35.0: The LeapHybridNLSampler class was made an alias for the StrideHybridSolver class.

Properties#

default_solver

parameters

Supported parameters.

properties

Solver properties as returned by a SAPI query.

Methods#

close()

Close the underlying cloud client to release system resources such as threads.

estimated_min_time_limit(nlm)

Return the minimum required time, in seconds, estimated for the given problem.

sample(model[, time_limit])

Sample from the specified nonlinear model.

LeapHybridNLSampler#

LeapHybridNLSampler[source]#

alias of StrideHybridSolver

Other Hybrid Solvers#

Additional hybrid solvers in the Leap service.

LeapHybridSampler#

class LeapHybridSampler(**config)[source]#

Bases: _ScopedSamplerMixin, Sampler

Submits binary quadratic models to a hybrid solver in the Leap service.

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

You can configure your solver selection as described in the Configuration section.[2]

Parameters:

**config – Keyword arguments passed to from_config().

Examples

This example samples a randomly generated binary quadratic model with 10 variables and 15 interactions.

>>> from dimod.generators import gnm_random_bqm
>>> from dwave.system import LeapHybridSampler
...
>>> bqm = gnm_random_bqm(10, 15, 'SPIN')
>>> with LeapHybridSampler() as sampler:
...     sampleset = sampler.sample(bqm)

Properties#

default_solver

parameters

Supported parameters.

properties

Solver properties as returned by a SAPI query.

See also inherited properties of the LeapHybridSampler class.

Methods#

close()

Close the underlying cloud client to release system resources such as threads.

min_time_limit(bqm)

Return the minimum time_limit accepted for the given problem.

sample(bqm[, time_limit])

Sample from the specified binary quadratic model.

See also inherited methods of the LeapHybridSampler class.

LeapHybridCQMSampler#

class LeapHybridCQMSampler(**config)[source]#

Submits constrained quadratic models to a hybrid solver in the Leap service.

The Leap service’s quantum-classical hybrid constrained quadratic model (CQM) solvers are intended to solve arbitrary application problems formulated as CQMs.

You can configure your solver selection as described in the Configuration section.[3]

Parameters:

**config – Keyword arguments passed to 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
>>> with LeapHybridCQMSampler() as sampler:
...     sampleset = sampler.sample_cqm(cqm)
...     feasible_results = sampleset.filter(lambda d: d.is_feasible)
...     print(feasible_results.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#

default_solver

properties

Solver properties as returned by a SAPI query.

parameters

Supported parameters.

Methods#

close()

Close the underlying cloud client to release system resources such as threads.

min_time_limit(cqm)

Return the minimum time_limit, in seconds, accepted for the given problem.

sample_cqm(cqm[, time_limit])

Sample from the specified constrained quadratic model.

LeapHybridDQMSampler#

class LeapHybridDQMSampler(**config)[source]#

Submits discrete quadratic models to a hybrid solver in the Leap service.

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

You can configure your solver selection as described in the Configuration section.[4]

Parameters:

**config – Keyword arguments passed to 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})
...
>>> with LeapHybridDQMSampler() as dqm_sampler:
...     sampleset = dqm_sampler.sample_dqm(dqm)
...     print(f"{} beats {}".format(cases[sampleset.first.sample['my_hand']],
...                                 cases[sampleset.first.sample['their_hand']]))
rock beats scissors

Properties#

default_solver

parameters

Solver parameters as returned by a SAPI query.

properties

Solver properties as returned by a SAPI query.

Methods#

min_time_limit(dqm)

Return the minimum time_limit accepted for the given problem.

sample_dqm(dqm[, time_limit, compress, ...])

Sample from the specified discrete quadratic model.