dwavesystem¶
dwavesystem is a basic API for easily incorporating the DWave system as a
sampler in the
DWave Ocean software stack,
directly or through Leap‘s cloudbased
hybrid solvers. It includes DWaveSampler
, a dimod sampler that accepts and
passes system parameters such as system identification and authentication down
the stack, LeapHybridSampler
, for Leap’s hybrid solvers, and other. It also
includes several useful composites—layers of pre and postprocessing—that
can be used with DWaveSampler
to handle minorembedding,
optimize chain strength, etc.
Documentation¶
 Date
Nov 15, 2021
Note
This documentation is for the latest version of dwavesystem. Documentation for the version currently installed by dwaveoceansdk is here: dwavesystem.
Introduction¶
dwavesystem enables easy incorporation of the DWave system as a sampler
in either a hybrid quantumclassical solution, using
LeapHybridSampler()
, for example, or
dwavehybrid samplers such as
KerberosSampler
, or directly using
DWaveSampler()
.
Note
For applications that require detailed control on communication with the remote compute resource (a DWave QPU or Leap’s hybrid solvers), see dwavecloudclient.
DWave System Documentation describes DWave quantum computers and Leap hybrid solvers, including features, parameters, and properties. It also provides guidance on programming the DWave system, including how to formulate problems and configure parameters.
Example¶
This example solves a small example of a known graph problem, minimum
vertex cover. It uses the NetworkX
graphic package to create the problem, Ocean’s dwave_networkx
to formulate the graph problem as a BQM, and dwavesystem’s
DWaveSampler()
to use a DWave system as the sampler.
dwavesystem’s EmbeddingComposite()
handles mapping
between the problem graph to the DWave system’s numerically indexed qubits,
a mapping known as minorembedding.
>>> import networkx as nx
>>> import dwave_networkx as dnx
>>> from dwave.system import DWaveSampler, EmbeddingComposite
...
>>> s5 = nx.star_graph(4) # a star graph where node 0 is hub to four other nodes
>>> sampler = EmbeddingComposite(DWaveSampler())
>>> print(dnx.min_vertex_cover(s5, sampler))
[0]
Reference Documentation¶
Samplers¶
A sampler accepts a problem in binary quadratic model (BQM) or discrete quadratic model (DQM) format and returns variable assignments. Samplers generally try to find minimizing values but can also sample from distributions defined by the problem.
These samplers are nonblocking: the returned SampleSet
is constructed
from a Future
like object that is resolved on the first
read of any of its properties; for example, by printing the results. Your code can
query its status with the done()
method or ensure resolution
with the resolve()
method.
Other Ocean packages provide additional samplers; for example, dimod provides samplers for testing your code.
DWaveSampler¶
 class DWaveSampler(failover=False, retry_interval= 1, **config)[source]¶
A class for using the DWave system as a sampler for binary quadratic models.
You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments. For more information, see DWave Cloud Client
get_solvers()
. By default, online DWave systems are returned ordered by highest number of qubits.Inherits from
dimod.Sampler
anddimod.Structured
. Parameters
failover (bool, optional, default=False) – Switch to a new QPU in the rare event that the currently connected system goes offline. Note that different QPUs may have different hardware graphs and a failover will result in a regenerated
nodelist
,edgelist
,properties
andparameters
.retry_interval (number, optional, default=1) – The amount of time (in seconds) to wait to poll for a solver in the case that no solver is found. If retry_interval is negative then it will instead propogate the SolverNotFoundError to the user.
**config – Keyword arguments passed to
dwave.cloud.client.Client.from_config()
.
Note
Prior to version 1.0.0,
DWaveSampler
used thebase
client, allowing nonQPU solvers to be selected. To reproduce the old behavior, instantiateDWaveSampler
withclient='base'
.Examples
This example submits a twovariable Ising problem mapped directly to two adjacent qubits on a DWave system.
qubit_a
is the first qubit in the QPU’s indexed list of qubits andqubit_b
is one of the qubits coupled to it. Other required parameters for communication with the system, such as its URL and an autentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to DWave Solvers. Given sufficient reads (here 100), the quantum computer should return the best solution, \({1, 1}\) onqubit_a
andqubit_b
, respectively, as its first sample (samples are ordered from lowest energy).>>> from dwave.system import DWaveSampler ... >>> sampler = DWaveSampler() ... >>> qubit_a = sampler.nodelist[0] >>> qubit_b = next(iter(sampler.adjacency[qubit_a])) >>> sampleset = sampler.sample_ising({qubit_a: 1, qubit_b: 1}, ... {}, ... num_reads=100) >>> sampleset.first.sample[qubit_a] == 1 and sampleset.first.sample[qubit_b] == 1 True
See Ocean Glossary for explanations of technical terms in descriptions of Ocean tools.
Properties¶
For parameters and properties of DWave systems, see DWave System Documentation.
DWave solver properties as returned by a SAPI query. 

