Samplers#

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

The Ocean SDK provides samplers for various uses.

  • Submitting problems directly to a quantum computer (the dwave-system package); for example, the DWaveSampler class

  • Submitting problems the the Leap service’s hybrid solvers (the dwave-system package); for example, the LeapHybridNLSampler class

  • Testing your code (the dimod package)

  • Solving problems classically (the dwave-samplers package)

QPU Samplers#

The following samplers are supported:

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

Bases: Sampler, Structured

A class for using D-Wave quantum computers as samplers 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 the D-Wave Cloud Client package’s get_solvers() method. By default, online D-Wave systems 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 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 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

See the Concepts section for explanations of technical terms in descriptions of Ocean tools.

property adjacency: dict[Hashable, set]#

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.

close()[source]#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

property edgelist#

List of active couplers for the D-Wave solver.

Examples

First 5 entries of the coupler list for one Advantage system.

>>> from dwave.system import DWaveSampler
>>> with DWaveSampler() as sampler:     
...     sampler.edgelist[:5]
[(30, 31), (30, 45), (30, 2940), (30, 2955), (30, 2970)]

See the Concepts section for explanations of technical terms in descriptions of Ocean tools.

Type:

list

property nodelist#

List of active qubits for the D-Wave solver.

Examples

First 5 entries of the node list for one Advantage system.

>>> from dwave.system import DWaveSampler
>>> with DWaveSampler() as sampler:     
...     sampler.nodelist[:5]
[30, 31, 32, 33, 34]

See the Concepts section for explanations of technical terms in descriptions of Ocean tools.

Type:

list

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

Solver parameters are dependent on the selected D-Wave solver and subject to change; for example, new released features may add parameters. The QPU Solver Properties and QPU Solver Parameters sections describe the parameters and properties supported on the D-Wave system.

Examples

