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-systempackage); for example, theDWaveSamplerclassSubmitting problems the the Leap service’s hybrid solvers (the
dwave-systempackage); for example, theLeapHybridNLSamplerclassTesting 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,StructuredA 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, raisesFailoverConditionorRetryConditionon 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,propertiesandparameters.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
failoverparameter 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,
DWaveSamplerused thebaseclient, allowing non-QPU solvers to be selected. To reproduce the old behavior, instantiateDWaveSamplerwithclient='base'.Note
The recommended way to use
DWaveSampleris 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_ais the first qubit in the QPU’s indexed list of qubits andqubit_bis 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}\) onqubit_aandqubit_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:
- 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:
- 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
propertiesfor 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.
- 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:
- 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 matchnodelistandedgelist.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:
Examples
This example submits a two-variable Ising problem mapped directly to two adjacent qubits on a D-Wave system.
qubit_ais the first qubit in the QPU’s indexed list of qubits andqubit_bis one of the qubits coupled to it. Given sufficient reads (here 100), the quantum computer should return the best solution, \({1, -1}\) onqubit_aandqubit_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
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- 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.
See also
- 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
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- 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:
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
- valid_bqm_graph(bqm: BinaryQuadraticModel) bool#
Validate that problem defined by
dimod.BinaryQuadraticModelmatches the graph provided by the sampler.- Parameters:
bqm –
dimod.BinaryQuadraticModelobject 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 andsample_qubo()’s warnings kwarg.
- class DWaveCliqueSampler(*, failover: bool = False, retry_interval: Number = -1, **config)[source]#
Bases:
SamplerA 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, usingEmbeddingCompositewithDWaveSampleris 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, raisesFailoverConditionorRetryConditionon 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,propertiesandparameters.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
failoverparameter 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
DWaveCliqueSampleris 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:
- 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:
- 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.
- 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 tolargest_clique_sizevariables. 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_strengthis calculated withuniform_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 thatauto_scaleis 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:
- 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
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- 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.
See also
- 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
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
Hybrid Solvers#
The following samplers are supported:
- class LeapHybridSampler(**config)[source]#
Bases:
_ScopedSamplerMixin,SamplerA 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 propertiescategory=hybridandsupported_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_solverproperty. 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_limitaccepted 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_limitfield underproperties. 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
propertiesfor 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:
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
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- 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.
See also
- 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
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- class LeapHybridCQMSampler(**config)[source]#
Bases:
_ScopedSamplerMixinA 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 propertiescategory=hybridandsupported_problem_type=cqm. By default, online hybrid CQM solvers are returned ordered by latestversion.- 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
propertiesfor 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:
Examples
See the example in
LeapHybridCQMSampler.
- class LeapHybridNLSampler(**config)[source]#
Bases:
_ScopedSamplerMixinA 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 propertiescategory=hybridandsupported_problem_type=nl. By default, online hybrid nonlinear-model solvers are returned ordered by latestversion.- Parameters:
**config – Keyword arguments passed to
from_config().
Examples
This example submits a model for a
flow-shop-schedulingproblem.>>> 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
- 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
propertiesfor 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. Fortime_limitvalues 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
infofield dictionary, which now replaces the previoustimingfield.
- class LeapHybridDQMSampler(**config)[source]#
Bases:
_ScopedSamplerMixinA 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 propertiescategory=hybridandsupported_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_solverproperty. Explicitly specifying a solver in a configuration file, an environment variable, or keyword arguments overrides this specification. See the example inLeapHybridSampleron 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_handinteracting with cases of variabletheir_handsuch that the former wins over the latter; for example, the interaction ofrock-scissorsis set to -1 whilescissors-rockis 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_limitfield underproperties. 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
propertiesfor 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, thenmap_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
compressinstead.**kwargs – Optional keyword arguments for the solver, specified in
parameters.
- Returns:
Sample set constructed from a (non-blocking)
Future-like object.- Return type:
Examples
See the example in
LeapHybridDQMSampler.