DWave solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in 

List of active qubits for the DWave solver. 

List of active couplers for the DWave solver. 

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

Structure of the structured sampler formatted as a 
Methods¶

Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

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

Converts DWaveSampler's structure to a Chimera or Pegasus NetworkX graph. 
DWaveCliqueSampler¶
 class DWaveCliqueSampler(*, failover: bool = False, retry_interval: numbers.Number =  1, **config)[source]¶
A sampler for solving clique binary quadratic models on the DWave system.
This sampler wraps
find_clique_embedding()
to generate embeddings with even chain length. These embeddings work well for dense binary quadratic models. For sparse models, usingEmbeddingComposite
withDWaveSampler
is preferred.Configuration such as solver selection is similar to that of
DWaveSampler
. Parameters
failover (optional, default=False) – Switch to a new QPU in the rare event that the currently connected system goes offline. Note that different QPUs may have different hardware graphs and a failover will result in a regenerated
nodelist
,edgelist
,properties
andparameters
.retry_interval (optional, default=1) – The amount of time (in seconds) to wait to poll for a solver in the case that no solver is found. If retry_interval is negative then it will instead propogate the SolverNotFoundError to the user.
**config – Keyword arguments, as accepted by
DWaveSampler
Examples
This example creates a BQM based on a 6node clique (complete graph), with random \(\pm 1\) values assigned to nodes, and submits it to a DWave system. Parameters for communication with the system, such as its URL and an autentication token, are implicitly set in a configuration file or as environment variables, as described in Configuring Access to DWave Solvers.
>>> from dwave.system import DWaveCliqueSampler >>> import dimod ... >>> bqm = dimod.generators.ran_r(1, 6) ... >>> sampler = DWaveCliqueSampler() >>> sampler.largest_clique_size > 5 True >>> sampleset = sampler.sample(bqm, num_reads=100)
Properties¶
The maximum number of variables that can be embedded. 

Range of linear biases allowed by the QPU. 

Range of quadratic biases allowed by the QPU. 

A dict containing any additional information about the sampler. 

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

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


Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
LeapHybridSampler¶
 class LeapHybridSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid BQM solvers.
Leap’s quantumclassical hybrid BQM solvers are intended to solve arbitrary application problems formulated as binary quadratic models (BQM).
You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=bqm
. By default, online hybrid BQM solvers are returned ordered by latestversion
.The default specification for filtering and ordering solvers by features is available as
default_solver
property. Explicitly specifying a solver in a configuration file, an environment variable, or keyword arguments overrides this specification. See the example below on how to extend it instead. Parameters
**config – Keyword arguments passed to
dwave.cloud.client.Client.from_config()
.
Examples
This example builds a random sparse graph and uses a hybrid solver to find a maximum independent set.
>>> import dimod >>> import networkx as nx >>> import dwave_networkx as dnx >>> import numpy as np >>> from dwave.system import LeapHybridSampler ... >>> # Create a maximumindependent set problem from a random graph >>> problem_node_count = 300 >>> G = nx.random_geometric_graph(problem_node_count, radius=0.0005*problem_node_count) >>> qubo = dnx.algorithms.independent_set.maximum_weighted_independent_set_qubo(G) >>> bqm = dimod.BQM.from_qubo(qubo) ... >>> # Find a good solution >>> sampler = LeapHybridSampler() >>> sampleset = sampler.sample(bqm)
This example specializes the default solver selection by filtering out bulk BQM solvers. (Bulk solvers are throughputoptimal for heavy/batch workloads, have a higher startup latency, and are not well suited for live workloads. Not all Leap accounts have access to bulk solvers.)
>>> from dwave.system import LeapHybridSampler ... >>> solver = LeapHybridSampler.default_solver >>> solver.update(name__regex=".*(?<!bulk)$") # name shouldn't end with "bulk" >>> sampler = LeapHybridSampler(solver=solver) >>> sampler.solver BQMSolver(id='hybrid_binary_quadratic_model_version2')
Properties¶
Solver properties as returned by a SAPI query. 

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

Methods¶

Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
Return the minimum time_limit accepted for the given problem. 
LeapHybridCQMSampler¶
 class LeapHybridCQMSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid CQM solvers.