>>> from dwave.system import DWaveSampler
>>> with DWaveSampler() as sampler:     
...     sampler.parameters
{'anneal_offsets': ['parameters'],
 'anneal_schedule': ['parameters'],
 'annealing_time': ['parameters'],
 'answer_mode': ['parameters'],
 'auto_scale': ['parameters'],
 # Snipped above response for brevity

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

Type:

dict[str, list]

property properties#

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

Solver properties are dependent on the selected D-Wave solver and subject to change; for example, new released features may add properties. The QPU Solver Properties and QPU Solver Parameters sections describe the parameters and properties supported on the D-Wave system.

Examples

>>> from dwave.system import DWaveSampler
>>> with DWaveSampler() as sampler:     
...     sampler.properties
{'anneal_offset_ranges': [[-0.2197463755538704, 0.03821687759418928],
  [-0.2242514597680286, 0.01718456460967399],
  [-0.20860153999435985, 0.05511969218508182],
# Snipped above response for brevity

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

Type:

dict

remove_unknown_kwargs(**kwargs) dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters:

**kwargs – Keyword arguments to be validated.

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm, warnings=None, **kwargs)[source]#

Sample from the specified binary quadratic model.

Parameters:
  • bqm (BinaryQuadraticModel) – The binary quadratic model. Must match nodelist and edgelist.

  • warnings (WarningAction, optional) – Defines what warning action to take, if any (see the Warnings section). The default behavior is to ignore warnings.

  • **kwargs – Optional keyword arguments for the sampling method, specified per solver in parameters. The QPU Solver Properties and QPU Solver Parameters sections describe the parameters and properties supported on the D-Wave system.

Returns:

Sample set constructed from a (non-blocking) Future-like object. In it this sampler also provides timing information in the info field as described in the SAPI Timing Fields section.

Return type:

SampleSet

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

See the Concepts section for explanations of technical terms in descriptions of Ocean tools.

sample_ising(h, *args, **kwargs)[source]#

Sample from an Ising model using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the Ising model into a BinaryQuadraticModel and then calls sample().

Parameters:
  • h – Linear biases of the Ising problem. If a list, indices are the variable labels.

  • J – Quadratic biases of the Ising problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from the Ising model.

sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#

Sample from a QUBO using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the quadratic unconstrained binary optimization (QUBO) into a BinaryQuadraticModel and then calls sample().

Parameters:
  • Q – Coefficients of a QUBO problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from a QUBO.

property structure: _Structure#

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

to_networkx_graph()[source]#

Converts DWaveSampler’s structure to a Chimera, Pegasus or Zephyr NetworkX graph.

Returns:

Either a Chimera lattice of shape [m, n, t], a Pegasus lattice of shape [m] or a Zephyr lattice of size [m,t].

Return type:

networkx.Graph

Examples

This example converts a selected D-Wave system solver to a graph and verifies it has over 5000 nodes.

>>> from dwave.system import DWaveSampler
...
>>> with DWaveSampler() as sampler:         
...     g = sampler.to_networkx_graph()
...     len(g.nodes) > 5000
True
trigger_failover()[source]#

Trigger a failover and connect to a new solver.

valid_bqm_graph(bqm: BinaryQuadraticModel) bool#

Validate that problem defined by dimod.BinaryQuadraticModel matches the graph provided by the sampler.

Parameters:

bqmdimod.BinaryQuadraticModel object to validate.

Returns:

Boolean indicating validity of BQM graph compared to sampler graph.

validate_anneal_schedule(anneal_schedule)[source]#

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

Parameters:

anneal_schedule (list) – An anneal schedule variation is defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first element in the pair is time t in microseconds; the second, normalized persistent current s in the range [0,1]. The resulting schedule is the piecewise-linear curve that connects the provided points.

Raises:
  • ValueError – If the schedule violates any of the conditions listed below.

  • RuntimeError – If the sampler does not accept the anneal_schedule parameter or if it does not have annealing_time_range or max_anneal_schedule_points properties.

As described in the QPU Solver Properties section, an anneal schedule must satisfy the following conditions:

  • Time t must increase for all points in the schedule.

  • For forward annealing, the first point must be (0,0) and the anneal fraction s must increase monotonically.

  • For reverse annealing, the anneal fraction s must start and end at s=1.

  • In the final point, anneal fraction s must equal 1 and time t must not exceed the maximum value in the annealing_time_range property.

  • The number of points must be >=2.

  • The upper bound is system-dependent; check the max_anneal_schedule_points property. For reverse annealing, the maximum number of points allowed is one more than the number given by this property.

Examples

This example sets a quench schedule on a D-Wave system.

>>> from dwave.system import DWaveSampler
>>> with DWaveSampler() as sampler:     
...     quench_schedule=[[0.0, 0.0], [12.0, 0.6], [12.8, 1.0]]
...     DWaveSampler().validate_anneal_schedule(quench_schedule)
warnings_default = 'ignore'#

Defines the default behavior for sample_ising()’s and sample_qubo()’s warnings kwarg.

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

Bases: Sampler

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

>>> from dwave.system import DWaveCliqueSampler
>>> import dimod
...
>>> 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
clique(variables)[source]#

Return a clique embedding of the given size.

Parameters:

variables (int/collection) – Source variables. If an integer, the variables embedded are labelled [0,n).

Returns:

The clique embedding.

Return type:

dict

close()[source]#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

largest_clique()[source]#

The clique embedding with the maximum number of source variables.

Returns:

The clique embedding with the maximum number of source variables.

Return type:

dict

property largest_clique_size: int#

The maximum number of variables that can be embedded.

property parameters: dict#

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.

property properties: dict#

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

property qpu_linear_range: Tuple[float, float]#

Range of linear biases allowed by the QPU.

property qpu_quadratic_range: Tuple[float, float]#

Range of quadratic biases allowed by the QPU.

remove_unknown_kwargs(**kwargs) dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters:

**kwargs – Keyword arguments to be validated.

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm, chain_strength=None, **kwargs)[source]#

Sample from the specified binary quadratic model.

Parameters:
  • bqm (BinaryQuadraticModel) – Any binary quadratic model with up to largest_clique_size variables. This BQM is embedded using a clique embedding.

  • chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default, chain_strength is calculated with uniform_torque_compensation().

  • **kwargs – Optional keyword arguments for the sampling method, specified per solver in parameters. The QPU Solver Properties and QPU Solver Parameters sections describe the parameters and properties supported on the D-Wave system. Note that auto_scale is not supported by this sampler, because it scales the problem as part of the embedding process.

Returns:

Sample set constructed from a (non-blocking) Future-like object.

Return type:

SampleSet

sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#

Sample from an Ising model using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the Ising model into a BinaryQuadraticModel and then calls sample().

Parameters:
  • h – Linear biases of the Ising problem. If a list, indices are the variable labels.

  • J – Quadratic biases of the Ising problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from the Ising model.

sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#

Sample from a QUBO using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the quadratic unconstrained binary optimization (QUBO) into a BinaryQuadraticModel and then calls sample().

Parameters:
  • Q – Coefficients of a QUBO problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from a QUBO.

property target_graph: Graph#

The QPU topology.

trigger_failover()[source]#

Trigger a failover and connect to a new solver.

Hybrid Solvers#

The following samplers are supported:

class LeapHybridSampler(**config)[source]#

Bases: _ScopedSamplerMixin, Sampler

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

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

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 the D-Wave Cloud Client package.

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 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
>>> with LeapHybridSampler() as sampler:    
...     sampleset = sampler.sample(bqm)
close()#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

min_time_limit(bqm)[source]#

Return the minimum time_limit accepted for the given problem.

The minimum time for a hybrid BQM solver is specified as a piecewise-linear curve defined by a set of floating-point pairs, the minimum_time_limit field under properties. The first element in each pair is the number of problem variables; the second is the minimum required time. The minimum time for any number of variables is a linear interpolation calculated on two pairs that represent the relevant range for the given number of variables.

Examples

For a solver where LeapHybridSampler().properties[“minimum_time_limit”] returns [[1, 0.1], [100, 10.0], [1000, 20.0]], the minimum time for a problem of 50 variables is 5 seconds (the linear interpolation of the first two pairs that represent problems with between 1 to 100 variables).

property parameters: Dict[str, list]#

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.

Solver parameters are dependent on the selected solver and subject to change.

property properties: Dict[str, Any]#

Solver properties as returned by a SAPI query.

Solver properties are dependent on the selected solver and subject to change.

remove_unknown_kwargs(**kwargs) dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters:

**kwargs – Keyword arguments to be validated.

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm, time_limit=None, **kwargs)[source]#