Leap’s quantumclassical hybrid CQM solvers are intended to solve application problems formulated as constrained quadratic models (CQM).
You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=cqm
. By default, online hybrid CQM solvers are returned ordered by latestversion
. Parameters
**config – Keyword arguments passed to
dwave.cloud.client.Client.from_config()
.
Examples
This example solves a simple problem of finding the rectangle with the greatest area when the perimeter is limited. In this example, the perimeter of the rectangle is set to 8 (meaning the largest area is for the \(2X2\) square).
A CQM is created that will have two integer variables, \(i, j\), each limited to half the maximum perimeter length of 8, to represent the lengths of the rectangle’s sides:
>>> from dimod import ConstrainedQuadraticModel, Integer >>> i = Integer('i', upper_bound=4) >>> j = Integer('j', upper_bound=4) >>> cqm = ConstrainedQuadraticModel()
The area of the rectangle is given by the multiplication of side \(i\) by side \(j\). The goal is to maximize the area, \(i*j\). Because DWave samplers minimize, the objective should have its lowest value when this goal is met. Objective \(i*j\) has its minimum value when \(i*j\), the area, is greatest:
>>> cqm.set_objective(i*j)
Finally, the requirement that the sum of both sides must not exceed the perimeter is represented as constraint \(2i + 2j <= 8\):
>>> cqm.add_constraint(2*i+2*j <= 8, "Max perimeter") 'Max perimeter'
Instantiate a hybrid CQM sampler and submit the problem for solution by a remote solver provided by the Leap quantum cloud service:
>>> from dwave.system import LeapHybridCQMSampler >>> sampler = LeapHybridCQMSampler() >>> sampleset = sampler.sample_cqm(cqm) >>> print(sampleset.first) Sample(sample={'i': 2.0, 'j': 2.0}, energy=4.0, num_occurrences=1, ... is_feasible=True, is_satisfied=array([ True]))
The best (lowestenergy) solution found has \(i=j=2\) as expected, a solution that is feasible because all the constraints (one in this example) are satisfied.
Properties¶
Solver properties as returned by a SAPI query. 

Solver parameters in the form of a dict, where keys are keyword parameters accepted by a SAPI query and values are lists of properties in 
Methods¶

Sample from the specified constrained quadratic model. 
Return the minimum time_limit accepted for the given problem. 
LeapHybridDQMSampler¶
 class LeapHybridDQMSampler(**config)[source]¶
A class for using Leap’s cloudbased hybrid DQM solvers.
Leap’s quantumclassical hybrid DQM solvers are intended to solve arbitrary application problems formulated as discrete quadratic models (DQM).
You can configure your solver selection and usage by setting parameters, hierarchically, in a configuration file, as environment variables, or explicitly as input arguments, as described in DWave Cloud Client.
dwavecloudclient’s
get_solvers()
method filters solvers you have access to by solver propertiescategory=hybrid
andsupported_problem_type=dqm
. By default, online hybrid DQM solvers are returned ordered by latestversion
.The default specification for filtering and ordering solvers by features is available as
default_solver
property. Explicitly specifying a solver in a configuration file, an environment variable, or keyword arguments overrides this specification. See the example inLeapHybridSampler
on how to extend it instead. Parameters
**config – Keyword arguments passed to
dwave.cloud.client.Client.from_config()
.
Examples
This example solves a small, illustrative problem: a game of rockpaperscissors. The DQM has two variables representing two hands, with cases for rock, paper, scissors. Quadratic biases are set to produce a lower value of the DQM for cases of variable
my_hand
interacting with cases of variabletheir_hand
such that the former wins over the latter; for example, the interaction ofrockscissors
is set to 1 whilescissorsrock
is set to +1.>>> import dimod >>> from dwave.system import LeapHybridDQMSampler ... >>> cases = ["rock", "paper", "scissors"] >>> win = {"rock": "scissors", "paper": "rock", "scissors": "paper"} ... >>> dqm = dimod.DiscreteQuadraticModel() >>> dqm.add_variable(3, label='my_hand') 'my_hand' >>> dqm.add_variable(3, label='their_hand') 'their_hand' >>> for my_idx, my_case in enumerate(cases): ... for their_idx, their_case in enumerate(cases): ... if win[my_case] == their_case: ... dqm.set_quadratic('my_hand', 'their_hand', ... {(my_idx, their_idx): 1}) ... if win[their_case] == my_case: ... dqm.set_quadratic('my_hand', 'their_hand', ... {(my_idx, their_idx): 1}) ... >>> dqm_sampler = LeapHybridDQMSampler() ... >>> sampleset = dqm_sampler.sample_dqm(dqm) >>> print("{} beats {}".format(cases[sampleset.first.sample['my_hand']], ... cases[sampleset.first.sample['their_hand']])) rock beats scissors
Properties¶
Solver properties as returned by a SAPI query. 

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

Methods¶

Sample from the specified discrete quadratic model. 
Return the minimum time_limit accepted for the given problem. 
Composites¶
dimod composites that provide layers of pre and postprocessing (e.g., minorembedding) when using the DWave system:
Other Ocean packages provide additional composites; for example, dimod provides composites that operate on the problem (e.g., scaling values), track inputs and outputs for debugging, and other useful functionality relevant to generic samplers.
CutOffs¶
Prunes the binary quadratic model (BQM) submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision.
CutOffComposite¶
 class CutOffComposite(child_sampler, cutoff, cutoff_vartype=Vartype.SPIN, comparison=<builtin function lt>)[source]¶
Composite to remove interactions below a specified cutoff value.
Prunes the binary quadratic model (BQM) submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision as specified by the
cutoff
argument. Also removes variables isolated post or preremoval of these interactions from the BQM passed on to the child sampler, setting these variables to values that minimize the original BQM’s energy for the returned samples. Parameters
sampler (
dimod.Sampler
) – A dimod sampler.cutoff (number) – Lower bound for absolute value of interactions. Interactions with absolute values lower than
cutoff
are removed. Isolated variables are also not passed on to the child sampler.cutoff_vartype (
Vartype
/str/set, default=’SPIN’) –Variable space to execute the removal in. Accepted input values:
Vartype.SPIN
,'SPIN'
,{1, 1}
Vartype.BINARY
,'BINARY'
,{0, 1}
comparison (function, optional) – A comparison operator for comparing interaction values to the cutoff value. Defaults to
operator.lt()
.
Examples
This example removes one interaction,
'ac': 0.7
, before embedding on a DWave system. Note that the lowestenergy sample for the embedded problem is{'a': 1, 'b': 1, 'c': 1}
but with a large enough number of samples (herenum_reads=1000
), the lowestenergy solution to the complete BQM is likely found and its energy recalculated by the composite.>>> import dimod >>> sampler = DWaveSampler(solver={'qpu': True}) >>> bqm = dimod.BinaryQuadraticModel({'a': 1, 'b': 1, 'c': 1}, ... {'ab': 0.8, 'ac': 0.7, 'bc': 1}, ... 0, ... dimod.SPIN) >>> CutOffComposite(AutoEmbeddingComposite(sampler), 0.75).sample(bqm, ... num_reads=1000).first.energy 3.5
The child sampler. 

List of child samplers that that are used by this composite. 

A dict containing any additional information about the sampler. 

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

Cut off interactions and sample from the provided binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
PolyCutOffComposite¶
Prunes the polynomial submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision.
 class PolyCutOffComposite(child_sampler, cutoff, cutoff_vartype=Vartype.SPIN, comparison=<builtin function lt>)[source]¶
Composite to remove polynomial interactions below a specified cutoff value.
Prunes the binary polynomial submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision as specified by the
cutoff
argument. Also removes variables isolated post or preremoval of these interactions from the polynomial passed on to the child sampler, setting these variables to values that minimize the original polynomial’s energy for the returned samples. Parameters
sampler (
dimod.PolySampler
) – A dimod binary polynomial sampler.cutoff (number) – Lower bound for absolute value of interactions. Interactions with absolute values lower than
cutoff
are removed. Isolated variables are also not passed on to the child sampler.cutoff_vartype (
Vartype
/str/set, default=’SPIN’) –Variable space to do the cutoff in. Accepted input values:
Vartype.SPIN
,'SPIN'
,{1, 1}
Vartype.BINARY
,'BINARY'
,{0, 1}
comparison (function, optional) – A comparison operator for comparing the interaction value to the cutoff value. Defaults to
operator.lt()
.
Examples
This example removes one interaction,
'ac': 0.2
, before submitting the polynomial to child samplerExactSolver
.>>> import dimod >>> sampler = dimod.HigherOrderComposite(dimod.ExactSolver()) >>> poly = dimod.BinaryPolynomial({'a': 3, 'abc':4, 'ac': 0.2}, dimod.SPIN) >>> PolyCutOffComposite(sampler, 1).sample_poly(poly).first.sample['a'] 1
The child sampler. 

List of child samplers that that are used by this composite. 

A dict containing any additional information about the sampler. 

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

Cutoff and sample from the provided binary polynomial. 

Sample from a higherorder Ising model. 

Sample from a higherorder unconstrained binary optimization problem. 
Embedding¶
Minorembed a problem BQM into a DWave system.
Embedding composites for various types of problems and application. For example:
EmbeddingComposite
for a problem with arbitrary structure that likely requires hueristic embedding.AutoEmbeddingComposite
can save unnecessary embedding for problems that might have a structure similar to the child sampler.LazyFixedEmbeddingComposite
can benefit applications that resubmit a BQM with changes in some values.
AutoEmbeddingComposite¶
 class AutoEmbeddingComposite(child_sampler, **kwargs)[source]¶
Maps problems to a structured sampler, embedding if needed.
This composite first tries to submit the binary quadratic model directly to the child sampler and only embeds if a
dimod.exceptions.BinaryQuadraticModelStructureError
is raised. Parameters
child_sampler (
dimod.Sampler
) – Structured dimod sampler, such as aDWaveSampler()
.find_embedding (function, optional) – A function find_embedding(S, T, **kwargs) where S and T are edgelists. The function can accept additional keyword arguments. Defaults to
minorminer.find_embedding()
.kwargs – See the
EmbeddingComposite
class for additional keyword arguments.
The child sampler. 