Sample from the specified binary quadratic model.

Parameters:
  • bqm (dimod.BinaryQuadraticModel) – Binary quadratic model.

  • time_limit (int) –

    Maximum run time, in seconds, to allow the solver to work on the problem. Must be at least the minimum required for the number of problem variables, which is calculated and set by default.

    min_time_limit() calculates (and describes) the minimum time for your problem.

  • **kwargs – Optional keyword arguments for the solver, specified in parameters.

Returns:

Sample set constructed from a (non-blocking) Future-like object.

Return type:

SampleSet

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
...
>>> # 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
>>> with LeapHybridSampler() as sampler:    
...     sampleset = sampler.sample(bqm)
sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#

Sample from an Ising model using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the Ising model into a BinaryQuadraticModel and then calls sample().

Parameters:
  • h – Linear biases of the Ising problem. If a list, indices are the variable labels.

  • J – Quadratic biases of the Ising problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from the Ising model.

sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#

Sample from a QUBO using the implemented sample method.

This method is inherited from the Sampler base class.

Converts the quadratic unconstrained binary optimization (QUBO) into a BinaryQuadraticModel and then calls sample().

Parameters:
  • Q – Coefficients of a QUBO problem.

  • **kwargs – See the implemented sampling for additional keyword definitions.

Returns: Samples from a QUBO.

class LeapHybridCQMSampler(**config)[source]#

Bases: _ScopedSamplerMixin

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 the D-Wave Cloud Client package.

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

close()#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

min_time_limit(cqm: ConstrainedQuadraticModel) float[source]#

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

property parameters: Dict[str, List[str]]#

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.

Solver parameters are dependent on the selected solver and subject to change.

property properties: Dict[str, Any]#

Solver properties as returned by a SAPI query.

Solver properties are dependent on the selected solver and subject to change.

sample_cqm(cqm: ConstrainedQuadraticModel, time_limit: float | None = None, **kwargs)[source]#

Sample from the specified constrained quadratic model.

Parameters:
  • cqm (dimod.ConstrainedQuadraticModel) – Constrained quadratic model (CQM).

  • time_limit (int, optional) –

    Maximum run time, in seconds, to allow the solver to work on the problem. Must be at least the minimum required for the problem, which is calculated and set by default.

    min_time_limit() calculates (and describes) the minimum time for your problem.

  • **kwargs – Optional keyword arguments for the solver, specified in parameters.

Returns:

Sample set constructed from a (non-blocking) Future-like object.

Return type:

SampleSet

Examples

See the example in LeapHybridCQMSampler.

class LeapHybridNLSampler(**config)[source]#