Parameters in the form of a dict. 

Properties in the form of a dict. 

Sample from the provided binary quadratic model. 

Sample from an Ising model using the implemented sample method. 
Sample from a QUBO using the implemented sample method. 
EmbeddingComposite¶
 class EmbeddingComposite(child_sampler, find_embedding=<function find_embedding>, embedding_parameters=None, scale_aware=False, child_structure_search=<function child_structure_dfs>)[source]¶
Maps problems to a structured sampler.
Automatically minorembeds a problem into a structured sampler such as a DWave system. A new minorembedding is calculated each time one of its sampling methods is called.
 Parameters
child_sampler (
dimod.Sampler
) – A dimod sampler, such as aDWaveSampler
, that accepts only binary quadratic models of a particular structure.find_embedding (function, optional) – A function find_embedding(S, T, **kwargs) where S and T are edgelists. The function can accept additional keyword arguments. Defaults to
minorminer.find_embedding()
.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments.
scale_aware (bool, optional, default=False) – Pass chain interactions to child samplers that accept an ignored_interactions parameter.
child_structure_search (function, optional) – A function child_structure_search(sampler) that accepts a sampler and returns the
dimod.Structured.structure
. Defaults todimod.child_structure_dfs()
.
Examples
>>> from dwave.system import DWaveSampler, EmbeddingComposite ... >>> sampler = EmbeddingComposite(DWaveSampler()) >>> h = {'a': 1., 'b': 2} >>> J = {('a', 'b'): 1.5} >>> sampleset = sampler.sample_ising(h, J, num_reads=100) >>> sampleset.first.energy 4.5
The child sampler. 

Parameters in the form of a dict. 

Properties in the form of a dict. 

Defines the default behaviour for 

Defines the default behavior for 

Sample from the provided binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
FixedEmbeddingComposite¶
 class FixedEmbeddingComposite(child_sampler, embedding=None, source_adjacency=None, **kwargs)[source]¶
Maps problems to a structured sampler with the specified minorembedding.
 Parameters
child_sampler (dimod.Sampler) – Structured dimod sampler such as a DWave system.
embedding (dict[hashable, iterable], optional) – Mapping from a source graph to the specified sampler’s graph (the target graph).
source_adjacency (dict[hashable, iterable]) – Deprecated. Dictionary to describe source graph as {node: {node neighbours}}.
kwargs – See the
EmbeddingComposite
class for additional keyword arguments. Note thatfind_embedding
andembedding_parameters
keyword arguments are ignored.
Examples
To embed a triangular problem (a problem with a threenode complete graph, or clique) in the Chimera topology, you need to chain two qubits. This example maps triangular problems to a composed sampler (based on the unstructured
ExactSolver
) with a Chimera unitcell structure.>>> import dimod >>> import dwave_networkx as dnx >>> from dwave.system import FixedEmbeddingComposite ... >>> c1 = dnx.chimera_graph(1) >>> embedding = {'a': [0, 4], 'b': [1], 'c': [5]} >>> structured_sampler = dimod.StructureComposite(dimod.ExactSolver(), ... c1.nodes, c1.edges) >>> sampler = FixedEmbeddingComposite(structured_sampler, embedding) >>> sampler.edgelist [('a', 'b'), ('a', 'c'), ('b', 'c')]
Properties in the form of a dict. 

Parameters in the form of a dict. 

List containing the structured sampler. 

The child sampler. 

Nodes available to the composed sampler. 

Edges available to the composed sampler. 

Adjacency structure for the composed sampler. 

Structure of the structured sampler formatted as a 

Sample the binary quadratic model. 

Sample from an Ising model using the implemented sample method. 
Sample from a QUBO using the implemented sample method. 
LazyFixedEmbeddingComposite¶
 class LazyFixedEmbeddingComposite(child_sampler, find_embedding=<function find_embedding>, embedding_parameters=None, scale_aware=False, child_structure_search=<function child_structure_dfs>)[source]¶
Maps problems to the structure of its first given problem.
This composite reuses the minorembedding found for its first given problem without recalculating a new minorembedding for subsequent calls of its sampling methods.
 Parameters
child_sampler (dimod.Sampler) – Structured dimod sampler.
find_embedding (function, default=:func:minorminer.find_embedding) – A function find_embedding(S, T, **kwargs) where S and T are edgelists. The function can accept additional keyword arguments. The function is used to find the embedding for the first problem solved.
embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments.
Examples
>>> from dwave.system import LazyFixedEmbeddingComposite, DWaveSampler ... >>> sampler = LazyFixedEmbeddingComposite(DWaveSampler()) >>> sampler.nodelist is None # no structure prior to first sampling True >>> __ = sampler.sample_ising({}, {('a', 'b'): 1}) >>> sampler.nodelist # has structure based on given problem ['a', 'b']
Parameters in the form of a dict. 

Properties in the form of a dict. 

Nodes available to the composed sampler. 

Edges available to the composed sampler. 

Adjacency structure for the composed sampler. 

Structure of the structured sampler formatted as a 

Sample the binary quadratic model. 
Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
TilingComposite¶
 class TilingComposite(sampler, sub_m, sub_n, t=4)[source]¶
Composite to tile a small problem across a structured sampler.
Enables parallel sampling on Chimera or Pegasus structured samplers of small problems. The small problem should be defined on a Chimera graph of dimensions
sub_m
,sub_n
,t
, or minorembeddable to such a graph.Notation CN refers to a Chimera graph consisting of an NxN grid of unit cells, where each unit cell is a bipartite graph with shores of size t. The DWave 2000Q QPU supports a C16 Chimera graph: its 2048 qubits are logically mapped into a 16x16 matrix of unit cells of 8 qubits (t=4). See also :func:dwave_networkx.chimera_graph
Notation PN referes to a Pegasus graph consisting of a 3x(N1)x(N1) grid of cells, where each unit cell is a bipartite graph with shore of size t, supplemented with odd couplers (see nice_coordinate definition). The Advantage QPU supports a P16 Pegasus graph: its qubits may be mapped to a 3x15x15 matrix of unit cells, each of 8 qubits. This code supports tiling of Chimerastructured problems, with an option of additional oddcouplers, onto Pegasus. See also :func:dwave_networkx.pegasus_graph .
A problem that can be minorembedded in a single chimera unit cell, for example, can therefore be tiled across the unit cells of a DWave 2000Q as 16x16 duplicates (or Advantage as 3x15x15 duplicates), subject to solver yield. This enables up to 256 (625) parallel samples per read.
 Parameters
sampler (
dimod.Sampler
) – Structured dimod sampler such as aDWaveSampler()
.sub_m (int) – Minimum number of Chimera unit cell rows required for minorembedding a single instance of the problem.
sub_n (int) – Minimum number of Chimera unit cell columns required for minorembedding a single instance of the problem.
t (int, optional, default=4) – Size of the shore within each Chimera unit cell.
Examples
This example submits a twovariable QUBO problem representing a logical NOT gate to a DWave system. The QUBO—two nodes with biases of 1 that are coupled with strength 2—needs only any two coupled qubits and so is easily minorembedded in a single unit cell. Composite
TilingComposite
tiles it multiple times for parallel solution: the two nodes should typically have opposite values.>>> from dwave.system import DWaveSampler, EmbeddingComposite >>> from dwave.system import TilingComposite ... >>> qpu_2000q = DWaveSampler(solver={'topology__type': 'chimera'}) >>> sampler = EmbeddingComposite(TilingComposite(qpu_2000q, 1, 1, 4)) >>> Q = {(1, 1): 1, (1, 2): 2, (2, 1): 0, (2, 2): 1} >>> sampleset = sampler.sample_qubo(Q) >>> len(sampleset)> 1 True
See Ocean Glossary for explanations of technical terms in descriptions of Ocean tools.
Properties in the form of a dict. 

Parameters in the form of a dict. 

The single wrapped structured sampler. 

The child sampler. 

List of active qubits for the structured solver. 

List of active couplers for the DWave solver. 

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

Structure of the structured sampler formatted as a 

Sample from the specified binary quadratic model. 

Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
VirtualGraphComposite¶
 class VirtualGraphComposite(sampler, embedding, chain_strength=None, flux_biases=None, flux_bias_num_reads=1000, flux_bias_max_age=3600)[source]¶