Bases: _ScopedSamplerMixin

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

Leap’s quantum-classical hybrid nonlinear-model solvers are intended to solve application problems formulated as nonlinear 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, as described in the D-Wave Cloud Client package.

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

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 LeapHybridNLSampler
...
>>> with LeapHybridNLSampler() 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.].
class SampleResult(model, info)[source]#

Bases: NamedTuple

count(value, /)#

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)#

Return first index of value.

Raises ValueError if the value is not present.

info: ResultInfoDict#

Alias for field number 1

model: Model#

Alias for field number 0

close()[source]#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

estimated_min_time_limit(nlm: Model) float[source]#

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

Runtime (and charge time) is not guaranteed to be shorter than this minimum time.

property parameters: Dict[str, List[str]]#

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.

Solver parameters are dependent on the selected solver and subject to change.

property properties: Dict[str, Any]#

Solver properties as returned by a SAPI query.

Solver properties are dependent on the selected solver and subject to change.

sample(model: Model, time_limit: float | None = None, **kwargs) concurrent.futures.Future[SampleResult][source]#

Sample from the specified nonlinear model.

Parameters:
  • model (Model) – Nonlinear model.

  • time_limit (float, optional) –

    Maximum runtime, in seconds, the solver should work on the problem. Should be at least the estimated minimum required for the problem, which is calculated and set by default.

    estimated_min_time_limit() estimates the minimum time for your problem. For time_limit values shorter than the estimated minimum, runtime (and charge time) is not guaranteed to be shorter than the estimated time.

  • **kwargs – Optional keyword arguments for the solver, specified in parameters.

Returns:

Named tuple, in a Future, containing the nonlinear model and general result information such as timing and the identity of the problem data.

Return type:

Future [SampleResult]

Changed in version 1.31.0: The return value includes timing information as part of the info field dictionary, which now replaces the previous timing field.

class LeapHybridDQMSampler(**config)[source]#

Bases: _ScopedSamplerMixin

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 the D-Wave Cloud Client package.

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 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
close()#

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

Note

The method blocks for all the currently scheduled work (sampling requests) to finish.

See: close().

min_time_limit(dqm)[source]#

Return the minimum time_limit accepted for the given problem.

The minimum time for a hybrid DQM solver is specified as a piecewise-linear curve defined by a set of floating-point pairs, the minimum_time_limit field under properties. The first element in each pair is a combination of the numbers of interactions, variables, and cases that reflects the “density” of connectivity between the problem’s variables; the second is the minimum required time. The minimum time for any particular problem size is a linear interpolation calculated on two pairs that represent the relevant range for the given problem.

Examples

For a solver where LeapHybridDQMSampler().properties[“minimum_time_limit”] returns [[1, 0.1], [100, 10.0], [1000, 20.0]], the minimum time for a problem of “density” 50 is 5 seconds (the linear interpolation of the first two pairs that represent problems with “density” between 1 to 100).

property parameters: Dict[str, list]#

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.

Solver parameters are dependent on the selected solver and subject to change.

property properties: Dict[str, Any]#

Solver properties as returned by a SAPI query.

Solver properties are dependent on the selected solver and subject to change.

sample_dqm(dqm, time_limit=None, compress=False, compressed=None, **kwargs)[source]#

Sample from the specified discrete quadratic model.

Parameters:
  • dqm (dimod.DiscreteQuadraticModel) –

    Discrete quadratic model (DQM).

    Note that if dqm is a dimod.CaseLabelDQM, then map_sample() will need to be used to restore the case labels in the returned sample set.

  • time_limit (int, optional) –

    Maximum run time, in seconds, to allow the solver to work on the problem. Must be at least the minimum required for the number of problem variables, which is calculated and set by default.

    min_time_limit() calculates (and describes) the minimum time for your problem.

  • compress (binary, optional) – Compresses the DQM data when set to True. Use if your problem somewhat exceeds the maximum allowed size. Compression tends to be slow and more effective on homogenous data, which in this case means it is more likely to help on DQMs with many identical integer-valued biases than ones with random float-valued biases, for example.

  • compressed (binary, optional) – Deprecated; please use compress instead.

  • **kwargs – Optional keyword arguments for the solver, specified in parameters.

Returns:

Sample set constructed from a (non-blocking) Future-like object.

Return type:

SampleSet

Examples

See the example in LeapHybridDQMSampler.