Composite to use the DWave virtual graph feature for minorembedding.
Calibrates qubits in chains to compensate for the effects of biases and enables easy creation, optimization, use, and reuse of an embedding for a given working graph.
Inherits from
dimod.ComposedSampler
anddimod.Structured
. Parameters
sampler (
DWaveSampler
) – A dimoddimod.Sampler
. Typically aDWaveSampler
or derived composite sampler; other samplers may not work or make sense with this composite layer.embedding (dict[hashable, iterable]) – Mapping from a source graph to the specified sampler’s graph (the target graph).
chain_strength (float, optional, default=None) – Desired chain coupling strength. This is the magnitude of couplings between qubits in a chain. If None, uses the maximum available as returned by a SAPI query to the DWave solver.
flux_biases (list/False/None, optional, default=None) – Perqubit flux bias offsets in the form of a list of lists, where each sublist is of length 2 and specifies a variable and the flux bias offset associated with that variable. Qubits in a chain with strong negative J values experience a Jinduced bias; this parameter compensates by recalibrating to remove that bias. If False, no flux bias is applied or calculated. If None, flux biases are pulled from the database or calculated empirically.
flux_bias_num_reads (int, optional, default=1000) – Number of samples to collect per flux bias value to calculate calibration information.
flux_bias_max_age (int, optional, default=3600) – Maximum age (in seconds) allowed for a previously calculated flux bias offset to be considered valid.
Attention
DWave’s virtual graphs feature can require many seconds of DWave system time to calibrate qubits to compensate for the effects of biases. If your account has limited DWave system access, consider using
FixedEmbeddingComposite
instead.Examples
This example uses
VirtualGraphComposite
to instantiate a composed sampler that submits a QUBO problem to a DWave solver. The problem represents a logical AND gate using penalty function \(P = xy  2(x+y)z +3z\), where variables x and y are the gate’s inputs and z the output. This simple threevariable problem is manually minorembedded to a single Chimera unit cell: variables x and y are represented by qubits 1 and 5, respectively, and z by a twoqubit chain consisting of qubits 0 and 4. The chain strength is set to the maximum allowed found from querying the solver’s extended J range. In this example, the ten returned samples all represent valid states of the AND gate.>>> from dwave.system import DWaveSampler, VirtualGraphComposite >>> embedding = {'x': {1}, 'y': {5}, 'z': {0, 4}} >>> qpu_2000q = DWaveSampler(solver={'topology__type': 'chimera'}) >>> qpu_2000q.properties['extended_j_range'] [2.0, 1.0] >>> sampler = VirtualGraphComposite(qpu_2000q, embedding, chain_strength=2) >>> Q = {('x', 'y'): 1, ('x', 'z'): 2, ('y', 'z'): 2, ('z', 'z'): 3} >>> sampleset = sampler.sample_qubo(Q, num_reads=10) >>> print(sampleset) x y z energy num_oc. chain_. 0 1 0 0 0.0 2 0.0 1 0 1 0 0.0 3 0.0 2 1 1 1 0.0 3 0.0 3 0 0 0 0.0 2 0.0 ['BINARY', 4 rows, 10 samples, 3 variables]
See Ocean Glossary for explanations of technical terms in descriptions of Ocean tools.
Properties in the form of a dict. 

Parameters in the form of a dict. 

List containing the structured sampler. 

The child sampler. 

Nodes available to the composed sampler. 

Edges available to the composed sampler. 

Adjacency structure for the composed sampler. 

Structure of the structured sampler formatted as a 

Sample from the given Ising model. 

Sample from an Ising model using the implemented sample method. 
Sample from a QUBO using the implemented sample method. 
Reverse Anneal¶
Composites that do batch operations for reverse annealing based on sets of initial states or anneal schedules.
ReverseBatchStatesComposite¶
 class ReverseBatchStatesComposite(child_sampler)[source]¶
Composite that reverse anneals from multiple initial samples. Each submission is independent from one another.
 Parameters
sampler (
dimod.Sampler
) – A dimod sampler.
Examples
This example runs 100 reverse anneals each from two initial states on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minorembedded on a DWave system using the
DWaveCliqueSampler
sampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseBatchStatesComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseBatchStatesComposite(sampler) >>> schedule = [[0.0, 1.0], [10.0, 0.5], [20, 1.0]] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = [{i: 1 for i in range(15)}, {i: 1 for i in range(15)}] >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedule=schedule, ... initial_states=init_samples, ... num_reads=100, ... reinitialize_state=True)
The child sampler. 

List of child samplers that that are used by this composite. 

A dict containing any additional information about the sampler. 

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

Sample the binary quadratic model using reverse annealing from multiple initial states. 
Sample from an Ising model using the implemented sample method. 

Sample from a QUBO using the implemented sample method. 
ReverseAdvanceComposite¶
 class ReverseAdvanceComposite(child_sampler)[source]¶
Composite that reverse anneals an initial sample through a sequence of anneal schedules.
If you do not specify an initial sample, a random sample is used for the first submission. By default, each subsequent submission selects the mostfound lowestenergy sample as its initial state. If you set reinitialize_state to False, which makes each submission behave like a random walk, the subsequent submission selects the last returned sample as its initial state.
 Parameters
sampler (
dimod.Sampler
) – A dimod sampler.
Examples
This example runs 100 reverse anneals each for three schedules on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minorembedded on a DWave system using the
DWaveCliqueSampler
sampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseAdvanceComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseAdvanceComposite(sampler) >>> schedule = [[[0.0, 1.0], [t, 0.5], [20, 1.0]] for t in (5, 10, 15)] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = {i: 1 for i in range(15)} >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedules=schedule, ... initial_state=init_samples, ... num_reads=100, ... reinitialize_state=True)
The child sampler. 

List of child samplers that that are used by this composite. 

A dict containing any additional information about the sampler. 

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

Sample the binary quadratic model using reverse annealing along a given set of anneal schedules. 

Sample from an Ising model using the implemented sample method. 
Sample from a QUBO using the implemented sample method. 
Embedding¶
Provides functions that map binary quadratic models and samples between a source graph and a target graph.
For an introduction to minorembedding, see MinorEmbedding.
Generators¶
Tools for finding embeddings.
Generic¶
minorminer is a heuristic tool for minor embedding: given a minor and target graph, it tries to find a mapping that embeds the minor into the target.
Heuristically attempt to find a minorembedding of source graph S into a target graph T. 
Chimera¶
Minorembedding in Chimerastructured target graphs.

Find an embedding for a clique in a Chimera graph. 

Find an embedding for a biclique in a Chimera graph. 

Find an embedding for a grid in a Chimera graph. 
Pegasus¶
Minorembedding in Pegasusstructured target graphs.

Find an embedding for a clique in a Pegasus graph. 
Utilities¶

Embed a binary quadratic model onto a target graph. 

Embed an Ising problem onto a target graph. 

Embed a QUBO onto a target graph. 

Unembed a sample set. 
Diagnostics¶

Determine the frequency of chain breaks in the given samples. 

Diagnose a minor embedding. 

A simple (bool) diagnostic for minor embeddings. 

A simple (exceptionraising) diagnostic for minor embeddings. 
Chain Strength¶
Utility functions for calculating chain strength.
Examples
This example uses uniform_torque_compensation()
, given a prefactor of 2,
to calculate a chain strength that EmbeddingComposite
then uses.
>>> from functools import partial
>>> from dwave.system import EmbeddingComposite, DWaveSampler
>>> from dwave.embedding.chain_strength import uniform_torque_compensation
...
>>> Q = {(0,0): 1, (1,1): 1, (2,3): 2, (1,2): 2, (0,3): 2}
>>> sampler = EmbeddingComposite(DWaveSampler())
>>> # partial() can be used when the BQM or embedding is not accessible
>>> chain_strength = partial(uniform_torque_compensation, prefactor=2)
>>> sampleset = sampler.sample_qubo(Q, chain_strength=chain_strength, return_embedding=True)
>>> sampleset.info['embedding_context']['chain_strength']
1.224744871391589
Chain strength that attempts to compensate for torque that would break the chain. 


Chain strength that is scaled to the problem bias range. 
ChainBreak Resolution¶
Unembedding samples with broken chains.
Generators¶

Discard broken chains. 

Unembed samples using the most common value for broken chains. 

Unembed samples using weighed random choice for broken chains. 
Callable Objects¶

Unembed samples by minimizing local energy for broken chains. 
Exceptions¶
Base class for all embedding exceptions. 


Raised if a node in the source graph has no associated chain. 

Raised if two source nodes have an overlapping chain. 
Raised if a chain is not connected in the target graph. 


Raised if a chain contains a node not in the target graph. 

Raised when two source nodes sharing an edge to not have a corresponding edge between their chains. 
Classes¶
 class EmbeddedStructure(target_edges, embedding)[source]¶
Processes an embedding and a target graph to collect target edges into those within individual chains, and those that connect chains. This is used elsewhere to embed binary quadratic models into the target graph.
 Parameters
target_edges (iterable[edge]) – An iterable of edges in the target graph. Each edge should be an iterable of 2 hashable objects.
embedding (dict) – Mapping from source graph to target graph as a dict of form {s: {t, …}, …}, where s is a sourcemodel variable and t is a targetmodel variable.
This class is a dict, and acts as an immutable duplicate of embedding.
Utilities¶
Utility functions.

Creates a graph using the common nodes and edges of two given graphs. 
Warnings¶
Installation¶
Installation from PyPI:
pip install dwavesystem
Installation from PyPI with drivers:
Note
Prior to v0.3.0, running pip install dwavesystem
installed a driver dependency called dwavedrivers
(previously also called dwavesystemtuning
). This dependency has a restricted license and has been made optional
as of v0.3.0, but is highly recommended. To view the license details:
from dwave.drivers import __license__
print(__license__)
To install with optional dependencies:
pip install dwavesystem[drivers] extraindexurl https://pypi.dwavesys.com/simple
Installation from source:
pip install r requirements.txt
python setup.py install
Note that installing from source installs dwavedrivers
. To uninstall the proprietary components:
pip uninstall dwavedrivers
License¶
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, nonexclusive, nocharge, royaltyfree, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, nonexclusive, nocharge, royaltyfree, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a crossclaim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such thirdparty notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NONINFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets “[]” replaced with your own identifying information. (Don’t include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same “printed page” as the copyright notice for easier identification within thirdparty archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.