DWave Ocean Software Documentation¶
Ocean software is a suite of tools DWave Systems provides on the DWave GitHub repository for solving hard problems with quantum computers.
 Getting Started shows how to install and begin using Ocean tools.
 Concepts defines and describes Ocean concepts and terminology.
Getting Started¶
New to Ocean? The following sections describe how to install Ocean tools, what they are and how they fit together, and give examples of using them to solve hard problems on a DWave quantum computer.
Initial Set Up¶
DWave’s Leap integrated development environment (IDE) is the fastest way to get started writing your quantum application or just learning to use Ocean tools. This cloudbased IDE—run in your browser—is available to all Leap accounts. It provides reusable/disposable workspaces (developer environments preconfigured with Ocean and other standard libraries as well as DWave extensions) for running code from your own GitHub repository or a collection of code examples you can then modify.
Alternatively, install the tools and configure for running problems on DWave remote compute resources, including quantumclassical hybrid solvers and the DWave quantum processing unit (QPU), or locally on your CPU.
Installing Ocean Tools¶
Ocean software is supported on the following operating systems:
 Linux
 Windows (tested on 64bit Windows 8, 10)
 Mac (tested on mac OS X 10.13)
Ocean software requires a Python environment. Python versions 3.5 and higher are supported.
Attention
DWave’s Ocean software stopped supporting Python 2 at the end of 2019.
For information on why many in the Python development community are requiring Python 3, see the Python 3 statement.
This section explains how to install Ocean software, either the entire suite of tools or particular tools from the DWave GitHub repositories listed in the navigation bar.
Most Ocean tools require that you configure a solver on your system, which might be a DWave system or a classical sampler that runs on your local CPU.
Python Virtual Environment¶
It’s recommended that you work in a virtual environment on your local machine; depending on your operating system, you may need to first install Python and/or virtualenv.
Download Python describes how to install Python on your local machine for supported operating system.
For Unixbased systems, which often have Python preinstalled, installation might be as simple as:
sudo aptget install python<version>
Attention
For Windows systems, note that only 64bit Python is supported.
Install virtualenv describes how to install the virtualenv tool for creating isolated Python environments on your local machine for supported operating system.
For Unixbased systems, installing virtualenv is typically done with a command such as this or similar:
sudo pip install virtualenv
Create a virtual environment for your Ocean work. For example, on Unix systems you might do:
virtualenv ocean source ocean/bin/activate
(On Windows operating system, activating a virtual environment might be done with the
Scripts\activate
command instead.)
Your machine is now ready to install Ocean software.
Install Ocean Software¶
The simplest way to start is to install dwaveoceansdk for the full suite of Ocean tools.
You can
pip install
the SDK inside your newly created virtual environment, typically with a command such as this or similar:pip install dwaveoceansdk
Alternatively, you can clone dwaveoceansdk repo and install the SDK to your virtual environment; for example:
git clone https://github.com/dwavesystems/dwaveoceansdk.git cd dwaveoceansdk python setup.py install
Note: To install a particular tool within the SDK only, follow the link to the GitHub repository for the tool, as listed in the navigation bar, and follow the installation instructions on the README file.
Set Up Your Environment¶
For a full and easy development experience it is recommended that before you start writing code, you complete the setup of your environment with two last steps:
Install Contributor Ocean Tools
Adds nonopensource tools such as the inspector.
Configuring Access to DWave Solvers
Sets defaults used for accessing DWave compute resources.
The dwaveoceansdk includes an interactive CLI that steps you through setup.
In the virtual environment you created as part of Installing Ocean Tools, run the
dwave setup
command. The output shown below includes the interactive
prompts and placeholder replies for a full setup. The next sections explain
the details.
$ dwave setup
Optionally install nonopensource packages and configure your environment.
Do you want to select nonopensource packages to install (y/n)? [y]:
DWave Drivers
These drivers enable some automated performancetuning features.
This package is available under the 'DWave EULA' license.
The terms of the license are available online: https://docs.ocean.dwavesys.com/eula
Install (y/n)? [y]:
Installing: DWave Drivers
Successfully installed DWave Drivers.
DWave Problem Inspector
This tool visualizes problems submitted to the quantum computer and the results returned.
This package is available under the 'DWave EULA' license.
The terms of the license are available online: https://docs.ocean.dwavesys.com/eula
Install (y/n)? [y]:
Installing: DWave Problem Inspector
Successfully installed DWave Problem Inspector.
Creating the DWave configuration file.
Configuration file not found; the default location is: /home/jane/.config/dwave/dwave.conf
Confirm configuration file path [/home/jane/.config/dwave/dwave.conf]:
Profile (create new) [prod]:
API endpoint URL [skip]:
Authentication token [skip]: ABC1234567890abcdef1234567890abcdef
Default client class (qpu or sw) [qpu]:
Default solver [skip]:
Configuration saved.
Install Contributor Ocean Tools¶
The interactive dwave setup
and dwave install
commands of the
the dwaveoceansdk step
you through installation of nonopensource (“contrib”) tools.
If you did not install contributor packages with the dwave setup
command
in the Set Up Your Environment section, or want to add packages at a later time, you
can use it again then or use the dwave install
command.
$ dwave install help
Usage: dwave install [OPTIONS] [PACKAGES]...
Install optional nonopensource Ocean packages.
Options:
l, list List available contrib (nonOSS) packages
a, all Install all contrib (nonOSS) packages
v, verbose Increase output verbosity
help Show this message and exit.
Both commands describe the tools and enable you to select which if any to install.
Most Ocean tools solve problems on a solver, which is a compute resource such as a DWave system or CPU, and might require that you configure a default solver. Configuring Access to DWave Solvers describes the next step of setting up your environment, how to configure your system to access DWave or other remote solvers.
Configuring Access to DWave Solvers¶
DWave’s Solver API (SAPI) provides access to solvers, remote compute resources for solving problems such as a DWave system or Leap’s quantumclassical hybrid solvers.
Interacting with SAPI¶
SAPI is an application layer built to provide resource discovery, permissions, and scheduling for DWave compute resources. The requisite information for problem submission through SAPI includes:
API endpoint URL
A URL to the remote resources. By default,
https://cloud.dwavesys.com/sapi
is used to connect to resources provided by DWave’s Leap quantum cloud service, including DWave quantum computers.API Token
An authentication token used to authenticate the client session when you connect to the remote environment. Because tokens provide authentication, user names and passwords are not required in your code.
Solver
A DWave resource to be used to solve your submitted problems; for example, a hybrid solver or a DWave 2000Q quantum computer.
You can find all the above information when you log in to your DWave account. For Leap users, select the Dashboard tab; for onpremises (Qubist) users, select the Solver API tab and the API Tokens menu item under your user name.
You save your SAPI configuration (URL, API token, etc) in a DWave Cloud Client configuration file that Ocean tools use unless overridden explicitly or with environment variables. Your configuration file can include one or more solvers.
Note
When you work in DWave’s Leap IDE, SAPI information such as your API token is preconfigured in the default workspace’s environment variables.
Creating a Configuration File¶
The simplest way to configure solver access is to use the interactive CLI, which is installed as part of the dwaveoceansdk installation.
If you did not already do so with the dwave setup
command
in the Set Up Your Environment section, or want to make changes at a later time, you
can use the dwave config
command.
$ dwave config help
Usage: dwave config [OPTIONS] COMMAND [ARGS]...
Create, update or inspect cloud client configuration file(s).
Options:
help Show this message and exit.
Commands:
create Create and/or update cloud client configuration file.
inspect Inspect existing configuration/profile.
ls List configuration files detected (and/or examined paths).
Creating a configuration file using the dwave config
is done
as follows (the dwave setup
command of the Set Up Your Environment section
runs these same configuration steps):
 In the virtual environment you created as part of Installing Ocean Tools, run the
dwave config create
command (the output shown below includes the interactive prompts and placeholder replies).
$ dwave config create
Configuration file not found; the default location is: /home/jane/.config/dwave/dwave.conf
Confirm configuration file path [/home/jane/.config/dwave/dwave.conf]:
Profile (create new) [prod]:
API endpoint URL [skip]:
Authentication token [skip]: ABC1234567890abcdef1234567890abcdef
Default client class (qpu or sw) [qpu]:
Default solver [skip]:
Configuration saved.
 Enter the SAPI information (e.g. your API token) found as described in the section above. To get started, create a minimum configuration by accepting the command’s defaults (pressing Enter) for all prompts except the API token (Leap users) or API token and endpoint (onpremises users). You can in the future update the file if needed.
Alternatively, you can create and edit a DWave Cloud Client configuration file manually.
You can always set or override the solver, API token, and URL directly in your code or as local environment variables. For more information, see the examples in this document or DWave Cloud Client.
Verifying Your Configuration¶
You can test that your solver access is configured correctly with the interactive CLI.
 In your virtual environment, run the
dwave ping
command (the output shown below is illustrative only).
$ dwave ping
Using endpoint: https://cloud.dwavesys.com/sapi
Using solver: My_DWAVE_2000Q
Wall clock time:
* Solver definition fetch: 2007.239 ms
* Problem submit and results fetch: 1033.931 ms
* Total: 3041.171 ms
QPU timing:
* total_real_time = 10493 us
* anneal_time_per_run = 20 us
* post_processing_overhead_time = 128 us
* qpu_anneal_time_per_sample = 20 us
# Snipped for brevity
 Optionally, run the
dwave sample randomproblem
command to submit a random problem to a remote solver (the output shown below is illustrative only).
$ dwave sample randomproblem
Using endpoint: https://my.dwavesys.url/
Using solver: My_DWAVE_2000Q
Using qubit biases: {0: 1.0345257941434953, 1: 0.5795618633919246, 2: 0.9721956399428491, 3: 1....
Using qubit couplings: {(1634, 1638): 0.721736584181423, (587, 590): 0.9611623181258304, (642, 64...
Number of samples: 1
Samples: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
Occurrences: [1]
Energies: [2882.197791239335]
Querying Available Solvers¶
Note
Leap accounts can see accessible solvers on the dashboard.
From your terminal, you can use the interactive CLI to see the available solvers, their parameters, and properties.
 Run the
dwave solvers
command (the output shown below is illustrative only).
$ dwave solvers
Solver: DW_2000Q_33
Parameters:
anneal_offsets: A list of anneal offsets for each working qubit (NaN if u...
anneal_schedule: A piecewise linear annealing schedule specified by a list...
annealing_time: A positive integer that sets the duration (in microsecond...
<Output snipped for brevity>
Properties:
anneal_offset_ranges: [[0.18627387668142237, 0.09542224439071689], [0.1836548...
anneal_offset_step: 0.00426679499507194
anneal_offset_step_phi0: 0.0002716837027763096
annealing_time_range: [1, 150000]
chip_id: W71_C16_472485402G4_C5R9devicecaldata18052714:27
couplers: [[0, 4], [1, 4], [2, 4], [3, 4], [0, 5], [1, 5], [2, 5], ...
<Output snipped for brevity>
Alternatively, from within your code or a Python interpreter you can query solvers available for
a SAPI URL and API token using
dwavecloudclient get_solvers()
function. For example, the code below queries available solvers for your default SAPI URL and a
specified token.
>>> from dwave.cloud import Client
>>> client = Client.from_config(token='ABC123456789123456789123456789') # doctest: +SKIP
>>> client.get_solvers() # doctest: +SKIP
[Solver(id='2000Q_ONLINE_SOLVER1'),
UnstructuredSolver(id='hybrid_v1')]
Typically, once you have selected and configured a solver, your code queries its parameters and properties as attributes of the instantiated solver object. The code example below (with output snipped for brevity) sets a DWave system as the sampler, using the default SAPI configuration as set above, and queries its parameters.
>>> from dwave.system import DWaveSampler
>>> sampler = DWaveSampler(solver={'qpu': True})
>>> sampler.parameters # doctest: +SKIP
{u'anneal_offsets': ['parameters'],
u'anneal_schedule': ['parameters'],
u'annealing_time': ['parameters'],
u'answer_mode': ['parameters'],
u'auto_scale': ['parameters'], ...
Descriptions of DWave system parameters and properties are in the system documentation.
Ocean’s Programming Model¶
Learn Ocean software’s workflow for problem solving.
How a DWave System Solves Problems¶
This section explains some of the basics of how you can use DWave quantum computers to solve problems and how Ocean tools can help.
For quantum computing, as for classical, solving a problem requires that it be formulated in a way the computer and its software understand.
For example, if you want your laptop to calculate the area of a $1 coin, you might
express the problem as an equation, \(A=\pi r^2\), that you program as
math.pi*13.245**2
in your Python CLI. For a laptop with Python software,
this formulation—a particular string of alphanumeric symbols—causes the manipulation
of bits in a CPU and memory chips that produces the correct result.
The DWave system uses a quantum processing unit (QPU) to solve a binary quadratic model (BQM)[1]: given \(N\) variables \(x_1,...,x_N\), where each variable \(x_i\) can have binary values \(0\) or \(1\), the system finds assignments of values that minimize
where \(q_i\) and \(q_{i,j}\) are configurable (linear and quadratic) coefficients. To formulate a problem for the DWave system is to program \(q_i\) and \(q_{i,j}\) so that assignments of \(x_1,...,x_N\) also represent solutions to the problem.
[1]  The “native” forms of BQM programmed into a DWave system are the Ising model traditionally used in statistical mechanics and its computerscience equivalent, shown here, the QUBO. 
Ocean software can abstract away much of the mathematics and programming for some types of problems. At its heart is a binary quadratic model (BQM) class that together with other Ocean tools helps formulate various optimization problems. It also provides an API to binary quadratic samplers (the component used to minimize a BQM and therefore solve the original problem), such as the DWave system and classical algorithms you can run on your computer.
The following sections describe this problemsolving procedure in two steps (plus a third that may benefit some problems); see the Getting Started Examples section and System Documentation for further description.
 Formulate Your Problem for a Quantum Computer.
 Sample the BQM on a Solver.
 Improve the Solutions, if needed, using advanced features.
Formulate Your Problem for a Quantum Computer¶
There are different ways of mapping between a problem—chains of amino acids forming 3D structures of folded proteins, traffic in the streets of Beijing, circuits of binary gates—and a BQM to be solved (by sampling) with a DWave system or locally on your CPU/GPU.
For example, consider the problem of determining outputs of a Boolean logic circuit. In its original context (in “problem space”), the circuit might be described with input and output voltages, equations of its component resistors, transistors, etc, an equation of logic symbols, multiple or an aggregated truth table, and so on. You can choose to use Ocean software to formulate BQMs for binary gates directly in your code or mathematically formulate a BQM, and both can be done in different ways too; for example, a BQM for each gate or one BQM for all the circuit’s gates.
The following are two example formulations.
The Boolean NOT Gate example, takes a NOT gate represented symbolically as \(x_2 \Leftrightarrow \neg x_1\) and formulates it mathematically as the following BQM:
\[x_1 x_2 + 2x_1x_2\]The table below shows that this BQM has lower values for valid states of the NOT gate (e.g., \(x_1=0, x_2=1\)) and higher for invalid states (e.g., \(x_1=0, x_2=0\)).
¶ \(x_1\) \(x_2\) Valid? BQM Value \(0\) \(1\) Yes \(0\) \(1\) \(0\) Yes \(0\) \(0\) \(0\) No \(1\) \(1\) \(1\) No \(1\) Ocean’s dwavebinarycsp tool enables the following formulation of an AND gate as a BQM:
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories.constraint.gates as gates
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(gates.and_gate(['x1', 'x2', 'y1'])) # add an AND gate
>>> bqm = dwavebinarycsp.stitch(csp)
The resultant BQM of this AND gate may look like this:
>>> bqm # doctest: +SKIP
BinaryQuadraticModel({'x1': 0.0, 'x2': 0.0, 'y1': 6.0},
... {('x2', 'x1'): 2.0, ('y1', 'x1'): 4.0, ('y1', 'x2'): 4.0},
... 0,
... 'BINARY')
The members of the two dicts are linear and quadratic coefficients, respectively, the third term is a constant offset associated with the model, and the fourth shows the variable types in this model are binary.
For more detailed information on the parts of Ocean programming model and how they work together, see Ocean Software Stack.
Once you have a BQM that represents your problem, you sample it for solutions. Solving Problems by Sampling explains how to submit your problem for solution.
Ocean Software Stack¶
The Ocean software stack provides a chain of tools that implements the steps needed to solve your problem on a CPU/GPU or a DWave system. As described in the How a DWave System Solves Problems section, these steps include formulating the problem in a way the quantum computer understands (as a binary quadratic model) and solving the formulated problem by submitting it to a DWave system or classical sampler (the component used to minimize a BQM and therefore solve the original problem).
It’s helpful to visualize the tool chain as layers of abstraction, each of which handles one part of the solution procedure.
Abstraction Layers¶
The Ocean Software Stack graphic above divides Ocean software and its context into the following layers of functionality:
Compute Resources
The hardware on which the problem is solved. This might be a DWave quantum processor but it can also be the CPU of your laptop computer.
Samplers
Abstraction layer of the sampler functionality. Ocean tools implement several samplers that use the DWave system and classical compute resources. You can use the Ocean tools to customize a DWave sampler, create your own sampler, or use existing (classical) samplers to your code as you develop it.
Sampler API
Abstraction layer that represents the problem in a form that can access the selected sampler; for example, a dimod binary quadratic model (BQM) class representing your problem wrapped in a minorembedding composite that handles the mapping between your problem’s variables and the sampler’s graph.
Methods
Tools that help formulate a problem as binary quadratic models; for example dwave_networkx (repo) for graphrelated problems.
Application
Original problem in its context (“problem space”); for example, circuit fault diagnosis attempts to identify failed logic gates during chip manufacturing.
ProblemtoSolution Tool Chain¶
As described in the How a DWave System Solves Problems section, problems can be posed in a variety of formulations; the DWave system solves binary quadratic models. Ocean tools assist you in converting the problem from its original form to a form native to the DWave system and sending the compatible problem for solving.
This section will familiarize you with the different tools and how you can fit them together to solve your problem.
BottomUp Approach¶
One approach to envisioning how you can map your problemsolving process to Ocean software is to start from the bottom—the hardware doing the computations—and work your way up the Ocean stack to see the complete picture. This section shows how you might map each stage of the process to a layer of the Ocean stack.
Compute resource
You will likely use some combination of both local classical resources and a DWave system in your work with Ocean software. When would you use which?
 CPU/GPU: for offline testing, small problems that can be solved exactly or heuristically in a reasonable amount of time.
 QPU: hard problems or for learning how to use quantum resources to solve such problems.
 Hybrid of both QPU and CPU/GPU: large, complex problems that need to run classically but may benefit from having some parts allocated to a quantum computer for solution.
Sampler
Your sampler provides access to the compute resource that solves your problem.
The table below shows some Ocean samplers and considerations for selecting one or another.
¶ Computation Tool & Sampler Usage Notes Classical dimod ExactSampler()
Find all states for small (<20 variables) problems. For codedevelopment testing. Classical dimod RandomSampler()
Random sampler for testing. For codedevelopment testing. Classical dimod SimulatedAnnealingSampler()
Simulated annealing sampler for testing. For codedevelopment testing. Classical dwaveneal SimulatedAnnealingSampler()
Simulated annealing sampler. Quantum dwavesystem DWaveSampler()
Quick incorporation of the DWave system as a sampler. Typically part of a composite that handles minorembedding. Quantum dwavecloudclient Solver()
DWave system as a sampler.[1] For lowlevel control of problem submission. Hybrid dwavehybrid KerberosSampler()
dimodcompatible hybrid asynchronous decomposition sampler. For problems of arbitrary structure and size. Hybrid Leap’s LeapHybridSampler()
Cloudbased quantumclassical hybrid solver. For problems of arbitrary structure and size, especially large problems. dimod custom Write a custom sampler for special cases. See examples in dimod.
[1]  This sampler is for lowlevel work on communicating with SAPI and is not a dimod sampler. 
Pre and PostProcessing
Samplers can be composed of composite patterns that layer pre and postprocessing to binary quadratic programs without changing the underlying sampler.
The table below shows some Ocean composites and considerations for selecting one or another.
¶ Tool & Composite Usage Notes dwavesystem EmbeddingComposite()
Maps unstructured problems to a structured sampler. Enables quick incorporation of the DWave system as a sampler by handling the minorembedding to the QPU’s Chimera topology of qubits. dwavesystem FixedEmbeddingComposite()
Maps unstructured problems to a structured sampler. Uses a precalculated minorembedding for improved performance. dwavesystem TilingComposite()
Tiles small problems multiple times to a Chimerastructured sampler. Enables parallel sampling for small problems. dwavesystem VirtualGraphComposite()
Uses the DWave virtual graph feature for improved 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. dimod SpinReversalTransformComposite()
Applies spin reversal transform preprocessing. Improves QPU results by reducing the impact of possible analog and systematic errors. dimod StructureComposite()
Creates a structured composed sampler from an unstructured sampler. Maps from a problem graph (e.g., a square graph) to a sampler’s graph. In addition to composites that provide pre and postprocessing, Ocean also provides standalone tools to handle complex or large problems. For example:
 minorminer for minorembedding might be used to improve solutions by fine tuning parameters or incorporating problem knowledge into the embedding.
 qbsolv splits problems too large for the QPU into pieces solved either via a DWave system or a classical tabu solver.
Map to a Supported Format
Typically, you formulate your problem as a binary quadratic model (BQM), which you solve by submitting to the sampler (with its pre and postprocessing composite layers) you select based on the considerations listed above.
Ocean provides tools for formulating the BQM:
 dwavebinarycsp for constraint satisfaction problems with small constraints over binary variables. For example, many problems can be posed as satisfiability problems or with Boolean logic.
 dwave_networkx for implementing graphtheory algorithms of the DWave system. Many problems can be posed in a form of graphs—this tool handles the construction of BQMs for several standard graph algorithms such as maximum cut, cover, and coloring.
You might formulate a BQM mathematically; see Boolean NOT Gate for a mathematical formulation for a twovariable problem.
See the system documents for more information on techniques for formulating problems as BQMs.
Formulate
The first step in solving a problem is to express it in a mathematical formulation. For example, the Map Coloring problem is to assign a color to each region of a map such that any two regions sharing a border have different colors. To begin solving this problem on any computer, classical or quantum, it must be concretely defined; an intuitive approach, for the map problem, is to think of the regions as variables representing the possible set of colors, the values of which must be selected from some numerical scheme, such as natural numbers.
The selection function must express the problem’s constraints:
 Each region is assigned one color only, of C possible colors.
 The color assigned to one region cannot be assigned to adjacent regions.
Now solving the problem means finding a permissible value for each of the variables.
When formulating a problem for the DWave system, bear in mind a few considerations:
 Mathematical formulations must use binary variables because the solution is implemented physically with qubits, and so must translate to spins \(s_i \in {−1, +1}\) or equivalent binary values \(x_i \in {0, 1}\).
 Relationships between variables must be reducible to quadratic (e.g., a QUBO) because the problem’s parameters are represented by qubits’ weights and couplers’ strengths on a QPU.
 Formulations should be sparing in its number of variables because a QPU has a limited number of qubits and couplers.
 Alternative formulations may have different implications for performance.
Ocean demo applications, which formulate known problems, include:
TopDown Approach¶
Another approach to envisioning how you can map your problemsolving process to Ocean software is to start from the top—your (possibly abstractly defined) problem—and work your way down the Ocean stack.
Step  Description 

State the Problem  Define your problem concretely/mathematically; for example, as a constraint satisfaction problem or a graph problem. 
Formulate as a BQM  Reformulate an integer problem to use binary variables, for example, or convert a nonquadratic (highorder) polynomial to a QUBO. Ocean’s dwavebinarycsp and dwave_networkx can be helpful for some problems. 
Decompose  Allocate large problems to classical and quantum resources. Ocean’s dwavehybrid provides a framework and building blocks to help you create hybrid workflows. 
Embed  Consider whether your problem has repeated elements, such as logic gates, when
deciding what tool to use to minorembed your BQM on the QPU. You might
start with fully automated embedding (using EmbeddingComposite() for example)
and then seek performance improvements through minorminer. 
Configure the QPU  Use spinreversal transforms to reduce errors, for example, or examine the annealing with reverse anneal. See the system documents for more information of features that improve performance. 
DWave Compute Resources¶
Use Ocean’s samplers to solve problems on DWave’s compute resources (solvers) or locally on your CPU.
Solving Problems by Sampling¶
Having followed the steps of the Formulate Your Problem for a Quantum Computer section, you sample the BQM that now represents your problem for solutions. Ocean software provides quantum, classical, and quantumclassical hybrid samplers that run either remotely (for example, in DWave’s Leap environment) or locally on your CPU. These compute resources are known as solvers.
Note
Some classical samplers actually bruteforce solve small problems rather than sample, and these are also referred to as “solvers”.
Sample the BQM on a Solver¶
Ocean’s samplers enable you to submit your problem to remote or local compute resources (solvers) of different types:
 Hybrid Solvers such as Leap’s hybrid_v1 solver
 Classical Solvers such as
dimod.ExactSolver
for exact solutions to small problems  Quantum Solvers such a DWave 2000Q system.
The example code below submits the BQM of the AND gate of the Formulate Your Problem for a Quantum Computer section,
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({'x1': 0.0, 'x2': 0.0, 'y1': 6.0},
... {('x2', 'x1'): 2.0, ('y1', 'x1'): 4.0, ('y1', 'x2'): 4.0},
... 0, 'BINARY')
to a Leap hybrid solver.
In this case, dwavesystem’s
dwave.system.LeapHybridSampler
is the Ocean sampler and the remote compute
resource selected might be Leap hybrid solver hybrid_v1.
>>> from dwave.system import LeapHybridSampler
>>> sampler = LeapHybridSampler() # doctest: +SKIP
>>> answer = sampler.sample(bqm) # doctest: +SKIP
>>> print(answer) # doctest: +SKIP
x1 x2 y1 energy num_oc.
0 0 1 0 0.0 1
['BINARY', 1 rows, 1 samples, 3 variables]
Improve the Solutions¶
More complex problems than the ones shown above can benefit from some of the DWave system’s advanced features and Ocean software’s advanced tools.
When sampling directly on the DWave QPU, the mapping from problem variables to qubits, minorembedding, can significantly affect performance. Ocean tools perform this mapping heuristically so simply rerunning a problem might improve results. Advanced users may customize the mapping by directly using the minorminer tool, setting a minorembedding themselves, or using DWave’s probleminspector tool.
For example, the Boolean AND Gate example submits the BQM representing an AND gate to a DWave system, which requires mapping the problem’s logical variables to qubits on the QPU. The code below invokes DWave’s probleminspector tool to visualize the minorembedding.
>>> import dwave.inspector
>>> dwave.inspector.show(response) # doctest: +SKIP
DWave systems offer features such as spinreversal (gauge) transforms and anneal offsets, which reduce the impact of possible analog and systematic errors.
You can see the parameters and properties a sampler supports. For example, Ocean’s dwavesystem lets you use the DWave’s virtual graphs feature to simplify minorembedding. The following example maps a problem’s variables x, y to qubits 1, 5 and variable z to two qubits 0 and 4, and checks some features supported on the DWave system used as a sampler.
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.
>>> from dwave.system import DWaveSampler
>>> from dwave.system.composites import VirtualGraphComposite
>>> DWaveSampler(solver={'qpu':True}).properties['extended_j_range']
[2.0, 1.0]
>>> embedding = {'x': {1}, 'y': {5}, 'z': {0, 4}}
>>> sampler = VirtualGraphComposite(DWaveSampler(solver={'qpu':True}), embedding) # doctest: +SKIP
>>> sampler.parameters # doctest: +SKIP
{u'anneal_offsets': ['parameters'],
u'anneal_schedule': ['parameters'],
u'annealing_time': ['parameters'],
u'answer_mode': ['parameters'],
'apply_flux_bias_offsets': [],
u'auto_scale': ['parameters'], ...
Note that the composed sampler (VirtualGraphComposite()
in the last example)
inherits properties from the child sampler (DWaveSampler()
in that example).
See the resources under Additional Tutorials and the System Documentation for more information.
Hybrid Solvers¶
Quantumclassical hybrid is the use of both classical and quantum resources to solve problems, exploiting the complementary strengths that each provides. For an overview of, and motivation for, hybrid computing, see: Medium Article on Hybrid Computing.
Ocean software currently supports two types of hybrid solvers:
 Leap’s Hybrid Solvers are cloudbased hybrid compute resources.
 dwavehybrid Hybrid Solvers are hybrid solvers developed in Ocean’s dwavehybrid tool.
Leap’s Hybrid Solvers¶
DWave’s Leap quantum cloud service provides cloudbased hybrid solvers you can submit arbitrary BQMs to. These solvers, which implement stateoftheart classical algorithms together with intelligent allocation of the quantum processing unit (QPU) to parts of the problem where it benefits most, are designed to accommodate even very large problems. Leap’s solvers can relieve you of the burden of any current and future development and optimization of hybrid algorithms that best solve your problem.
Structural Imbalance in a Social Network is an example of submitting a problem for solution on a Leap hybrid solver.
dwavehybrid Hybrid Solvers¶
dwavehybrid provides you with a Python framework for building a variety of flexible hybrid workflows. These use quantum and classical resources together to find good solutions to your problem. For example, a hybrid workflow might use classical resources to find a problem’s hard core and send that to the QPU, or break a large problem into smaller pieces that can be solved on a QPU and then recombined.
The dwavehybrid framework enables rapid development of experimental prototypes, which provide insight into expected performance of the productized versions. It provides reference samplers and workflows you can quickly plug into your application code. You can easily experiment with customizing workflows that best solve your problem. You can also develop your own hybrid components to optimize performance.
Large Map Coloring and Problem With Many Variables are examples of solving problems using dwavehybrid samplers.
Classical Solvers¶
You might use a classical solver while developing your code or on a small version of your problem to verify your code. To solve a problem classically on your local machine, you configure a classical solver, either one of those included in the Ocean tools or your own.
Examples¶
Among several samplers provided in the dimod
tool for testing your code locally, is the ExactSolver()
that calculates the energy of all
possible samples for a given problem. Such a sampler can solve a small threevariable
problem like the AND gate of the Formulate Your Problem for a Quantum Computer section,
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({'x1': 0.0, 'x2': 0.0, 'y1': 6.0},
... {('x2', 'x1'): 2.0, ('y1', 'x1'): 4.0, ('y1', 'x2'): 4.0},
... 0, 'BINARY')
as follows:
>>> from dimod.reference.samplers import ExactSolver
>>> sampler = ExactSolver()
>>> response = sampler.sample(bqm)
>>> print(response) # doctest: +SKIP
x1 x2 y1 energy num_oc.
0 0 0 0 0.0 1
1 1 0 0 0.0 1
3 0 1 0 0.0 1
5 1 1 1 0.0 1
2 1 1 0 2.0 1
4 0 1 1 2.0 1
6 1 0 1 2.0 1
7 0 0 1 6.0 1
['BINARY', 8 rows, 8 samples, 3 variables]
Note that the first four samples are the valid states of the AND gate and have lower values than the second four, which represent invalid states.
If you use a classical solver running locally on your CPU, a single sample might provide the optimal solution.
This example solves a twovariable problem using the dwave_neal
simulated annealing sampler. For such a small problem, num_reads=10
most likely
finds the optimal solution.
>>> import neal
>>> solver = neal.SimulatedAnnealingSampler()
>>> sampleset = solver.sample_ising({'a': 0.5, 'b': 1.0}, {('a', 'b'): 1}, num_reads=10)
>>> sampleset.first.sample["a"] == sampleset.first.sample["b"] == 1
True
Quantum Solvers¶
Ocean’s dwavesystem tool enables you to use a DWave system as a sampler. In addition to DWaveSampler(), the tool provides a EmbeddingComposite() composite that maps unstructured problems to the graph structure of the selected sampler, a process known as minorembedding. For the AND gate of the Formulate Your Problem for a Quantum Computer section,
>>> import dimod
>>> bqm = dimod.BinaryQuadraticModel({'x1': 0.0, 'x2': 0.0, 'y1': 6.0},
... {('x2', 'x1'): 2.0, ('y1', 'x1'): 4.0, ('y1', 'x2'): 4.0},
... 0, 'BINARY')
the problem is defined on alphanumeric variables \(x1, x2, y1\), that must be mapped to the QPU’s numerically indexed qubits.
Because of the sampler’s probabilistic nature, you typically request multiple samples for a problem; this example sets num_reads to 1000.
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> sampler = EmbeddingComposite(DWaveSampler())
>>> sampleset = sampler.sample(bqm, num_reads=1000)
>>> print(sampleset) # doctest: +SKIP
x1 x2 y1 energy num_oc. chain_b.
0 1 0 0 0.0 321 0.0
1 1 1 1 0.0 97 0.0
2 0 0 0 0.0 375 0.0
3 0 1 0 0.0 206 0.0
4 1 0 1 2.0 1 0.333333
['BINARY', 5 rows, 1000 samples, 3 variables]
Note that the first four samples are the valid states of the AND gate and have lower energy than invalid state \(x1=1, x2=0, y1=1\).
Once you have configured a DWave Cloud Client configuration file as described in the Configuring Access to DWave Solvers section, your default solver configuration is used when you submit a problem without explicitly overriding it.
Several of the examples in the Getting Started Example’s section show how to submit problems to DWave systems.
Examples¶
See how Ocean tools are used with these endtoend examples.
Because many large, hard problems are best approached with quantumclassical hybrid solvers, a good place to start is with examples of the BeginnerLevel Examples: Hybrid Computing section and then learn how to work directly on the quantum computer with examples of the BeginnerLevel Examples: Using the QPU section.
BeginnerLevel Examples: Hybrid Computing¶
Structural Imbalance in a Social Network¶
This example solves a structuralimbalance problem, similar to the Leap demo and Jupyter Notebook, to demonstrate using Leap’s hybrid solver service on a problem of arbitrary structure and size.
Social networks map relationships between people or organizations onto graphs, with the people/organizations as nodes and relationships as edges; for example, Facebook friends form a social network. Signed social networks map both friendly and hostile relationships by assigning to edges either positive or negative values. Such networks are said to be structurally balanced when they can be cleanly divided into two sets, with each set containing only friends, and all relations between these sets are hostile. The measure of structural imbalance or frustration for a signed social network, when it cannot be cleanly divided, is the minimum number of edges that violate the social rule, “the enemy of my friend is my enemy.”
Finding a division that minimizes frustration is an NPhard graph problem (it can be viewed as an expansion of the wellknown maximum cut problem).
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavesystem and dwave_networkx.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system, classical sampler, or hybrid sampler. In this example, a function in Ocean software handles both steps. Our task is mainly to select the sampler used to solve the problem.
Formulate the Problem¶
For a social graph, G, this example simply builds a random sparse graph—using the NetworkX random_geometric_graph() function, which places uniformly at random a specified number of nodes, problem_node_count, in a unit cube, joining edges of any two if the distance is below a given radius—and randomly assigns \(0, 1\) signs to represent friendly and hostile relationships.
>>> import networkx as nx
>>> import random
>>> problem_node_count = 300
>>> G = nx.random_geometric_graph(problem_node_count, radius=0.0005*problem_node_count)
>>> G.add_edges_from([(u, v, {'sign': 2*random.randint(0, 1)1}) for u, v in G.edges])
Solve the Problem by Sampling¶
As mentioned above, this example uses Ocean’s dwave_networkx function, structural_imbalance(), to create the appropriate BQM to represent the problem graph and return a solution. It requires just the selection of a sampler.
DWave’s quantum cloud service provides cloudbased hybrid solvers you can submit arbitrary BQMs to. These solvers, which implement stateoftheart classical algorithms together with intelligent allocation of the quantum processing unit (QPU) to parts of the problem where it benefits most, are designed to accommodate even very large problems. Leap’s solvers can relieve you of the burden of any current and future development and optimization of hybrid algorithms that best solve your problem.
Ocean software’s dwavesystem LeapHybridSampler class enables you to easily incorporate Leap’s hybrid solvers into your application:
>>> from dwave.system import LeapHybridSampler
>>> sampler = LeapHybridSampler() # doctest: +SKIP
Finally, the returned set of frustrated edges and a bicoloring are counted and printed.
>>> import dwave_networkx as dnx
>>> imbalance, bicoloring = dnx.structural_imbalance(G, sampler) # doctest: +SKIP
>>> set1 = int(sum(list(bicoloring.values()))) # doctest: +SKIP
>>> print("One set has {} nodes; the other has {} nodes.".format(set1, problem_node_countset1)) # doctest: +SKIP
>>> print("The network has {} frustrated relationships.".format(len(list(imbalance.keys())))) # doctest: +SKIP
One set has 143 nodes; the other has 157 nodes.
The network has 904 frustrated relationships.
The graphic below visualizes the result of one such run.
Large Map Coloring¶
This example solves a map coloring problem to demonstrate an outofthebox use of Ocean’s classicalquantum hybrid sampler, dwavehybrid Kerberos, that enables you to solve problems of arbitrary structure and size.
Map coloring is an example of a constraint satisfaction problem (CSP). CSPs require that all a problem’s variables be assigned values, out of a finite domain, that result in the satisfying of all constraints. The mapcoloring CSP is to assign a color to each region of a map such that any two regions sharing a border have different colors.
The Map Coloring advanced example demonstrates lowerlevel coding of a similar problem, which gives the user more control over the solution procedure but requires the knowledge of some system parameters (e.g., knowing the maximum number of supported variables for the problem). Example Problem With Many Variables demonstrates the hybrid approach to problem solving in more detail by explicitly configuring the classical and quantum workflows.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers
 Ocean tools dwavehybrid and dwave_networkx.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. In this example, a function in Ocean software handles both steps. Our task is mainly to select the sampler used to solve the problem.
Formulate the Problem¶
This example uses the NetworkX read_adjlist function to read a text file, usa.adj, containing the states of the USA and their adjacencies (states with a shared border) into a graph. The original map information was found here on writeonly blog of Gregg Lind and looks like this:
# Author Gregg Lind
# License: Public Domain. I would love to hear about any projects you use if it for though!
#
AK,HI
AL,MS,TN,GA,FL
AR,MO,TN,MS,LA,TX,OK
AZ,CA,NV,UT,CO,NM
CA,OR,NV,AZ
CO,WY,NE,KS,OK,NM,AZ,UT
# Snipped here for brevity
You can see in the first noncomment line that the state of Alaska (“AK”) has Hawaii (“HI”) as an adjacency and that Alabama (“AL”) shares borders with four states.
>>> import networkx as nx
>>> G = nx.read_adjlist('usa.adj', delimiter = ',') # doctest: +SKIP
Graph G now represents states as vertices and each state’s neighbors as shared edges.
Solve the Problem by Sampling¶
Ocean’s dwave_networkx can return a minimum vertex coloring for a graph, which assigns a color to the vertices of a graph in a way that no adjacent vertices have the same color, using the minimum number of colors. Given a graph representing a map and a sampler, the min_vertex_coloring function tries to solve the map coloring problem.
dwavehybrid Kerberos is classicalquantum hybrid asynchronous decomposition sampler, which can decompose large problems into smaller pieces that it can run both classically (on your local machine) and on the DWave system. Kerberos finds best samples by running in parallel tabu search, simulated annealing, and DWave subproblem sampling on problem variables that have high impact. The only optional parameters set here are a maximum number of iterations and number of iterations with no improvement that terminates sampling. (See the Problem With Many Variables example for more details on configuring the classical and quantum workflows.)
>>> import dwave_networkx as dnx
>>> from hybrid.reference.kerberos import KerberosSampler
>>> coloring = dnx.min_vertex_coloring(G, sampler=KerberosSampler(), chromatic_ub=4, max_iter=10, convergence=3) # doctest: +SKIP
>>> set(coloring.values()) # doctest: +SKIP
{0, 1, 2, 3}
Note
The next code requires Matplotlib.
Plot the solution, if valid.
>>> import matplotlib.pyplot as plt # doctest: +SKIP
>>> node_colors = [coloring.get(node) for node in G.nodes()] # doctest: +SKIP
# Adjust the next line if using a different map
>>> if dnx.is_vertex_coloring(G, coloring): # doctest: +SKIP
... nx.draw(G, pos=nx.shell_layout(G, nlist = [list(G.nodes)[x:x+10] for x in range(0, 50, 10)] + [[list(G.nodes)[50]]]), with_labels=True, node_color=node_colors, node_size=400, cmap=plt.cm.rainbow)
>>> plt.show() # doctest: +SKIP
The graphic below shows the result of one such run.
 Structural Imbalance in a Social Network solves an arbitrarysized problem using a Leap hybrid solver.
 Large Map Coloring demonstrates using an outofthebox Ocean hybrid solver.
BeginnerLevel Examples: Using the QPU¶
Vertex Cover¶
This example solves a few small examples of a known graph problem, minimum vertex cover. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minimum vertex cover is the vertex cover of smallest size.
The purpose of this example is to help a new user to submit a problem to a DWave system using Ocean tools with little configuration or coding. Other examples demonstrate more advanced steps that might be needed for complex problems.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavesystem, dimod, and dwave_networkx.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. In this example, a function in Ocean software handles both steps. Our task is mainly to select the sampler used to solve the problem.
Formulate the Problem¶
The realworld application for this example might be a network provider’s routers interconnected by fiberoptic cables or traffic lights in a city’s intersections. It is posed as a graph problem; here, the fivenode star graph shown below. Intuitively, the solution to this small example is obvious — the minimum set of vertices that touch all edges is node 0, but the general problem of finding such a set is NP hard.
First, we run the code snippet below to create a star graph where node 0 is hub to four other nodes. The code uses NetworkX, which is part of your dwave_networkx or dwaveoceansdk installation.
>>> import networkx as nx
>>> s5 = nx.star_graph(4)
Solve the Problem by Sampling¶
For small numbers of variables, even your computer’s CPU can solve minimum vertex covers quickly. In this example, we demonstrate how to solve the problem both classically on your CPU and on the quantum computer.
Before using the DWave system, it can sometimes be helpful to test code locally. Here we select one of Ocean software’s test samplers to solve classically on a CPU. Ocean’s dimod provides a sampler that simply returns the BQM’s value for every possible assignment of variable values.
>>> from dimod.reference.samplers import ExactSolver
>>> sampler = ExactSolver()
The next code lines use Ocean’s dwave_networkx
to produce a BQM for our s5
graph and solve it on our selected sampler. In other
examples the BQM is explicitly created but the Ocean tool used here abstracts the
BQM: given the problem graph it returns a solution to a BQM it creates internally.
>>> import dwave_networkx as dnx
>>> print(dnx.min_vertex_cover(s5, sampler))
[0]
We now use a sampler from Ocean software’s dwavesystem to solve on a DWave system. In addition to DWaveSampler(), we use EmbeddingComposite(), which maps unstructured problems to the graph structure of the selected sampler, a process known as minorembedding: our problem star graph must be mapped to the QPU’s numerically indexed qubits.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> sampler = EmbeddingComposite(DWaveSampler())
>>> print(dnx.min_vertex_cover(s5, sampler))
[0]
Additional Problem Graphs¶
The figure below shows another fivenode (wheel) graph.
The code snippet below creates a new graph and solves on a DWave system.
>>> w5 = nx.wheel_graph(5)
>>> print(dnx.min_vertex_cover(w5, sampler)) # doctest: +SKIP
[0, 1, 3]
Note that the solution found for this problem is not unique; for example, [0, 2, 4] is also a valid solution.
>>> print(dnx.min_vertex_cover(w5, sampler)) # doctest: +SKIP
[0, 2, 4]
The figure below shows a tennode (circularladder) graph.
The code snippet below replaces the problem graph and submits twice to the DWave system for solution, producing two of the possible valid solutions.
>>> c5 = nx.circular_ladder_graph(5)
>>> print(dnx.min_vertex_cover(c5, sampler)) # doctest: +SKIP
[0, 2, 3, 6, 8, 9]
>>> print(dnx.min_vertex_cover(c5, sampler)) # doctest: +SKIP
[1, 3, 4, 5, 7, 9]
Summary¶
In the terminology of Ocean Software Stack, Ocean tools moved the original problem through the following layers:
 Application: an example application might be placing limited numbers of trafficmonitoring equipment on routers in a telecommunication network. Such problems can be posed as graphs.
 Method: graph mapping. Many different realworld problems can be formulated as instances of classified graph problems. Some of these are hard and the best currently known algorithms for solution may not scale well. Quantum computing might provide better solutions. In this example, vertex cover is a hard problem that can be solved on DWave systems.
 Sampler API: the Ocean tool internally builds a BQM with lowest values (“ground states”) that correspond to a minimum vertex cover and uses our selected sampler to solve it.
 Sampler: classical ExactSolver() and then DWaveSampler().
 Compute resource: first a local CPU then a DWave system.
Constrained Scheduling¶
This example solves a binary constraint satisfaction problem (CSP). CSPs require that all a problem’s variables be assigned values that result in the satisfying of all constraints. Here, the constraints are a company’s policy for scheduling meetings:
 Constraint 1: During business hours, all meetings must be attended in person at the office.
 Constraint 2: During business hours, participation in meetings is mandatory.
 Constraint 3: Outside business hours, meetings must be teleconferenced.
 Constraint 4: Outside business hours, meetings must not exceed 30 minutes.
Solving such a CSP means finding meetings that meet all the constraints.
The purpose of this example is to help a new user to formulate a constraint satisfaction problem using Ocean tools and solve it on a DWave system. Other examples demonstrate more advanced steps that might be needed for complex problems.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavebinarycsp, dwavesystem, and dimod.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. In this example, Ocean’s dwavebinarycsp tool builds the BQM based on the constraints we formulate.
Formulate the Problem¶
DWave systems solve binary quadratic models, so the first step is to express the problem with binary variables.
 Time of day is represented by binary variable
time
with value \(1\) for business hours and \(0\) for hours outside the business day.  Venue is represented by binary variable
location
with value \(1\) for office and \(0\) for teleconference.  Meeting duration is represented by variable
length
with value \(1\) for short meetings (under 30 minutes) and \(0\) for meetings of longer duration.  Participation is represented by variable
mandatory
with value \(1\) for mandatory participation and \(0\) for optional participation.
For large numbers of variables and constraints, such problems can be hard. This example has four binary variables, so only \(2^4=16\) possible meeting arrangements. As shown in the table below, it is a simple matter to work out all the combinations by hand to find solutions that meet all the constraints.
Time of Day  Venue  Duration  Participation  Valid? 

Business hours  Office  Short  Mandatory  Yes 
Business hours  Office  Short  Optional  No (violates 2) 
Business hours  Office  Long  Mandatory  Yes 
Business hours  Office  Long  Optional  No (violates 2) 
Business hours  Teleconference  Short  Mandatory  No (violates 1) 
Business hours  Teleconference  Short  Optional  No (violates 1, 2) 
Business hours  Teleconference  Long  Mandatory  No (violates 1) 
Business hours  Teleconference  Long  Optional  No (violates 1, 2) 
Nonbusiness hours  Office  Short  Mandatory  No (violates 3) 
Nonbusiness hours  Office  Short  Optional  No (violates 3) 
Nonbusiness hours  Office  Long  Mandatory  No (violates 3, 4) 
Nonbusiness hours  Office  Long  Optional  No (violates 3, 4) 
Nonbusiness hours  Teleconference  Short  Mandatory  Yes 
Nonbusiness hours  Teleconference  Short  Optional  Yes 
Nonbusiness hours  Teleconference  Long  Mandatory  No (violates 4) 
Nonbusiness hours  Teleconference  Long  Optional  No (violates 4) 
Ocean’s dwavebinarycsp enables the definition of constraints in different ways, including by defining functions that evaluate True when the constraint is met. The code below defines a function that returns True when all this example’s constraints are met.
def scheduling(time, location, length, mandatory):
if time: # Business hours
return (location and mandatory) # In office and mandatory participation
else: # Outside business hours
return ((not location) and length) # Teleconference for a short duration
The next code lines create a constraint from this function and adds it to CSP instance,
csp
, instantiated with binary variables.
>>> import dwavebinarycsp
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(scheduling, ['time', 'location', 'length', 'mandatory'])
This tool, dwavebinarycsp, can also convert the binary CSP to a BQM. The following code does so and the graph below provides a view on the BQM’s linear and quadratic coefficients, \(q_i\) and \(q_{i,j}\) respectively in \(\sum_i^N q_ix_i + \sum_{i<j}^N q_{i,j}x_i x_j\), which are the inputs for programming the quantum computer.
>>> bqm = dwavebinarycsp.stitch(csp)
Solve the Problem by Sampling¶
For small numbers of variables, even your computer’s CPU can solve CSPs quickly. Here we solve both classically on your CPU and on the quantum computer.
Before using the DWave system, it can sometimes be helpful to test code locally. Here we select one of Ocean software’s test samplers to solve classically on a CPU. Ocean’s dimod provides a sampler that simply returns the BQM’s value (energy) for every possible assignment of variable values.
>>> from dimod.reference.samplers import ExactSolver
>>> sampler = ExactSolver()
>>> solution = sampler.sample(bqm)
Valid solutions—assignments of variables that do not violate any constraint—should have the lowest value of the BQM:
The code below prints all those solutions (assignments of variables) for which the BQM has its minimum value[1].
>>> from math import isclose
>>> min_energy = solution.record.energy.min()
>>> for sample, energy in solution.data(['sample', 'energy']): # doctest: +SKIP
... if isclose(energy, min_energy, abs_tol=1.0):
... time = 'business hours' if sample['time'] else 'evenings'
... location = 'office' if sample['location'] else 'home'
... length = 'short' if sample['length'] else 'long'
... mandatory = 'mandatory' if sample['mandatory'] else 'optional'
... print("During {} at {}, you can schedule a {} meeting that is {}".format(time, location, length, mandatory))
...
During evenings at home, you can schedule a short meeting that is optional
During evenings at home, you can schedule a short meeting that is mandatory
During business hours at office, you can schedule a short meeting that is mandatory
During business hours at office, you can schedule a long meeting that is mandatory
[1]  Because it compares float values, this code uses the standard isclose
function to find values that are approximately equal. A small tolerance is needed
to overcome rounding errors but for simplicity a value of abs_tol=1.0 is used
because by default the stich() function increases the
energy of solutions that violate one constraint by min_classical_gap=2.0 . 
We now solve on a DWave system using sampler DWaveSampler() from Ocean software’s
dwavesystem. We also use
its EmbeddingComposite() composite to map our unstructured problem (variables
such as time
etc.) to the sampler’s graph structure (the QPU’s numerically
indexed qubits) in a process known as minorembedding. The next code sets up
a DWave system as the sampler.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> sampler = EmbeddingComposite(DWaveSampler())
Because the sampled solution is probabilistic, returned solutions may differ between runs. Typically, when submitting a problem to the system, we ask for many samples, not just one. This way, we see multiple “best” answers and reduce the probability of settling on a suboptimal answer. Below, we ask for 5000 samples.
>>> sampleset = sampler.sample(bqm, num_reads=5000)
The code below prints all those solutions (assignments of variables) for which the BQM has its minimum value and the number of times it was found.
>>> total = 0
... for sample, energy, occurrences in sampleset.data(['sample', 'energy', 'num_occurrences']): # doctest: +SKIP
... total = total + occurrences
... if isclose(energy, min_energy, abs_tol=1.0):
... time = 'business hours' if sample['time'] else 'evenings'
... location = 'office' if sample['location'] else 'home'
... length = 'short' if sample['length'] else 'long'
... mandatory = 'mandatory' if sample['mandatory'] else 'optional'
... print("{}: During {} at {}, you can schedule a {} meeting that is {}".format(occurrences, time, location, length, mandatory))
... print("Total occurrences: ", total)
...
1676: During business hours at office, you can schedule a long meeting that is mandatory
1229: During business hours at office, you can schedule a short meeting that is mandatory
1194: During evenings at home, you can schedule a short meeting that is optional
898: During evenings at home, you can schedule a short meeting that is mandatory
Total occurrences: 5000
Summary¶
In the terminology of Ocean Software Stack, Ocean tools moved the original problem through the following layers:
 Application: scheduling under constraints. There exist many CSPs that are computationally hard problems; for example, the mapcoloring problem is to color all regions of a map such that any two regions sharing a border have different colors. The jobshop scheduling problem is to schedule multiple jobs done on several machines with constraints on the machines’ execution of tasks.
 Method: constraint compilation.
 Sampler API: the Ocean tool builds a BQM with lowest values (“ground states”) that correspond to assignments of variables that satisfy all constraints.
 Sampler: classical ExactSolver() and then DWaveSampler().
 Compute resource: first a local CPU then a DWave system.
Boolean NOT Gate¶
This example solves a simple problem of a Boolean NOT gate to demonstrate the mathematical formulation of a problem as a binary quadratic model (BQM) and using Ocean tools to solve such problems on a DWave system. Other examples demonstrate the more advanced steps that are typically needed for solving actual problems.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers
 Ocean tools dwavesystem and dimod.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. In this example, we mathematically formulate the BQM and use Ocean tools to solve it on a DWave system.
Formulate the NOT Gate as a BQM¶
We use a sampler like the DWave systems to solve binary quadratic models (BQM)[1]: given \(M\) variables \(x_1,...,x_N\), where each variable \(x_i\) can have binary values \(0\) or \(1\), the system tries to find assignments of values that minimize
where \(q_i\) and \(q_{i,j}\) are configurable (linear and quadratic) coefficients. To formulate a problem for the DWave system is to program \(q_i\) and \(q_{i,j}\) so that assignments of \(x_1,...,x_N\) also represent solutions to the problem.
[1]  The “native” forms of BQM programmed into a DWave system are the Ising model traditionally used in statistical mechanics and its computerscience equivalent, shown here, the QUBO. 
Ocean tools can automate the representation of logic gates as a BQM, as demonstrated in the MultipleGate Circuit example.
This example demonstrates a mathematical formulation of the BQM. We can represent a NOT gate, \(z \Leftrightarrow \neg x\), where \(x\) is the gate’s input and \(z\) its output, using a penalty function:
This penalty function represents the NOT gate in that for assignments of variables that match valid states of the gate, the function evaluates at a lower value than assignments that would be invalid for the gate. Therefore, when the DWave minimizes a BQM based on this penalty function, it finds those assignments of variables that match valid gate states.
The table below shows that this function penalizes states that are not valid for the gate while no penalty is applied to assignments of variables that correctly represent a NOT gate. In this table, column x is all possible states of the gate’s input; column \(\mathbf{z}\) is the corresponding output values; column Valid? shows whether the variables represent a valid state for a NOT gate; column \(\mathbf{P}\) shows the value of the penalty for all possible assignments of variables.
x  \(\mathbf{z}\)  Valid?  \(\mathbf{P}\) 

\(0\)  \(1\)  Yes  \(0\) 
\(1\)  \(0\)  Yes  \(0\) 
\(0\)  \(0\)  No  \(1\) 
\(1\)  \(1\)  No  \(1\) 
For example, the state \(x, z=0,1\) of the first row represents valid assignments, and the value of \(P\) is
not penalizing the valid assignment of variables. In contrast, the state \(x, z=0,0\) of the third row represents an invalid assignment, and the value of \(P\) is
adding a value of \(1\) to the BQM being minimized. By penalizing both possible assignments of variables that represent invalid states of a NOT gate, the BQM based on this penalty function has minimal values (lowest energy states) for variable values that also represent a NOT gate.
See the system documentation for more information about penalty functions in general, and penalty functions for representing Boolean operations.
Sometimes penalty functions are of cubic or higher degree and must be reformulated as quadratic to be mapped to a binary quadratic model. For this penalty function we just need to drop the freestanding constant: the function’s values are simply shifted by \(1\) but still those representing valid states of the NOT gate are lower than those representing invalid states. The remaining terms of the penalty function,
are easily reordered in standard QUBO formulation:
where \(z=x_2\) is the NOT gate’s output, \(x=x_1\) the input, linear coefficients are \(q_1=q_2=1\), and quadratic coefficient is \(q_{1,2}=2\). These are the coefficients used to program a DWave system.
Often it is convenient to format the coefficients as an uppertriangular matrix:
See the system documentation for more information about formulating problems as QUBOs.
Solve the Problem by Sampling¶
We now solve on a DWave system using sampler DWaveSampler() from Ocean software’s
dwavesystem. We also use
its EmbeddingComposite() composite to map our unstructured problem (variables
such as time
etc.) to the sampler’s graph structure (the QPU’s numerically
indexed qubits) in a process known as minorembedding.
The next code sets up a DWave system as the sampler.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> sampler = EmbeddingComposite(DWaveSampler())
Because the sampled solution is probabilistic, returned solutions may differ between runs. Typically, when submitting a problem to the system, we ask for many samples, not just one. This way, we see multiple “best” answers and reduce the probability of settling on a suboptimal answer. Below, we ask for 5000 samples.
>>> Q = {('x', 'x'): 1, ('x', 'z'): 2, ('z', 'x'): 0, ('z', 'z'): 1}
>>> sampleset = sampler.sample_qubo(Q, num_reads=5000)
>>> print(sampleset) # doctest: +SKIP
x z energy num_oc. chain_.
0 0 1 1.0 2266 0.0
1 1 0 1.0 2732 0.0
2 0 0 0.0 1 0.0
3 1 1 0.0 1 0.0
['BINARY', 4 rows, 5000 samples, 2 variables]
Almost all the returned samples represent valid value assignments for a NOT gate, and minima (lowenergy states) of the BQM, and with high likelihood the best (lowest energy) samples satisfy the NOT gate formulation:
>>> sampleset.first.sample["x"] != sampleset.first.sample["z"]
True
Summary¶
In the terminology of Ocean Software Stack, Ocean tools moved the original problem through the following layers:
 The sampler API is a QUBO formulation of the problem.
 The sampler is DWaveSampler().
 The compute resource is a DWave system.
Boolean AND Gate¶
This example solves a simple problem of a Boolean AND gate on a DWave system to demonstrate programming the underlying hardware more directly; in particular, minorembedding a chain.
Other examples demonstrate more advanced steps that are typically needed for solving actual problems.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers
 Ocean tools dwavesystem. Optionally: probleminspector.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. In this example, we mathematically formulate the BQM and use Ocean tools to solve it on a DWave system.
Formulate the AND Gate as a BQM¶
Ocean tools can automate the representation of logic gates as a BQM, as demonstrated in the MultipleGate Circuit example. The Boolean NOT Gate example presents a mathematical formulation of a BQM for a Boolean gate in detail. Here we briefly repeat the steps of mathematically formulating a BQM while adding details on the underlying physical processes.
A DWave quantum processing unit (QPU) is a chip with interconnected qubits; for example, a DWave 2000Q has up to 2048 qubits connected in a Chimera topology. Programming it consists mostly of setting two inputs:
 Qubit bias weights: control the degree to which a qubit tends to a particular state.
 Qubit coupling strengths: control the degree to which two qubits tend to the same state.
The biases and couplings define an energy landscape, and the DWave quantum computer seeks the minimum energy of that landscape. Once you express your problem in a formulation[1] such that desired outcomes have low energy values and undesired outcomes high energy values, the DWave system solves your problem by finding the lowenergy states.
[1]  This formulation, called an objective function, corresponds to the Ising model traditionally used in statistical mechanics: given \(N\) variables \(s_1,...,s_N\), corresponding to physical Ising spins, where each variable \(s_i\) can have values \(1\) or \(+1\), the system energy for an assignment of values is,
\[E(\pmb{s}\pmb{h},\pmb{J}) = \left\{ \sum_{i=1}^N h_i s_i + \sum_{i<j}^N J_{i,j} s_i s_j \right\}\]
where \(h_i\) are biases and \(J_{i,j}\) couplings between spins. 
Here we use another binary quadratic model (BQM), the computerscience equivalent of the Ising model, the QUBO: given \(M\) variables \(x_1,...,x_N\), where each variable \(x_i\) can have binary values \(0\) or \(1\), the system tries to find assignments of values that minimize
where \(q_i\) and \(q_{i,j}\) are configurable (linear and quadratic) coefficients. To formulate a problem for the DWave system is to program \(q_i\) and \(q_{i,j}\) so that assignments of \(x_1,...,x_N\) also represent solutions to the problem.
This example represents the AND operation, \(z \Leftrightarrow x_1 \wedge x_2\), where \(x_1, x_2\) are the gate’s inputs and \(z\) its output, using a penalty function:
This penalty function represents the AND gate in that for assignments of variables that match valid states of the gate, the function evaluates at a lower value than assignments that would be invalid for the gate. Therefore, when the DWave system minimizes a BQM based on this penalty function, it finds those assignments of variables that match valid gate states.
You can verify that this penalty function represents the AND gate in the same way as was done in the Boolean NOT Gate example. See the DWave ProblemSolving Handbook for more information about penalty functions in general, and penalty functions for representing Boolean operations in particular.
For this example, the penalty function is quadratic, and easily reordered in the familiar QUBO formulation:
where \(z=x_3\) is the AND gate’s output, \(x_1, x_2\) the inputs, linear coefficients are \(q_1=3\), and quadratic coefficients are \(q_{1,2}=1, q_{1,3}=2, q_{2,3}=2\). The coefficients matrix is,
See the Getting Started with the DWave System and DWave ProblemSolving Handbook books for more information about formulating problems as QUBOs.
The line of code below sets the QUBO coefficients for this AND gate.
>>> Q = {('x1', 'x2'): 1, ('x1', 'z'): 2, ('x2', 'z'): 2, ('z', 'z'): 3}
Solve the Problem by Sampling: Automated MinorEmbedding¶
For reference, we first solve with the same steps used in the Boolean NOT Gate example before solving again while manually controlling additional parameters.
Again we use sampler DWaveSampler() from Ocean software’s dwavesystem and its EmbeddingComposite() composite to minorembed our unstructured problem (variables x1, x2, and z) on the sampler’s graph structure (the QPU’s numerically indexed qubits).
The next code sets up a DWave system as the sampler.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> sampler = DWaveSampler()
>>> sampler_embedded = EmbeddingComposite(sampler)
As before, we ask for 5000 samples.
>>> sampleset = sampler_embedded.sample_qubo(Q, num_reads=5000)
>>> print(sampleset) # doctest: +SKIP
x1 x2 z energy num_oc. chain_b.
0 0 1 0 0.0 1812 0.0
1 1 0 0 0.0 645 0.0
2 1 1 1 0.0 862 0.0
3 0 0 0 0.0 1676 0.0
5 1 0 0 0.0 1 0.333333
6 1 1 1 0.0 1 0.333333
4 0 1 1 1.0 3 0.0
['BINARY', 7 rows, 5000 samples, 3 variables]
All the returned samples from this execution represent valid value assignments for an AND gate, and minimize (are lowenergy states of) the BQM.
Note that lines 5 and 6 of output from this execution show samples that seem
identical to lines 1 and 2 (but with nonzero values in the rightmost column,
chain_breaks
). The next section addresses that.
Solve the Problem by Sampling: Nonautomated MinorEmbedding¶
This section looks more closely into minorembedding. Above and in the Boolean NOT Gate example, dwavesystem EmbeddingComposite() composite abstracted the minorembedding.
For simplicity, we first return to the NOT gate. The Boolean NOT Gate example found that a NOT gate can be represented by a BQM in QUBO form with the following coefficients:
>>> Q_not = {('x', 'x'): 1, ('x', 'z'): 2, ('z', 'x'): 0, ('z', 'z'): 1}
Minor embedding maps the two problem variables x and z to the indexed qubits of the DWave QPU. Here we do this mapping ourselves.
The next line of code looks at properties of the sampler. We select the first node, which on a QPU is a qubit, and print its adjacent nodes, i.e., coupled qubits.
>>> print(sampler.adjacency[sampler.nodelist[0]]) # doctest: +SKIP
{128, 4, 5, 6, 7}
For the DWave system the above code ran on, we see that the first available qubit is adjacent to qubit 4 and four others.
We can map the NOT problem’s two linear coefficients and single quadratic coefficient, \(q_1=q_2=1\) and \(q_{1,2}=2\), to biases on qubits 0 and 4 and coupling (0, 4). The figure below shows a minor embedding of the NOT gate into a DWave 2000Q QPU unit cell (four horizontal qubits connected to four vertical qubits via couplers).
The following code uses the FixedEmbeddingComposite composite to manually minorembed the problem. Its last line prints a confirmation that indeed the two selected qubits are adjacent (coupled).
>>> from dwave.system import FixedEmbeddingComposite
>>> sampler_embedded = FixedEmbeddingComposite(sampler, {'x': [0], 'z': [4]})
>>> print(sampler_embedded.adjacency["x"])
{'z'}
As before, we ask for 5000 samples.
>>> sampleset = sampler_embedded.sample_qubo(Q_not, num_reads=5000)
>>> print(sampleset) # doctest: +SKIP
x z energy num_oc. chain_.
0 0 1 1.0 2310 0.0
1 1 0 1.0 2688 0.0
2 0 0 0.0 2 0.0
['BINARY', 3 rows, 5000 samples, 2 variables]
 The BQM for a NOT gate, \(x z + 2xz\), can be represented by a fully connected \(K_2\) graph: its linear coefficients are weights of the two connected nodes with the single quadratic coefficient the weight of its connecting edge.
 The BQM for an AND gate, \(3z + x_1x_2  2x_1z  2x_2z\), needs a \(K_3\) graph.
We saw above how to minorembed a \(K_2\) graph on a DWave system. To minorembed a fully connected \(K_3\) graph requires chaining qubits.
To understand how a \(K_3\) graph fits on the Chimera topology of the QPU, look at the Chimera unit cell structure shown below. You cannot connect 3 qubits in a closed loop. However, you can make a closed loop of 4 qubits using, say, qubits 0, 1, 4, and 5.
To fit the 3qubit loop into a 4sided structure, create a chain of 2 qubits to represent a single variable. For example, chain qubit 0 and qubit 4 to represent variable \(z\).
The strength of the coupler between qubits 0 and 4, which represents variable \(z\), must be set to correlate the qubits strongly, so that in most solutions they have a single value for \(z\). (Remember the output in the Solve the Problem by Sampling: Automated MinorEmbedding section with its identical two last lines? This was likely due to the qubits in a chain taking different values.)
The code below uses Ocean’s dwavesystem FixedEmbeddingComposite() composite for manual minorembedding. Its last line prints a confirmation that indeed all three variables are connected. (coupled).
>>> embedding = {'x1': {1}, 'x2': {5}, 'z': {0, 4}}
>>> sampler_embedded = FixedEmbeddingComposite(sampler, embedding)
>>> print(sampler_embedded.adjacency) # doctest: +SKIP
{'x1': {'x2', 'z'}, 'x2': {'x1', 'z'}, 'z': {'x1', 'x2'}}
We ask for 5000 samples.
>>> Q = {('x1', 'x2'): 1, ('x1', 'z'): 2, ('x2', 'z'): 2, ('z', 'z'): 3}
>>> sampleset = sampler_embedded.sample_qubo(Q, num_reads=5000)
>>> print(sampleset) # doctest: +SKIP
x1 x2 z energy num_oc. chain_.
0 1 0 0 0.0 2107 0.0
1 0 1 0 0.0 684 0.0
2 1 1 1 0.0 1011 0.0
3 0 0 0 0.0 1193 0.0
4 1 0 1 1.0 4 0.0
5 1 1 0 1.0 1 0.0
['BINARY', 6 rows, 5000 samples, 3 variables]
Optionally, you can use the probleminspector to view the solution on the QPU.
Note
The next code requires the use of Ocean’s problem inspector.
>>> import dwave.inspector
>>> dwave.inspector.show(sampleset) # doctest: +SKIP
For comparison, the following code purposely weakens the chain strength (strength of the coupler between qubits 0 and 4, which represents variable \(z\)). The first line prints the range of values available for the DWave system this code is executed on. By default, FixedEmbeddingComposite() used the maximum chain strength, which is 2. By setting it to a low value of 0.25, the two qubits are not strongly correlated and the result is that many returned samples represent invalid states for an AND gate.
>>> print(sampler.properties['extended_j_range'])
[2.0, 1.0]
>>> sampler_embedded = FixedEmbeddingComposite(sampler, embedding)
>>> sampleset = sampler_embedded.sample_qubo(Q, num_reads=5000, chain_strength=0.25)
>>> print(sampleset) # doctest: +SKIP
x1 x2 z energy num_oc. chain_b.
0 1 0 0 0.0 629 0.0
1 0 1 0 0.0 693 0.0
3 1 1 1 0.0 660 0.0
4 0 0 0 0.0 812 0.0
2 1 0 1 1.0 773 0.333333
5 0 1 1 1.0 1432 0.333333
6 0 1 1 1.0 1 0.0
['BINARY', 7 rows, 5000 samples, 3 variables]
In this case, you are likely to see broken chains (nonzero values in the
chain_breaks
column) and calling the problem inspector shows these:
 Vertex Cover solves a small graph problem.
 Constrained Scheduling solves a small constraint satisfaction problem.
 Boolean NOT Gate mathematically formulates a BQM for a twovariable problem.
 Boolean AND Gate demonstrates programming the QPU more directly (minorembedding).
IntermediateLevel Examples¶
Map Coloring¶
This example solves a mapcoloring problem to demonstrate using Ocean tools to solve a problem on a DWave system. It demonstrates using the DWave system to solve a more complex constraint satisfaction problem (CSP) than that solved in the example of Constrained Scheduling.
Constraint satisfaction problems require that all a problem’s variables be assigned values, out of a finite domain, that result in the satisfying of all constraints. The mapcoloring CSP, for example, is to assign a color to each region of a map such that any two regions sharing a border have different colors.
The constraints for the mapcoloring problem can be expressed as follows:
 Each region is assigned one color only, of \(C\) possible colors.
 The color assigned to one region cannot be assigned to adjacent regions.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavebinarycsp and dwavesystem. For graphics, you will also need NetworkX.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Following the standard solution process described in Section How a DWave System Solves Problems, we (1) formulate the problem as a binary quadratic model (BQM) by using unary encoding to represent the \(C\) colors: each region is represented by \(C\) variables, one for each possible color, which is set to value \(1\) if selected, while the remaining \(C1\) variables are \(0\). (2) Solve the BQM with a DWave system as the sampler.
The full workflow is as follows:
 Formulate the problem as a graph, with provinces represented as nodes and shared borders as edges, using 4 binary variables (one per color) for each province.
 Create a binary constraint satisfaction problem and add all the needed constraints.
 Convert to a binary quadratic model.
 Sample.
 Plot a valid solution.
FourColor Canadian Map¶
This example finds a solution to the mapcoloring problem for a map of Canada using four colors (the sample code can easily be modified to change the number of colors or use different maps). Canada’s 13 provinces are denoted by postal codes:
Code  Province  Code  Province 

AB  Alberta  BC  British Columbia 
MB  Manitoba  NB  New Brunswick 
NL  Newfoundland and Labrador  NS  Nova Scotia 
NT  Northwest Territories  NU  Nunavut 
ON  Ontario  PE  Prince Edward Island 
QC  Quebec  SK  Saskatchewan 
YT  Yukon 
See Map Coloring for a description of the following code.
import dwavebinarycsp
from dwave.system import DWaveSampler, EmbeddingComposite
import networkx as nx
import matplotlib.pyplot as plt
# Represent the map as the nodes and edges of a graph
provinces = ['AB', 'BC', 'MB', 'NB', 'NL', 'NS', 'NT', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT']
neighbors = [('AB', 'BC'), ('AB', 'NT'), ('AB', 'SK'), ('BC', 'NT'), ('BC', 'YT'), ('MB', 'NU'),
('MB', 'ON'), ('MB', 'SK'), ('NB', 'NS'), ('NB', 'QC'), ('NL', 'QC'), ('NT', 'NU'),
('NT', 'SK'), ('NT', 'YT'), ('ON', 'QC')]
# Function for the constraint that two nodes with a shared edge not both select one color
def not_both_1(v, u):
return not (v and u)
# Function that plots a returned sample
def plot_map(sample):
G = nx.Graph()
G.add_nodes_from(provinces)
G.add_edges_from(neighbors)
# Translate from binary to integer color representation
color_map = {}
for province in provinces:
for i in range(colors):
if sample[province+str(i)]:
color_map[province] = i
# Plot the sample with colorcoded nodes
node_colors = [color_map.get(node) for node in G.nodes()]
nx.draw_circular(G, with_labels=True, node_color=node_colors, node_size=3000, cmap=plt.cm.rainbow)
plt.show()
# Valid configurations for the constraint that each node select a single color
one_color_configurations = {(0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)}
colors = len(one_color_configurations)
# Create a binary constraint satisfaction problem
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
# Add constraint that each node (province) select a single color
for province in provinces:
variables = [province+str(i) for i in range(colors)]
csp.add_constraint(one_color_configurations, variables)
# Add constraint that each pair of nodes with a shared edge not both select one color
for neighbor in neighbors:
v, u = neighbor
for i in range(colors):
variables = [v+str(i), u+str(i)]
csp.add_constraint(not_both_1, variables)
# Convert the binary constraint satisfaction problem to a binary quadratic model
bqm = dwavebinarycsp.stitch(csp)
# Set up a solver using the local system’s default DWave Cloud Client configuration file
# and sample 1000 times
sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm, num_reads=1000)
# Plot the lowestenergy sample if it meets the constraints
sample = sampleset.first.sample
if not csp.check(sample):
print("Failed to color map")
else:
plot_map(sample)
Note
You can skip directly to the complete code for the problem here: Map Coloring: Full Code.
The example uses the DWave binary CSP tool to set up constraints and convert the CSP to a binary quadratic model, dwavesystem to set up a DWave system as the sampler, and NetworkX to plot results.
>>> import dwavebinarycsp
>>> from dwave.system import DWaveSampler, EmbeddingComposite
>>> import networkx as nx
>>> import matplotlib.pyplot as plt # doctest: +SKIP
Start by formulating the problem as a graph of the map with provinces as nodes and shared borders between provinces as edges (e.g., “(‘AB’, ‘BC’)” is an edge representing the shared border between British Columbia and Alberta).
>>> # Represent the map as the nodes and edges of a graph
>>> provinces = ['AB', 'BC', 'MB', 'NB', 'NL', 'NS', 'NT', 'NU', 'ON', 'PE',
... 'QC', 'SK', 'YT']
>>> neighbors = [('AB', 'BC'), ('AB', 'NT'), ('AB', 'SK'), ('BC', 'NT'), ('BC', 'YT'),
... ('MB', 'NU'), ('MB', 'ON'), ('MB', 'SK'), ('NB', 'NS'), ('NB', 'QC'),
... ('NL', 'QC'), ('NT', 'NU'), ('NT', 'SK'), ('NT', 'YT'), ('ON', 'QC')]
Create a binary constraint satisfaction problem based on two types of constraints, where csp is the dwavebinarycsp CSP object:
csp.add_constraint(one_color_configurations, variables)
represents the constraint that each node (province) select a single color, as represented by valid configurationsone_color_configurations = {(0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)}
csp.add_constraint(not_both_1, variables)
represents the constraint that two nodes (provinces) with a shared edge (border) not both select the same color.
>>> # Function for the constraint that two nodes with a shared edge not both select
>>> # one color
>>> def not_both_1(v, u):
... return not (v and u)
...
>>> # Valid configurations for the constraint that each node select a single color
>>> one_color_configurations = {(0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)}
>>> colors = len(one_color_configurations)
...
>>> # Create a binary constraint satisfaction problem
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
...
>>> # Add constraint that each node (province) select a single color
>>> for province in provinces:
... variables = [province+str(i) for i in range(colors)]
... csp.add_constraint(one_color_configurations, variables)
...
>>> # Add constraint that each pair of nodes with a shared edge not both select one color
>>> for neighbor in neighbors:
... v, u = neighbor
... for i in range(colors):
... variables = [v+str(i), u+str(i)]
... csp.add_constraint(not_both_1, variables)
Convert the CSP into a binary quadratic model so it can be solved on the DWave system.
>>> bqm = dwavebinarycsp.stitch(csp)
The next code sets up a DWave system as the sampler and requests 1000 samples.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
>>> # Sample 1000 times
>>> sampler = EmbeddingComposite(DWaveSampler()) # doctest: +SKIP
>>> sampleset = sampler.sample(bqm, num_reads=1000) # doctest: +SKIP
...
>>> # Check that a good solution was found
>>> sample = sampleset.first.sample # doctest: +SKIP
>>> if not csp.check(sample): # doctest: +SKIP
... print("Failed to color map. Try sampling again.")
... else:
... print(sample)
Note
The next code requires Matplotlib.
Plot a valid solution.
# Function that plots a returned sample
def plot_map(sample):
G = nx.Graph()
G.add_nodes_from(provinces)
G.add_edges_from(neighbors)
# Translate from binary to integer color representation
color_map = {}
for province in provinces:
for i in range(colors):
if sample[province+str(i)]:
color_map[province] = i
# Plot the sample with colorcoded nodes
node_colors = [color_map.get(node) for node in G.nodes()]
nx.draw_circular(G, with_labels=True, node_color=node_colors, node_size=3000, cmap=plt.cm.rainbow)
plt.show()
>>> plot_map(sample) # doctest: +SKIP
The plot shows a solution returned by the DWave solver. No provinces sharing a border have the same color.
Note
You can copy the complete code for the problem here: Map Coloring: Full Code.
MultipleGate Circuit¶
This example solves a logic circuit problem to demonstrate using Ocean tools to solve a problem on a DWave system. It builds on the discussion in the Boolean AND Gate example about the effect of minorembedding on performance.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers
 Ocean tools dwavebinarycsp and dwavesystem. For the optional graphics, you will also need Matplotlib and probleminspector.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Formulating the Problem as a CSP¶
This example demonstrates two formulations of constraints from the problem’s logic gates:
 Single comprehensive constraint.
import dwavebinarycsp
def logic_circuit(a, b, c, d, z):
not1 = not b
or2 = b or c
and3 = a and not1
or4 = or2 or d
and5 = and3 and or4
not6 = not or4
or7 = and5 or not6
return (z == or7)
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(logic_circuit, ['a', 'b', 'c', 'd', 'z'])
 Multiple small constraints.
import dwavebinarycsp
import dwavebinarycsp.factories.constraint.gates as gates
import operator
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(operator.ne, ['b', 'not1']) # add NOT 1 gate
csp.add_constraint(gates.or_gate(['b', 'c', 'or2'])) # add OR 2 gate
csp.add_constraint(gates.and_gate(['a', 'not1', 'and3'])) # add AND 3 gate
csp.add_constraint(gates.or_gate(['d', 'or2', 'or4'])) # add OR 4 gate
csp.add_constraint(gates.and_gate(['and3', 'or4', 'and5'])) # add AND 5 gate
csp.add_constraint(operator.ne, ['or4', 'not6']) # add NOT 6 gate
csp.add_constraint(gates.or_gate(['and5', 'not6', 'z'])) # add OR 7 gate
Note
dwavebinarycsp works best for constraints of up to 4 variables; it may not function as expected for constraints of over 8 variables.
The next line of code converts the constraints into a BQM that we solve by sampling.
# Convert the binary constraint satisfaction problem to a binary quadratic model
bqm = dwavebinarycsp.stitch(csp)
Binary Quadratic Model:
BinaryQuadraticModel({'a': 6.0, 'c': 2.0, 'z': 6.0, 'd': 0.0, 'b': 2.0,
'aux0': 0.0, 'aux1': 0.0}, {('aux1', 'a'): 4.0, ('z', 'a'): 0.0, ('aux1', 'aux0'): 0.0,
('z', 'aux1'): 4.0, ('b', 'a'): 2.0, ('d', 'c'): 0.0, ('z', 'c'): 2.0, ('z', 'd'): 0.0,
('z', 'aux0'): 4.0, ('z', 'b'): 4.0, ('c', 'a'): 2.0, ('c', 'aux0'): 4.0, ('c', 'b'): 2.0,
('d', 'a'): 2.0, ('d', 'aux1'): 4.0, ('d', 'aux0'): 2.0, ('b', 'aux0'): 2.0,
('aux0', 'a'): 2.0, ('c', 'aux1'): 2.0, ('b', 'aux1'): 0.0, ('d', 'b'): 0.0},
2.5, Vartype.BINARY)
Embedding 1:
{'a': [946, 951, 959],
'aux0': [954, 957],
'aux1': [955, 1083, 1086, 1081, 1080],
'b': [948, 956],
'c': [944, 958, 950],
'd': [953, 825, 831, 824],
'z': [952]}
Embedding 2:
{'a': [1104],
'aux0': [1110, 1102],
'aux1': [1107, 981, 979, 977, 976],
'b': [1111, 1103, 1098],
'c': [1105, 1233, 1232, 1238],
'd': [1108, 1100, 1099],
'z': [1106, 1109]}
Embedding 3:
{'a': [1838, 1846, 1840, 1847],
'aux0': [1839],
'aux1': [1836, 1835],
'b': [1837, 1831, 1829, 1826, 1830],
'c': [1706, 1834, 1711],
'd': [1705, 1833, 1709],
'z': [1704, 1832]}
Embedding 4:
{'a': [665, 537, 540, 539],
'aux0': [669, 661, 656],
'aux1': [664, 668],
'b': [670, 662, 659],
'c': [667],
'd': [666, 794, 798, 793, 795],
'z': [671, 663]}
Binary Quadratic Model:
BinaryQuadraticModel({'a': 0.0, 'c': 2.0, 'b': 0.0, 'not1': 2.0, 'd': 2.0,
'or4': 0.0, 'or2': 4.0, 'not6': 0.0, 'and5': 8.0, 'z': 2.0, 'and3': 6.0},
{('not6', 'and5'): 2.0, ('or2', 'c'): 4.0, ('or4', 'd'): 4.0, ('or4', 'and3'): 2.0,
('and3', 'a'): 4.0, ('and5', 'and3'): 4.0, ('z', 'and5'): 4.0, ('or4', 'not6'): 4.0,
('or4', 'or2'): 4.0, ('z', 'not6'): 4.0, ('or2', 'd'): 2.0, ('or4', 'and5'): 4.0,
('c', 'b'): 2.0, ('b', 'not1'): 4.0, ('not1', 'and3'): 4.0, ('or2', 'b'): 4.0,
('not1', 'a'): 2.0}, 5.5, Vartype.BINARY)
Embedding 1:
{'a': [1870, 1737, 1862, 1856, 1865, 1609],
'and3': [1728, 1600],
'and5': [1731, 1735],
'b': [1603],
'c': [1605],
'd': [1606],
'not1': [1604, 1612],
'not6': [1730],
'or2': [1607, 1602],
'or4': [1733, 1729, 1601],
'z': [1734]}
Embedding 2:
{'a': [578, 450, 452],
'and3': [448, 576],
'and5': [447, 455],
'b': [574, 569],
'c': [572],
'd': [444],
'not1': [582],
'not6': [442, 446, 454],
'or2': [440, 568],
'or4': [441, 445, 453],
'z': [451]}
Embedding 3:
{'a': [1051],
'and3': [1058, 1060, 1052],
'and5': [1059],
'b': [921, 924],
'c': [926],
'd': [1054],
'not1': [1049, 1055],
'not6': [1063, 1056],
'or2': [922, 1050],
'or4': [1061, 1053, 1048],
'z': [1062]}
Embedding 4:
{'a': [1438],
'and3': [1560, 1432],
'and5': [1688, 1695],
'b': [1561, 1566],
'c': [1564],
'd': [1565],
'not1': [1439, 1433],
'not6': [1691, 1693],
'or2': [1563],
'or4': [1562, 1567, 1690],
'z': [1694]}
The first approach, which consolidates the circuit as a single constraint, yields a binary quadratic model with 7 variables: 4 inputs, 1, output, and 2 ancillary variables. The second approach, which creates a constraint satisfaction problem from multiple small constraints, yields a binary quadratic model with 11 variables: 4 inputs, 1 output, and 6 intermediate outputs of the logic gates.
You can see the binary quadratic models here: MultipleGate Circuit: Further Details.
MinorEmbedding and Sampling¶
Algorithmic minorembedding is heuristic—solution results vary significantly based on the minorembedding found.
The next code sets up a DWave system as the sampler.
Note
The code below sets a sampler without specifying SAPI parameters. Configure a default solver as described in Configuring Access to DWave Solvers to run the code as is, or see dwavecloudclient to access a particular solver by setting explicit parameters in your code or environment variables.
from dwave.system import DWaveSampler, EmbeddingComposite
# Set up a DWave system as the sampler
sampler = EmbeddingComposite(DWaveSampler())
Next, we ask for 1000 samples and separate those that satisfy the CSP from those that fail to do so.
sampleset = sampler.sample(bqm, num_reads=1000)
# Check how many solutions meet the constraints (are valid)
valid, invalid, data = 0, 0, []
for datum in sampleset.data(['sample', 'energy', 'num_occurrences']):
if (csp.check(datum.sample)):
valid = valid+datum.num_occurrences
for i in range(datum.num_occurrences):
data.append((datum.sample, datum.energy, '1'))
else:
invalid = invalid+datum.num_occurrences
for i in range(datum.num_occurrences):
data.append((datum.sample, datum.energy, '0'))
>>> print(valid, invalid) # doctest: +SKIP
For the single constraint approach, 4 runs with their different minorembeddings yield significantly varied results, as shown in the following table:
Embedding  (valid, invalid) 

1  (39, 961) 
2  (1000, 0) 
3  (998, 2) 
4  (316, 684) 
You can see the minorembeddings found here: MultipleGate Circuit: Further Details; below those embeddings are visualized graphically.
Optionally, you can use the probleminspector to view the solution on the QPU.
Note
The next code requires the use of Ocean’s problem inspector.
>>> import dwave.inspector
>>> dwave.inspector.show(sampleset) # doctest: +SKIP
For the second approach, which creates a constraint satisfaction problem based on multiple small constraints, a larger number of variables (11 versus 7) need to be minorembedded, resulting in worse performance. However, performance can be greatly improved in this case by increasing the chain strength (to 2 instead of the default of 1).
Embedding  Chain Strength  (valid, invalid) 

1  1  (7, 993) 
2  1  (417, 583) 
3  2  (941, 59) 
4  2  (923, 77) 
You can see the minorembeddings used here: MultipleGate Circuit: Further Details; below those embeddings are visualized graphically.
Looking at the Results¶
You can verify the solution to the circuit problem by checking an arbitrary valid or invalid sample:
>>> print(sampleset.first.sample) # doctest: +SKIP
{'a': 1, 'c': 0, 'b': 0, 'not1': 1, 'd': 1, 'or4': 1, 'or2': 0, 'not6': 0,
'and5': 1, 'z': 1, 'and3': 1}
For the lowestenergy sample of the last run, found above, the inputs are \(a, b, c, d = 1, 0, 0, 1\) and the output is \(z=1\), which indeed matches the analytical solution for the circuit,
The example code above converted the constraint satisfaction problem to a binary quadratic model using the default minimum energy gap of 2. Therefore, each constraint violated by the solution increases the energy level of the binary quadratic model by at least 2 relative to ground energy. You can also plot the energies for valid and invalid samples:
import matplotlib.pyplot as plt
plt.ion()
plt.scatter(range(len(data)), [x[1] for x in data], c=['y' if (x[2] == '1') \
else 'r' for x in data],marker='.')
plt.xlabel('Sample')
plt.ylabel('Energy')
You can see in the graph that valid solutions have energy 9.5 and invalid solutions energies of 7.5, 5.5, and 3.5.
>>> for datum in sampleset.data(['sample', 'energy', 'num_occurrences', 'chain_break_fraction']): # doctest: +SKIP
... print(datum)
...
Sample(sample={'a': 1, 'c': 0, 'b': 1, 'not1': 0, 'd': 1, 'or4': 1, 'or2': 1, 'not6': 0, 'and5': 0, 'z': 0, 'and3': 0}, energy=9.5, num_occurrences=13, chain_break_fraction=0.0)
Sample(sample={'a': 1, 'c': 1, 'b': 1, 'not1': 0, 'd': 0, 'or4': 1, 'or2': 1, 'not6': 0, 'and5': 0, 'z': 0, 'and3': 0}, energy=9.5, num_occurrences=14, chain_break_fraction=0.0)
# Snipped this section for brevity
Sample(sample={'a': 1, 'c': 0, 'b': 0, 'not1': 1, 'd': 1, 'or4': 1, 'or2': 0, 'not6': 1, 'and5': 1, 'z': 1, 'and3': 1}, energy=7.5, num_occurrences=3, chain_break_fraction=0.09090909090909091)
Sample(sample={'a': 1, 'c': 1, 'b': 0, 'not1': 1, 'd': 1, 'or4': 1, 'or2': 1, 'not6': 1, 'and5': 1, 'z': 1, 'and3': 1}, energy=7.5, num_occurrences=1, chain_break_fraction=0.18181818181818182)
Sample(sample={'a': 1, 'c': 1, 'b': 1, 'not1': 1, 'd': 0, 'or4': 1, 'or2': 1, 'not6': 1, 'and5': 1, 'z': 1, 'and3': 1}, energy=5.5, num_occurrences=4, chain_break_fraction=0.18181818181818182)
# Snipped this section for brevity
Sample(sample={'a': 1, 'c': 1, 'b': 1, 'not1': 1, 'd': 0, 'or4': 1, 'or2': 1, 'not6': 1, 'and5': 0, 'z': 1, 'and3': 1}, energy=3.5, num_occurrences=1, chain_break_fraction=0.2727272727272727)
You can see, for example, that sample:
Sample(sample={'a': 1, 'c': 1, 'b': 0, 'not1': 1, 'd': 1, 'or4': 1, 'or2': 1, 'not6': 1, 'and5': 1, 'z': 1, 'and3': 1}, energy=7.5, num_occurrences=1, chain_break_fraction=0.18181818181818182)
has a higher energy by 2 than the ground energy. It is expected that this solution violates a single constraint, and you can see that it violates constraint:
Constraint.from_configurations(frozenset([(1, 0, 0), (0, 1, 0), (0, 0, 0), (1, 1, 1)]), ('a', 'not1', 'and3'), Vartype.BINARY, name='AND')
on AND gate 3.
Note also that for samples with higher energy there tends to be an increasing fraction of broken chains: zero for the valid solutions but rising to almost 30% for solutions that have three broken constraints.
Problem With Many Variables¶
This example solves a graph problem with too many variables to fit onto the QPU.
The purpose of this example is to illustrate a hybrid solution—the combining of classical and quantum resources—to a problem that cannot be mapped in its entirety to the DWave system due to the number of its variables. Hard optimization problems might have many variables; for example, scheduling or allocation of resources. In such cases, quantum resources are used as an accelerator much as GPUs are for graphics.
Note
For fully connected graphs, the number of edges grows very quickly with increased nodes, degrading performance. The current example uses 100 nodes but with a degree of three (each node connects to three other nodes). You can increase the number of nodes substantially as long as you keep the graph sparse.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavesystem, dimod, and dwavehybrid.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
Section How a DWave System Solves Problems describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a Dwave system or classical sampler. This example uses dwavehybrid to combine a tabu search on a CPU with the submission of parts of the (large) problem to the DWave system.
Formulate the Problem¶
This example uses a synthetic problem for illustrative purposes: a NetworkX generated graph, NetworkX barabasi_albert_graph(), with random +1 or 1 couplings assigned to its edges.
# Represent the graph problem as a binary quadratic model
import dimod
import networkx as nx
import random
graph = nx.barabasi_albert_graph(100, 3, seed=1) # Build a quasirandom graph
# Set node and edge values for the problem
h = {v: 0.0 for v in graph.nodes}
J = {edge: random.choice([1, 1]) for edge in graph.edges}
bqm = dimod.BQM(h, J, offset=0, vartype=dimod.SPIN)
Create a Hybrid Workflow¶
The following simple workflow uses a RacingBranches
class to iterate two
Branch
classes in parallel: a tabu search, InterruptableTabuSampler
,
which is interrupted to potentially incorporate samples from subproblems (subsets of the problem
variables and structure) by EnergyImpactDecomposer  QPUSubproblemAutoEmbeddingSampler  SplatComposer
, which decomposes the
problem by selecting variables with the greatest energy impact, submits these to
the DWave system, and merges the subproblem’s samples into the latest problem samples.
In this case, subproblems contain 30 variables in a rolling window that can cover up
to 75 percent of the problem’s variables.
# Set a workflow of tabu search in parallel to submissions to a DWave system
import hybrid
workflow = hybrid.Loop(
hybrid.RacingBranches(
hybrid.InterruptableTabuSampler(),
hybrid.EnergyImpactDecomposer(size=30, rolling=True, rolling_history=0.75)
 hybrid.QPUSubproblemAutoEmbeddingSampler()
 hybrid.SplatComposer())  hybrid.ArgMin(), convergence=3)
Solve the Problem Using Hybrid Resources¶
Once you have a hybrid workflow, you can run and tune it within the dwavehybrid framework or convert it to a dimod sampler.
# Convert to dimod sampler and run workflow
result = hybrid.HybridSampler(workflow).sample(bqm)
While the tabu search runs locally, one or more subproblems are sent to the QPU.
>>> print("Solution: sample={}".format(result.first)) # doctest: +SKIP
Solution: sample=Sample(sample={0: 1, 1: 1, 2: 1, 3: 1, 4: 1, ... energy=169.0, num_occurrences=1)
 Map Coloring example solves a more complex constraint satisfaction problem.
 MultipleGate Circuit looks more deeply at minorembedding.
 Problem With Many Variables builds a hybrid workflow and solver for a large graph problem.
AdvancedLevel Examples¶
Using the Problem Inspector¶
This example solves a graph partitioning problem to show how DWave’s inspector tool can help you evaluate the minorembedding used in your problem submissions to the quantum computer.
Example Requirements¶
To run the code in this example, the following is required.
 The requisite information for problem submission through SAPI, as described in Configuring Access to DWave Solvers.
 Ocean tools dwavesystem and dwaveinspector.
If you installed dwaveoceansdk
and ran dwave setup
, your installation should meet these requirements.
In DWave’s Leap IDE, the default workspace
meets these requirements.
Solution Steps¶
The How a DWave System Solves Problems section describes the process of solving problems on the quantum computer in two steps: (1) Formulate the problem as a binary quadratic model (BQM) and (2) Solve the BQM with a DWave system or classical sampler. In this example, a QUBO is formulated with simple math, the problem is submitted naively to the QPU, its minor embedding examined using the problem inspector, and the submission improved.
Formulate the Problem¶
This example uses a synthetic problem for illustrative purposes: a NetworkX generated graph, NetworkX random_geometric_graph(). The problem of interest here, which is NPhard, is to try and find the best division of the graph’s nodes into two equal sets with a minimum number of edges between the two groups.
import networkx as nx
graph_nodes = 16
G = nx.random_geometric_graph(n=graph_nodes, radius=.5, dim=2)
This example formulates the BQM as a QUBO using the same steps described in detail in the Graph Partitioning code example of the DWave Code Examples GitHub repository.
from collections import defaultdict
from itertools import combinations
gamma = 60
Q = defaultdict(int)
# Fill in Q matrix
for u, v in G.edges:
Q[(u,u)] += 1
Q[(v,v)] += 1
Q[(u,v)] += 2
for i in G.nodes:
Q[(i,i)] += gamma*(1len(G.nodes))
for i, j in combinations(G.nodes, 2):
Q[(i,j)] += 2*gamma
Print the range of values for the generated QUBO’s elements:
>>> print("Maximum element is {:.2f} and minimum is {:.2f}.".format(max(Q.values()), min(Q.values()))) # doctest: +SKIP
Maximum element is 120.00 and minimum is 898.00.
Solve the Problem by Sampling¶
Note
Importing the problem inspector activates for the session the capture of data such as problems sent to the QPU and returned responses, relevant details of minorembedding, and warnings. The recommended workflow is to import it at the start of your coding session or at least before submitting your problem, as is done below.
import numpy as np
from dwave.system import DWaveSampler, EmbeddingComposite
# Import the problem inspector to begin data capture
import dwave.inspector
sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
num_reads = 1000
sampleset = sampler.sample_qubo(Q, num_reads=num_reads)
Check the best returned answer:
>>> print("Number of nodes in one set is {}, in the other, {}. \nEnergy is {}.".format(
... sum(sampleset.first.sample.values()),
... graph_nodes  sum(sampleset.first.sample.values()),
... sampleset.first.energy)) # doctest: +SKIP
Number of nodes in one set is 8, in the other, 8.
Energy is 3813.0.
One simple measure of the overall quality of the returned samples is the percentage of samples based on chains with high breakage rates. Here a rate above one third is chosen as the acceptable threshold:
>>> print("Percentage of samples with high rates of breaks is {}.".format(
... np.count_nonzero(sampleset.record.chain_break_fraction > 0.33)/num_reads*100)) # doctest: +SKIP
Percentage of samples with high rates of breaks is 78.7.
Use the problem inspector on the returned samples:
>>> dwave.inspector.show(sampleset) # doctest: +SKIP
The problem inspector can also display the embedded problem, showing the qubits chains viewed on a background representation of the QPU topology:
Using the same logic described in the Graph Partitioning code example, the problem is resubmitted using a higher chain strength:
>>> sampleset = sampler.sample_qubo(Q, num_reads=num_reads, chain_strength=1000)
Check the best returned answer and percentage of samples based on chains with breakage rates of over 33 percent. Results will vary due to the probabilistic nature of the quantum computer and its integrated control errors (ICE), but in this case the shown submission had a lower minimum energy and no samples based on high rates of broken chains.
>>> print("Number of nodes in one set is {}, in the other, {}. \nEnergy is {}.".format(
... sum(sampleset.first.sample.values()),
... graph_nodes  sum(sampleset.first.sample.values()),
... sampleset.first.energy)) # doctest: +SKIP
Number of nodes in one set is 8, in the other, 8.
Energy is 3815.0.
...
>>> print("Percentage of samples with high rates of breaks is {}.".format(
... np.count_nonzero(sampleset.record.chain_break_fraction > 0.33)/num_reads*100)) # doctest: +SKIP
Percentage of samples with high rates of breaks is 0.0.
If you again use the problem inspector on the returned samples, you see the improved chains.
>>> dwave.inspector.show(sampleset) # doctest: +SKIP
Also of interest is the “spread” of solution energies. For this submission there are a few distinct clusters. The problem inspector can zoom in on the lowest:
You see that most the returned solutions of lowest energy cluster closely around an energy of approximately 3807 but that the QPU has found some even lowerenergy solutions. From this one can assume that it might be possible find a better solution by increasing the number of reads. Additionally however, the complete lack of broken chains for the current returned sample set suggests that the chain strength can likely be lowered while still maintaining a low rate of broken chains. Doing so enables the problem to be represented more accurately on the QPU.
>>> sampleset = sampler.sample_qubo(Q, num_reads=num_reads, chain_strength=300)
Below is one run of a few iterations of adjusting chain strength. Notice that the acceptable rate of chain breaks was set lower, to breakage rates of over 5 percent.
>>> print("Number of nodes in one set is {}, in the other, {}. \nEnergy is {}.".format(
... sum(sampleset.first.sample.values()),
... graph_nodes  sum(sampleset.first.sample.values()),
... sampleset.first.energy)) # doctest: +SKIP
Number of nodes in one set is 8, in the other, 8.
Energy is 3817.0.
...
>>> print("Percentage of samples with >5 percent chain breaks is {}.".format(
... np.count_nonzero(sampleset.record.chain_break_fraction > 0.05)/num_reads*100)) # doctest: +SKIP
Percentage of samples with >5 percent chain breaks is 1.7000000000000002.
The result of the shown submission, with a chain strength of \(300\), still had less than 2% of its samples based on broken chains.
Working With Different Topologies¶
The examples shows how to construct software samplers with the same structure as the QPU, and how to work with embeddings with different topologies.
The code examples below will use the following imports:
>>> import neal
>>> import dimod
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> import dwave.embedding
...
>>> from dwave.system import DWaveSampler, EmbeddingComposite
Creating a Chimera Sampler¶
As detailed in Classical Solvers, you might want to use a classical solver while developing your code or writing tests. However, it is sometimes useful to work with a software solver that behaves more like a quantum computer.
One of the key features of the quantum computer is its working graph, which defines the connectivity allowed by the binary quadratic model.
To create a software solver with the same connectivity as a DWave 2000Q quantum computer
we first need a representation of the Chimera graph which can be obtained
from the dwave_networkx project using the
chimera_graph()
function.
>>> C16 = dnx.chimera_graph(16)
Next, we need a software sampler. We will use the
neal.SimulatedAnnealingSampler
found in dwave_neal,
though the tabu.TabuSampler
from dwavetabu
would work equally well.
>>> classical_sampler = neal.SimulatedAnnealingSampler()
Now, with a classical sampler and the desired graph, we can use
dimod’s dimod.StructuredComposite
to create
a Chimerastructured sampler.
>>> sampler = dimod.StructureComposite(classical_sampler, C16.nodes, C16.edges)
This sampler accepts Chimerastructured problems. In this case we create an Ising problem.
>>> h = {v: 0.0 for v in C16.nodes}
>>> J = {(u, v): 1 for u, v in C16.edges}
>>> sampleset = sampler.sample_ising(h, J)
We can even use the sampler with the dwave.system.EmbeddingComposite
>>> embedding_sampler = EmbeddingComposite(sampler)
Finally, we can confirm that our sampler matches the dwave.system.DWaveSampler
’s
structure. We make sure that our QPU has the same topology we have
been simulating. Also note that the working graph of the QPU is usually
a subgraph of the full hardware graph.
>>> qpu_sampler = DWaveSampler(solver={'qpu': True, 'num_active_qubits__within': [2000, 2048]})
>>> QPUGraph = nx.Graph(qpu_sampler.edgelist)
>>> all(v in C16.nodes for v in QPUGraph.nodes)
True
>>> all(edge in C16.edges for edge in QPUGraph.edges) # doctest: +SKIP
True
Creating a Pegasus Sampler¶
Another topology of interest is the Pegasus topology.
As above, we can use the generator function dwave_networkx.pegasus_graph()
found in
dwave_networkx and the
neal.SimulatedAnnealingSampler
found in dwave_neal
to construct a sampler.
>>> P6 = dnx.pegasus_graph(6)
>>> classical_sampler = neal.SimulatedAnnealingSampler()
>>> sampler = dimod.StructureComposite(classical_sampler, P6.nodes, P6.edges)
Working With Embeddings¶
The example above using the EmbeddingComposite
hints that we might be interested in trying embedding with different
topologies.
One thing we might be interested in is the chain length when embedding our problem. Say that we have a fully connected problem with 40 variables and we want to know the chain length needed to embed it on a 2048 node Chimera graph.
We can use dwavesystem’s
find_clique_embedding()
function to find the
embedding and determine the maximum chain length.
>>> num_variables = 40
>>> embedding = dwave.embedding.chimera.find_clique_embedding(num_variables, 16)
>>> max(len(chain) for chain in embedding.values())
11
Similarly we can explore clique embeddings for a 40variables fully connected
problem with a 680 node Pegasus graph using
dwavesystem’s
find_clique_embedding()
function
>>> num_variables = 40
>>> embedding = dwave.embedding.pegasus.find_clique_embedding(num_variables, 6)
>>> max(len(chain) for chain in embedding.values())
6
 Using the Problem Inspector improves minorembedding on a graph partition problem.
 Working With Different Topologies runs your code on software samplers with different QPUinspired topologies.
Demonstrations and Jupyter Notebooks¶
DWave’s dwaveexamples GitHub repo contains demos, typically in the form of short code examples, you can open in the Leap IDE or copy (clone) locally and run.
DWave’s Leap Quantum Application Environment provides a number of Jupyter Notebooks with detailed code examples for various types of problems (for example, constraint satisfaction problems) and ways of using the quantum computer (for example, hybrid computing and reverse annealing). These can also serve as a framework in which to develop your own code.
Additional Tutorials¶
Getting Started with the DWave System
This guide in the System Documentation introduces the DWave quantum computer, provides some key background information on how the system works, and explains how to construct a simple problem that the system can solve.
DWave ProblemSolving Handbook
This guide for more advanced users has an opening chapter of illustrative examples that explain the main steps of solving problems on the DWave system through two “toy” problems.
Concepts¶
See the Glossary for short definitions of terminology or learn Ocean concepts here:
Concepts  Related terms 

Binary Quadratic Models  BQM, Ising, QUBO 
Constraint Satisfaction  CSP, binary CSP 
Hybrid  quantumclassical hybrid, Leap’s hybrid solvers, hybrid workflows 
MinorEmbedding  embedding, mapping logical variables to physical qubits, chains, chain strength 
QPU Topology  Chimera, Pegasus 
Samplers and Composites  solver 
Solutions  samples, sampleset, probabilistic, energy 
Binary Quadratic Models¶
The binary quadratic model (BQM) class encodes Ising and quadratic unconstrained binary optimization (QUBO) models used by samplers such as the DWave system.
The BQM equation,
can represent both.
The Ising model is an objective function of \(N\) variables \(s=[s_1,...,s_N]\) corresponding to physical Ising spins, where \(h_i\) are the biases and \(J_{i,j}\) the couplings (interactions) between spins.
The QUBO model is an objective function of \(N\) binary variables represented as an upperdiagonal matrix \(Q\), where diagonal terms are the linear coefficients and the nonzero offdiagonal terms the quadratic coefficients.
The BinaryQuadraticModel
class can contain both these models and its methods provide
convenient utilities for working with, and interworking between, the two representations
of a problem.
These models and their use in solving problems on the DWave system is described in the following documentation:
Getting Started with the DWave System
Introduces key concepts such as objective functions, Ising models, QUBOs, and graphs, explains how these models are used to represent problems, and provides some simple examples.
DWave ProblemSolving Handbook
Provides a variety of techniques for, and examples of, reformulating problems as BQMs.
Solving Problems on a DWave System
Describes and demonstrates the use of BQM in the context of Ocean software.
Constraint Satisfaction¶
A constraint satisfaction problem (CSP) requires that all the problem’s variables be assigned values, out of a finite domain, that result in the satisfying of all constraints.
The mapcoloring CSP, for example, is to assign a color to each region of a map such that any two regions sharing a border have different colors.
The constraints for the mapcoloring problem can be expressed as follows:
 Each region is assigned one color only, of \(C\) possible colors.
 The color assigned to one region cannot be assigned to adjacent regions.
A finite domain CSP consists of a set of variables, a specification of the domain of each variable, and a specification of the constraints over combinations of the allowed values of the variables. A constraint \(C_\alpha(\bf{x}_\alpha)\) defined over a subset of variables \(\bf{x}_\alpha\) defines the set of feasible and infeasible combinations of \(\bf{x}_\alpha\). The constraint \(C_\alpha\) may be be viewed as a predicate which evaluates to true on feasible configurations and to false on infeasible configurations. For example, if the domains of variables \(X_1,X_2,X_3\) are all \(\{0,1,2\}\), and the constraint is \(X_1+X_2<X_3\) then the feasible set is \(\{(0,0,1),(0,0,2),(0,1,2),(1,0,2)\}\), and all remaining combinations are infeasible.
Binary CSPs¶
Solving such problems as the mapcoloring CSP on a sampler such as the DWave system necessitates that the mathematical formulation use binary variables because the solution is implemented physically with qubits, and so must translate to spins \(s_i\in\{1,+1\}\) or equivalent binary values \(x_i\in \{0,1\}\). This means that in formulating the problem by stating it mathematically, you might use unary encoding to represent the \(C\) colors: each region is represented by \(C\) variables, one for each possible color, which is set to value \(1\) if selected, while the remaining \(C1\) variables are \(0\).
Another example is logical circuits. Logic gates such as AND, OR, NOT, XOR etc can be viewed as binary CSPs: the mathematically expressed relationships between binary inputs and outputs must meet certain validity conditions. For inputs \(x_1,x_2\) and output \(y\) of an AND gate, for example, the constraint to satisfy, \(y=x_1x_2\), can be expressed as a set of valid configurations: (0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1), where the variable order is \((x_1, x_2, y)\).
\(x_1,x_2\)  \(y\) 

\(0,0\)  \(0\) 
\(0,1\)  \(0\) 
\(1,0\)  \(0\) 
\(1,1\)  \(1\) 
You can use Ocean’s dwavebinarycsp to construct a BQM from a CSP. It maps each individual constraint in the CSP to a ‘small’ Ising model or QUBO, in a mapping called a penalty model.
For more information on using the DWave system to solve CSPs, see the following documentation:
Getting Started with the DWave System
Introduces the use of QUBOs to represent constraints in some simple examples.
DWave ProblemSolving Handbook
Provides a variety of techniques for, and examples of, reformulating CSPs as BQMs.
Hybrid¶
Quantumclassical hybrid is the use of both classical and quantum resources to solve problems, exploiting the complementary strengths that each provides. As quantum processors grow in size, offloading hard optimization problems to quantum computers promises performance benefits similar to CPUs’ outsourcing of computeintensive graphicsdisplay processing to GPUs.
For an overview of, and motivation for, hybrid computing, see this Medium Article.
DWave’s Leap quantum cloud service provides cloudbased hybrid solvers you can submit arbitrary BQMs to. These solvers, which implement stateoftheart classical algorithms together with intelligent allocation of the quantum processing unit (QPU) to parts of the problem where it benefits most, are designed to accommodate even very large problems. Leap’s solvers can relieve you of the burden of any current and future development and optimization of hybrid algorithms that best solve your problem.
dwavehybrid provides you with a Python framework for building a variety of flexible hybrid workflows. These use quantum and classical resources together to find good solutions to your problem. For example, a hybrid workflow might use classical resources to find a problem’s hard core and send that to the QPU, or break a large problem into smaller pieces that can be solved on a QPU and then recombined.
The dwavehybrid framework enables rapid development of experimental prototypes, which provide insight into expected performance of the productized versions. It provides reference samplers and workflows you can quickly plug into your application code. You can easily experiment with customizing workflows that best solve your problem. You can also develop your own hybrid components to optimize performance.
For more information on hybrid computing, see the following:

Describes how to use reference hybrid solvers, build hybrid workflows, and your own hybrid components.

Introduces Leap‘s quantumclassical hybrid solvers and provides references to usage information.
Getting Started Demonstrations and Jupyter Notebooks
Provides pointers to a codeexamples repository and Jupyter Notebooks, which have relevant content.
MinorEmbedding¶
To solve an arbitrarily posed binary quadratic problem directly on a DWave system requires mapping,
called minor embedding, to a Chimera graph that represents the system’s quantum processing unit.
This preprocessing can be done by a composed sampler consisting of the
DWaveSampler()
and a composite that performs minorembedding.
(This step is handled automatically by LeapHybridSampler()
and dwavehybrid reference samplers.)
For example, a simple twovariable bqm,
might be embedded to two connected qubits, such as 1929 and 1801 on a DWave 2000Q system:
In the DWave 2000Q Chimera topology, most qubits are conencted to six other qubits, so other valid minorembeddings might be \(s_1=1929, s_0=1933\) or \(s_0=1801, s_0=1807\) or \(s_0=0, s_1=4\).
Chains¶
Larger problems often require chains because the QPU topology is not fully connected.
For example, a fullyconected \(K_3\) threevariable bqm,
cannot be represented by three qubits in the Chimera topology—a \(K_3\) graph is not native to the Chimera graph. (Look at the Chimera “unit cell” shown in the QPU topology section and notice there is no way to connect three qubits in a closed loop to form a triangle graph.)
Instead, a variable is represented by a chain of physical qubits:
The embedding above derived from the hueristic used by EmbeddingComposite()
on the working graph of a DWave 2000Q selected by DWaveSampler()
:
sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
Other qubits might have been chosen; for example,
sampler = FixedEmbeddingComposite(DWaveSampler(solver={'qpu': True}),
embedding={'s0': [0, 4, 7], 's1': [2], 's2': [3, 6]})
intentionally sets the embedding shown below to represent this same \(K_3\) graph:
emphasized (and displaying a solution of \(+1\)).
Chain Strength¶
For a chain of qubits to represent a variable, all its constituent qubits must return the same value for a sample. This is accomplished by setting a strong coupling to the edges connecting these qubits. For the solutions shown above to the \(K_3\) problem, the default chain strength achieved identical values and the qubit chains properly represented the variables of the problem.
However, that is not always the case. For the qubits in a chain to be likely to return identical values, the coupling strength for their connecting edges must be strong compared to the coupling with other qubits that influence nonidentical outcomes.
For example, another threevariable \(K_3\) fullyconnected BQM,
can be embedded by representing one variable with two qubits, for example:
sampler = FixedEmbeddingComposite(DWaveSampler(solver={'qpu': True}),
embedding={'s0': [0, 4], 's1': [2], 's2': [7]})
This BQM has six ground states (best solutions, shown below—solved by bruteforce stepping through all possible configurations of values for the variables—with lowest energy of 1.0):
>>> bqm = dimod.BQM({}, {('s0', 's1'): 1, ('s0', 's2'): 1, ('s1', 's2'): 1},
... 0, dimod.Vartype.SPIN)
>>> print(dimod.ExactSolver().sample(bqm)) # doctest: +SKIP
s0 s1 s2 energy num_oc.
0 1 1 1 1.0 1
2 +1 +1 1 1.0 1
3 1 +1 1 1.0 1
5 +1 +1 +1 1.0 1
6 +1 1 +1 1.0 1
7 1 1 +1 1.0 1
1 +1 1 1 3.0 1
4 1 +1 +1 3.0 1
['SPIN', 8 rows, 8 samples, 3 variables]
In this case, the default chain strength is not always sufficient:
>>> sampleset = sampler.sample(bqm, num_reads=1000) # doctest: +SKIP
>>> print(sampleset) # doctest: +SKIP
s0 s1 s2 energy num_oc. chain_b.
0 1 +1 1 1.0 85 0.0
1 1 1 +1 1.0 147 0.0
2 +1 +1 1 1.0 81 0.333333
3 +1 1 +1 1.0 60 0.0
4 +1 +1 +1 1.0 162 0.0
5 1 1 1 1.0 128 0.0
6 +1 1 +1 1.0 89 0.333333
7 +1 +1 1 1.0 248 0.0
['SPIN', 8 rows, 1000 samples, 3 variables]
The solutions of line 2 and 6 above shown a chains broken in a third of the variables, meaning that for variable \(s_0\) the two qubits representing it did not return identical values.
For information on handling embedding and chains, see the following documentation:
Boolean AND Gate, MultipleGate Circuit, and Using the Problem Inspector examples
Shows through some simple examples how to embed and set chain strength.
minorminer tool
Is the hueristic used by common Ocean embedding composites.
problem inspector tool
Visualizes embeddings.

Provides embedding composites.
QPU Topology¶
To solve a bqm on the DWave system, you must map it to a graph that represents the topology of the system’s qubits. For DWave 2000Q systems, this is the chimera topology; for nextgeneration Advantage systems, this is the Pegasus topology.
Note
If you are sending your problem to a Leap quantumclassical hybrid solver, the solver handles all interactions with the QPU.
Chimera¶
The Chimera architecture comprises sets of connected unit cells, each with four horizontal qubits connected to four vertical qubits via couplers (bipartite connectivity). Unit cells are tiled vertically and horizontally with adjacent qubits connected, creating a lattice of sparsely connected qubits. A unit cell is typically rendered as either a cross or a column.
Chimera qubits are considered to have a nominal length of 4 (each qubit is connected to 4 orthogonal qubits through internal couplers) and degree of 6 (each qubit is coupled to 6 different qubits).
The notation CN refers to a Chimera graph consisting of an \(N{\rm x}N\) grid of unit cells. The DWave 2000Q QPU supports a C16 Chimera graph: its 2048 qubits are logically mapped into a \(16 {\rm x} 16\) matrix of unit cells of 8 qubits.
Pegasus¶
In Pegasus as in Chimera, qubits are “oriented” vertically or horizontally but similarly aligned qubits can also be also shifted by distances and in groupings that differ between Pegasus families. Pegasus qubits are also more densely connected and have three types of coupler:
 Internal couplers. Internal couplers connect pairs of orthogonal (with opposite orientation) qubits. In Pegasus, each qubit is connected via internal coupling to 12 other qubits (versus four in the Chimera topology).
 External couplers. External couplers connect vertical qubits to adjacent vertical qubits and horizontal qubits to adjacent horizontal qubits. Each qubit has one or two external couplers.
 Odd couplers. Odd couplers connect similarly aligned pairs of qubits. Each qubit has one odd coupler.
Pegasus qubits are considered to have a nominal length of 12 (each qubit is connected to 12 orthogonal qubits through internal couplers) and degree of 15 (each qubit is coupled to 15 different qubits).
As we use the notation CN to refer to a Chimera graph with size parameter N, we refer to instances of Pegasus topologies by PN; for example, P3 is a graph with 144 nodes.
Samplers and Composites¶
Samplers¶
Samplers are processes that sample from low energy states of a problem’s objective function. A BQM sampler samples from low energy states in models such as those defined by an Ising equation or a Quadratic Unconstrained Binary Optimization (QUBO) problem and returns an iterable of samples, in order of increasing energy.
Ocean software provides a variety of dimod samplers, which
all support ‘sample_qubo’ and ‘sample_ising’ methods as well as the generic BQM sampler method.
In addition to DWaveSampler()
, classical solvers, which run on CPU or GPU, are available and
useful for developing code or on a small versions of a problem to verify code.
Hybrid QuantumClassical Samplers¶
Quantumclassical hybrid is the use of both classical and quantum resources to solve problems, exploiting the complementary strengths that each provides.
DWave’s Leap Quantum Application Environment provides stateoftheart hybrid solvers you can submit arbitrary BQMs to. dwavehybrid provides you with a Python framework for building a variety of flexible hybrid workflows that use quantum and classical resources together to find good solutions to your problem.
Solvers¶
Ocean software provides quantum, classical, and quantumclassical hybrid samplers that run either remotely (for example, in DWave’s Leap environment) or locally on your CPU. These compute resources are known as solvers.
Note
Some classical samplers actually bruteforce solve small problems rather than sample, and these are also referred to as “solvers”.
Composites¶
Samplers can be composed. The composite pattern allows layers of pre and postprocessing to be applied to binary quadratic programs without needing to change the underlying sampler implementation. We refer to these layers as composites. A composed sampler includes at least one sampler and possibly many composites.
Examples of composites are EmbeddingComposite()
,
which handle the mapping known as minorembedding,
and RoofDualityComposite()
, which
uses roof duality to assign
some variables as a preprocessing step before submitting the problem for sampling.
The use of samplers in solving problems is described in the following documentation:

Describes the available types of samplers in Ocean and their use in solving BQMs.
Solutions¶
samplers sample from lowenergy states of a problem’s objective function—BQM samplers sample from lowenergy states in models such as those defined by an Ising equation or a QUBO problem—and return an iterable of samples, in order of increasing energy.
When the D‑Wave quantum computer solves a problem, it uses quantum phenomena such as superposition and tunneling to explore all possible solutions simultaneously and find a set of the best ones. At the end of the computation (anneal), a single solution is sampled from a set of good solutions, with some probability, and returned. Because the sampled solution is probabilistic, different solutions may be returned in different runs. The standard way of submitting a problem to the system requests many samples, not just one. This not only returns multiple “best” answers but also reduces the probability of settling on a suboptimal answer.
Some classical samplers might return nonprobabilistic solutions; for example,
the dimod ExactSolver
deterministically
returns the best solution or solutions to small problems by calculating the result for
every configuration of variable values. Such samplers are called solvers.
Some Ocean functions might return a single best solution; for example, some dwavenetworkx graph algorithms return only the lowestenergy sample.
SampleSets¶
Ocean uses the dimod SampleSet
class to hold samples and some additional information (e.g., timing information from some
samplers).
For the simple example threevariable “triangular” BQM,
might be solved directly on a DWave 2000Q system by sampling 1000 times as follows, where the
EmbeddingComposite
composite maps the symbolic BQM to
qubits on the quantum processor, which is called by the
DWaveSampler
sampler:
>>> bqm = dimod.BQM({}, {('s0', 's1'): 1, ('s0', 's2'): 1, ('s1', 's2'): 1}, 0, dimod.Vartype.SPIN)
>>> sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
>>> sampleset = sampler.sample(bqm, num_reads=1000)
>>> print(sampleset) # doctest: +SKIP
s0 s1 s2 energy num_oc. chain_b.
0 1 1 +1 1.0 141 0.0
1 +1 +1 +1 1.0 132 0.0
2 1 1 1 1.0 159 0.0
3 1 +1 1 1.0 143 0.333333
4 +1 +1 1 1.0 91 0.0
5 1 +1 1 1.0 86 0.0
6 +1 +1 +1 1.0 129 0.333333
7 +1 1 +1 1.0 119 0.0
['SPIN', 8 rows, 1000 samples, 3 variables]
The returned SampleSet
, in this case, shows eight solutions of
equal energy \(1.0\). Solution \(s_0=1, s_1=1, s_2=+1\) occurred
in 141 of the 1000 samples. Two solutions, shown in line 3 and 6,
were based on a broken chain of qubits that represented one of the variables.
For this submission to a DWave 2000Q, the sampleset also contained the following additional information:
>>> print(sampleset.info.keys()) # doctest: +SKIP
dict_keys(['timing', 'problem_id', 'embedding_context', 'warnings'])
For example, the timing information for the problem might look something like:
>>> print(sampleset.info["timing"]) # doctest: +SKIP
{'qpu_sampling_time': 314960,
'qpu_anneal_time_per_sample': 20,
'qpu_readout_time_per_sample': 274,
'qpu_access_time': 324321,
'qpu_access_overhead_time': 5362,
'qpu_programming_time': 9361,
'qpu_delay_time_per_sample': 21,
'total_post_processing_time': 409,
'post_processing_overhead_time': 409,
'total_real_time': 324321,
'run_time_chip': 314960,
'anneal_time_per_run': 20,
'readout_time_per_run': 274}
Glossary¶
 binary quadratic model
 BQM
 A collection of binaryvalued variables (variables that can be assigned two values, for example 1, 1) with associated linear and quadratic biases. Sometimes referred to in other tools as a problem. See a fuller description under Binary Quadratic Models.
 Chain
 One or more nodes or qubits in a target graph that represent a single variable in the source graph. See embedding. See a fuller description under MinorEmbedding.
 Chain length
 The number of qubits in a Chain. See a fuller description under MinorEmbedding.
 Chain strength
 Magnitude of the negative quadratic bias applied between variables to form a chain. See a fuller description under MinorEmbedding.
 Chimera
 The DWave QPU is a lattice of interconnected qubits. While some qubits connect to others via couplers, the DWave QPU is not fully connected. Instead, the qubits interconnect in an architecture known as Chimera. See a fuller description under QPU Topology.
 Complete graph
 Fully connected
 See complete graph. on wikipedia. A fully connected or complete binary quadratic model is one that has interactions between all of its variables.
 Composed sampler
 Samplers that apply pre and/or postprocessing to binary quadratic programs without changing the underlying sampler implementation by layering composite patterns on the sampler. For example, a composed sampler might add spin transformations when sampling from the DWave system.
 Composite
 A sampler can be composed. The composite pattern allows layers of pre and postprocessing to be applied to binary quadratic programs without needing to change the underlying sampler implementation. We refer to these layers as “composites”. A composed sampler includes at least one sampler and possibly many composites.
 Embed
 Embedding
 Minorembed
 Minorembedding
 The nodes and edges on the graph that represents an objective function translate to the qubits and couplers in Chimera. Each logical qubit, in the graph of the objective function, may be represented by one or more physical qubits. The process of mapping the logical qubits to physical qubits is known as minor embedding. See a fuller description under MinorEmbedding.
 Excited state
 States of a quantum system that have higher energy than the ground state. Such states represent nonoptimal solutions for problems represented by an Objective function and infeasible configurations for problems represented by a penalty model.
 Graph
 A collection of nodes and edges. A graph can be derived from a model: a node for each variable and an edge for each pair of variables with a nonzero quadratic bias.
 Ground state
 The lowestenergy state of a quantummechanical system and the global minimum of a problem represented by an Objective function.
 Hamiltonian
A classical Hamiltonian is a mathematical description of some physical system in terms of its energies. We can input any particular state of the system, and the Hamiltonian returns the energy for that state. For a quantum system, a Hamiltonian is a function that maps certain states, called eigenstates, to energies. Only when the system is in an eigenstate of the Hamiltonian is its energy well defined and called the eigenenergy. When the system is in any other state, its energy is uncertain. For the DWave system, the Hamiltonian may be represented as
\begin{equation} {\cal H}_{ising} = \underbrace{\frac{A({s})}{2} \left(\sum_i {\hat\sigma_{x}^{(i)}}\right)}_\text{Initial Hamiltonian} + \underbrace{\frac{B({s})}{2} \left(\sum_{i} h_i {\hat\sigma_{z}^{(i)}} + \sum_{i>j} J_{i,j} {\hat\sigma_{z}^{(i)}} {\hat\sigma_{z}^{(j)}}\right)}_\text{Final Hamiltonian} \end{equation}where \({\hat\sigma_{x,z}^{(i)}}\) are Pauli matrices operating on a qubit \(q_i\), and \(h_i\) and \(J_{i,j}\) are the qubit biases and coupling strengths.
 Hardware graph
 See hardware graph. The hardware graph is the physical lattice of interconnected qubits. See also working graph. See a fuller description under QPU Topology.
 Ising
Traditionally used in statistical mechanics. Variables are “spin up” (\(\uparrow\)) and “spin down” (\(\downarrow\)), states that correspond to \(+1\) and \(1\) values. Relationships between the spins, represented by couplings, are correlations or anticorrelations. The objective function expressed as an Ising model is as follows:
\begin{equation} \text{E}_{ising}(\pmb{s}) = \sum_{i=1}^N h_i s_i + \sum_{i=1}^N \sum_{j=i+1}^N J_{i,j} s_i s_j \end{equation}where the linear coefficients corresponding to qubit biases are \(h_i\), and the quadratic coefficients corresponding to coupling strengths are \(J_{i,j}\). See also Ising Model on Wikipedia.
 Minimum gap
 The minimum distance between the ground state and the first excited state throughout any point in the anneal.
 Model
 A collection of variables with associated linear and quadratic biases. Sometimes referred to as a problem.
 Objective function
 A mathematical expression of the energy of a system as a function of binary variables representing the qubits.
 Pegasus
 The DWave QPU is a lattice of interconnected qubits. While some qubits connect to others via couplers, the DWave QPU is not fully connected. Instead, the qubits interconnect in an architecture known as Pegasus. See a fuller description under QPU Topology.
 Penalty function
 An algorithm for solving constrained optimization problems. In the context of Ocean tools, penalty functions are typically employed to increase the energy level of a problem’s objective function by penalizing nonvalid configurations. See Penalty method on Wikipedia
 Penalty model
 An approach to solving constraint satisfaction problems (CSP) using an Ising model or a QUBO by mapping each individual constraint in the CSP to a ‘small’ Ising model or QUBO.
 QPU
 Quantum processing unit
 QUBO
Quadratic unconstrained binary optimization. QUBO problems are traditionally used in computer science. Variables are TRUE and FALSE, states that correspond to 1 and 0 values. A QUBO problem is defined using an upperdiagonal matrix \(Q\), which is an \(N\) x \(N\) uppertriangular matrix of real weights, and \(x\), a vector of binary variables, as minimizing the function
\begin{equation} f(x) = \sum_{i} {Q_{i,i}}{x_i} + \sum_{i<j} {Q_{i,j}}{x_i}{x_j} \end{equation}where the diagonal terms \(Q_{i,i}\) are the linear coefficients and the nonzero offdiagonal terms are the quadratic coefficients \(Q_{i,j}\). This can be expressed more concisely as
\begin{equation} \min_{{x} \in {\{0,1\}^n}} {x}^{T} {Q}{x}. \end{equation}In scalar notation, the objective function expressed as a QUBO is as follows:
\begin{equation} \text{E}_{qubo}(a_i, b_{i,j}; q_i) = \sum_{i} a_i q_i + \sum_{i<j} b_{i,j} q_i q_j. \end{equation}See also QUBO on Wikipedia.
 Sampler
 Samplers are processes that sample from low energy states of a problem’s objective function, which is a mathematical expression of the energy of a system. A binary quadratic model (BQM) sampler samples from low energy states in models such as those defined by an Ising equation or a QUBO problem and returns an iterable of samples, in order of increasing energy.
 SAPI
 Solver API used by clients to communicate with a solver.
 Solver
 A resource that runs a problem. Some solvers interface to the QPU; others leverage CPU and GPU resources.
 Source
 Source graph
 In the context of embedding, the model or induced graph that we wish to embed. Sometimes referred to as the logical graph/model. See a fuller description under MinorEmbedding.
 Structured sampler
 Samplers that are restricted to sampling only binary quadratic models defined on a specific graph.
 Subgraph
 See subgraph on wikipedia.
 Target
 Target graph
 Embedding attempts to create a target model from a target graph. The process of embedding takes a source model, derives the source graph, maps the source graph to the target graph, then derives the target model. Sometimes referred to as the embedded graph/model. See a fuller description under MinorEmbedding.
 Working graph
 In a DWave QPU, the set of qubits and couplers that are available for computation is known as the working graph. The yield of a working graph is typically less than 100% of qubits and couplers that are fabricated and physically present in the QPU. See hardware graph.
How to Contribute¶
The goal of this document is to establish a common understanding among software contributors to DWave’s Ocean software projects based on the code conventions and best practices used at DWave.
This document is intended to be a living document, and is not complete. Feedback is welcome.
Testing¶
A feature or bugfix is complete only when the code has been unittested. Part of the pullrequest process is to test your branch against master, and so the more tests you provide, the easier the pullrequest process.
Submitting Changes¶
When contributing to a DWave project, fork the repository using the Github fork button and work in a feature branch in your own repository. In your feature branch, commit and push often, you can always rebase locally to edit your commit history and make it readable. To start a discussion, initiate a pull request. The sooner you start the pull request, the better. This allows early discussion on your feature and saves time and effort when you are ready to merge. When you are ready to merge, notify the repository owner and they will merge your code in.
Follow the commit conventions described here:
 https://chris.beams.io/posts/gitcommit/
 http://tbaggery.com/2008/04/19/anoteaboutgitcommitmessages.html
TL;DR:
 Separate subject from body with a blank line
 Limit the subject line to 50 characters
 Capitalize the subject line
 Do not end the subject line with a period
 Use the imperative mood in the subject line
 Wrap the body at 72 characters
 Use the body to explain what and why vs. how
If your branch is longlived, rebase off of master periodically.
If you’re already familiar with Git, but rebasing is still scary, try this think like a Git guide.
The master branch in a dwavesystems repository reflects the bleedingedge developments of the project. Significant old versions forked from master are kept in version branches. For example, we might keep version branches 2.x and 3.x while master tracks the latest 4.x version. We try to minimize the number of version branches kept alive/maintained.
Stable releases are tracked using tags. These tagged snapshots are deployed to PyPI after successfully passing the test cases during continuous integration.
Coding Conventions¶
 Variable naming should follow the wellknown conventions of a language. Avoid uninformative or needlessly terse variable names.
 Code is read more often than written.
 Functions should do one thing.
 Early pull requests and code reviews.
 Early architecting/design. Code reviews can happen before any code has been written.
 Use a consistent character width of 120.
 Use 4 spaces instead of tabs.
 End all files with a newline.
Documentation and Comments¶
Do a good job of commenting. Read this Coding Horror article.
Comments should add, not repeat: avoid repeating in English or pseudocode what the code does. Rather, discuss what the block is trying to achieve.
Side effects should be visible on screen; if not in code, then in comments.
Remember, the best documentation is clean, simple code with good variable names. When this is not possible, you must use a comment to explain the purpose of a functional block.
Example:
The following code
# z must not be greater than 255. if z > 255: raise RuntimeError('z must be <= 255!')
would be much more informative as
# if z is greater than 255, this universe will collapse. See https://url.to.issue.tracker/IS42 if z > 255: raise RuntimeError('z must be <= 255!')
or even better:
# See https://url.to.issue.tracker/IS42 if z > 255: raise RuntimeError('z cannot be greater than 255, or this universe will collapse.')
Python¶
Python 2/3¶
All code should be both Python 2 and 3 compatible.
Documentation¶
 Google docstrings convention (definition, example) on all publicfacing functions. The
following are exceptions:
 For DWave extensions of thirdparty projects, we match the existing convention (e.g. the DWave NetworkX project follows NumPy conventions).
 Argument defaults are written “default=x” rather than “default x”.
 Private functions should include some sort of docstring.
 If your module has more than one public unit, it should have a module docstring with a table of contents.
 The docstring for the
__init__
method goes on the class.  All docstrings should be parsable by the Sphinx documentation generation tool (i.e. reStructuredText) The sphinx theme should be readthedocs.
C++¶
.clangformat¶
When starting a new C++ project, copy the .clangformat file included here.
Our style is based on Google (as opposed to LLVM, Chromium, Mozilla, or Webkit) with minor differences.
ColumnLimit
is set to120
, as specified in Coding Conventions.NamespaceIndentation
is set toInner
as a middle ground betweenNone
(Google) andAll
, such that every line in a file defining a namespace isn’t indented, but nested namespaces are easily spotted.Various indentwidth specifiers are scaled by a factor of 2 such that the base indent is
4
, as specified in Coding Conventions, instead of2
(Google). This is especially helpful for readibility in cases likeif (condition) { foo(); } else { bar(); }
as opposed to
if (condition) { foo(); } else { bar(); }
Additional Style¶
Favor the use of the optional braces for singleline control statements, which enhance consistency and extensibility.
Example:
Use the following format
if (a) {
return;
}
as opposed to
if (a) return;
This could potentially be enforced by clangtidy
.
Versioning Scheme¶
Our code follows Semantic Versioning conventions: major.minor.patch.
A change that breaks backwards compatibility must increment the major version. Anything below version 1.0.0 can break backwards compatibility.
Readme File¶
If you are creating a repository, don’t forget to include a README.rst
containing
a reasonable description of your project.
Licenses¶
Below are the opensource licenses for the SDK and its tools:
dwaveoceansdk¶
Apache LicenseVersion 2.0, January 2004
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.
dwavebinarycsp¶
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.
dwavecloudclient¶
Apache LicenseVersion 2.0, January 2004
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.
dwavehybrid¶
Apache LicenseVersion 2.0, January 2004
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.
dwaveneal¶
Apache LicenseVersion 2.0, January 2004
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.
dwavenetworkx¶
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.
dwavesystem¶
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.
dwavetabu¶
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.
2. 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.
3. 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.
4. 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:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) 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
(d) 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.
5. 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.
6. 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.
7. 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.
8. 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.
9. 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
http://www.apache.org/licenses/LICENSE2.0
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.
minorminer¶
Apache LicenseVersion 2.0, January 2004
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.
penaltymodel¶
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.
Ocean software also includes nonopensource packages you can optionally install with the following DWave enduser license agreements (EULAs):
dwavedrivers¶
COPYRIGHT 2017 DWAVE SYSTEMS INC. All Rights Reserved.
DWAVE SYSTEMS INC. (“DWAVE”) ENDUSER LICENSE AGREEMENT (“EULA”)
The software subject to this EULA is/are known as “dwave_system_tuning”.
IMPORTANT  READ CAREFULLY BEFORE COPYING, INSTALLING OR OTHERWISE USING: THIS EULA IS A LEGAL BINDING CONTRACT BETWEEN YOU AND DWAVE. DO NOT COPY, INSTALL, OR USE THIS SOFTWARE UNTIL YOU HAVE CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS. BY USING, COPYING OR DISTRIBUTING ALL OR ANY PORTION OF THE SOFTWARE YOU ACCEPT ALL THE TERMS AND CONDITIONS OF THIS EULA AND YOU AGREE THAT THIS EULA IS ENFORCEABLE LIKE ANY WRITTEN NEGOTIATED AGREEMENT SIGNED BY YOU. THIS EULA IS ENFORCEABLE AGAINST YOU AND ANY LEGAL ENTITY THAT OBTAINED THE SOFTWARE AND ON WHOSE BEHALF IT IS USED, FOR EXAMPLE, YOUR EMPLOYER. IF YOU DO NOT AGREE, DO NOT INSTALL OR USE THIS SOFTWARE.
IF YOU OR THE LEGAL ENTITY ON WHOSE BEHALF THE SOFTWARE WAS OBTAINED HAVE A SEPARATE CONTRACT WITH DWAVE (“ALTERNATE CONTRACT”), ADDITIONAL OR DIFFERENT TERMS MAY APPLY TO YOUR USE OF THIS SOFTWARE. IN THE EVENT OF A CONFLICT BETWEEN THE TERMS OF THIS EULA AND THE ALTERNATE CONTRACT, THE TERMS OF THE ALTERNATE CONTRACT APPLY.
US GOVERNMENT USERS: The Software and related documentation qualify as “commercial items,” as that term is defined at Federal Acquisition Regulation (“FAR”) (48 CFR 2.101, consisting of “commercial computer software” and “commercial computer software documentation” as such terms are used in FAR 12.212. Consistent with FAR 12.212 and DoD FAR Supp. 227.72021 through 227.72024, and notwithstanding any other FAR or other contractual clause to the contrary in any agreement into which this EULA may be incorporated, Government end users acquire the Software and related documentation with only those rights set forth in the EULA. Use of either the Software or the related documentation or both constitutes agreement by the Government that the Software and Documentation are “commercial computer software” and “commercial computer software documentation,” and constitutes acceptance of the rights and restrictions herein.
DWAVE AND ITS SUPPLIERS OWN ALL INTELLECTUAL PROPERTY IN THIS SOFTWARE. DWAVE PERMITS YOU TO COPY, INSTALL, USE AND DISTRIBUTE THE SOFTWARE ONLY IN ACCORDANCE WITH THE TERMS OF THIS EULA. USE OF SOME THIRD PARTY MATERIALS ASSOCIATED WITH THE SOFTWARE MAY BE SUBJECT TO OTHER TERMS AND CONDITIONS TYPICALLY FOUND IN A SEPARATE LICENSE AGREEMENT OR A “READ ME” OR “LICENCE.TXT” FILE PROVIDED IN ASSOCIATION WITH SUCH MATERIALS.
BY INSTALLING OR OTHERWISE USING THE SOFTWARE, YOU (THE “LICENSEE”) AGREE TO BE BOUND BY THE TERMS OF THIS EULA.
This EULA applies to the evaluation of the attached software product by Licensee during the evaluation period, which is without charge.
In this EULA, “Software” means (a) the object and/or source code version of the computer programs identified above as being subject to this EULA; (b) the object and/or source code version of any computer program related to the software of clause (a); (c) all of the contents of the files (provided either by electronic download, on physical media or any other method of distribution), disk(s), CDROM(s) or other media with which this EULA is provided; (d) related explanatory written materials, user manuals, electronic files and other documentation accompanying or published for such program or files (“Documentation”); (e) upgrades, updates, additions to, and copies of the foregoing, if any, provided to you by DWAVE or an authorized licensee, for example, downloaded software updates (collectively, “Updates”); and (f) any copies of the foregoing.
“DWAVE” means DWave Systems Inc., a Canadian corporation, 3033 Beta Avenue, Burnaby, British Columbia, Canada.
 SOFTWARE LICENSE.
a. In order to use the Software, Licensee must first agree to this EULA. Licensee may not use the Software if Licensee does not accept this EULA.
b. If Licensee is agreeing to be bound by this EULA on behalf of Licensee’s employer or other entity, Licensee represents and warrants that Licensee has full legal authority to bind Licensee’s employer or such entity to this EULA. If Licensee does not have the requisite authority, Licensee may not accept the EULA or use the Software on behalf of Licensee’s employer or other entity.
c. Licensee can accept this EULA by: i. clicking to accept or agree to the EULA before downloading the Software where this option is made available to Licensee; or ii. using the Software. d. Upon Licensee’s agreement to be bound by the terms of this EULA and subject to the terms of this EULA and Licensee’s compliance with same, DWAVE grants to Licensee a limited, nonexclusive, nontransferable, nonsublicensable copyright license to use the Software solely to develop applications to run on or with DWAVE’s product(s) for (i) noncommercial use, or (ii) Licensee’s internal product development purposes.
e. No Support. DWAVE is not obligated to provide any technical or other support for the Software to Licensee.
f. Fees. DWAVE may choose in the future to charge for use of the Software. If DWAVE in its sole discretion chooses to establish fees and payment terms for such use, DWAVE will provide notice of such terms as provided in Section 12 below, and Licensee may elect to stop using the Software rather than incurring fees.
 USE RESTRICTIONS. At all times during the term of this EULA:
a. Permitted Users. Licensee may: (i) if an individual, himself or herself use the Software as permitted by this EULA; or (ii) if a corporation or other entity, allow only its then current employees to use the Software as permitted by this EULA; but may not allow any other persons to use the Software.
b. Permitted Computers. Licensee may install the Software and make the Software available for use only on computers owned or leased by Licensee which are located at the premises of Licensee. Licensee may make one backup copy of the Software, provided that the backup copy is not installed or used on any computer. Any copy of the Software made by Licensee must contain the same copyright and other proprietary notices that appear on or in the Software and may not be provided to any other person.
c. Other Restrictions. Except to the extent required by applicable third party licenses, Licensee may not:
i. use the Software except in accordance with this EULA; ii. copy, modify, adapt, translate or create any derivative works of or based upon the Software; iii. decompile, disassemble, reverse engineer, or otherwise attempt to discover or derive the source code for the Software; iv. load any part of the Software onto a mobile handset or any other hardware device except a personal computer, combine any part of the Software with other software, or distribute any software or device incorporating a part of the Software; v. distribute, sell, rent, lease, sublicense, assign or otherwise transfer this EULA or its rights to the Software; or vi. remove or alter any trademark, logo, copyright or other proprietary notices, legends, symbols or labels on the Software.
d. Use, reproduction and distribution of components of the Software licensed under a third party license are governed solely by the terms of that third party license and not this EULA.
e. Compliance with Laws. Licensee will comply with all export laws and regulations of Canada, the United States, or any other government having jurisdiction and agrees that it will not export or reexport the Software in violation of any such laws or regulations. Licensee will also comply with all applicable laws and regulations with respect to the import into any country or the use in any country of the Software. Licensee agrees to use the Software and write applications only for purposes that are permitted by this EULA and any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from Canada, the United States or other relevant countries). In addition, if the Software is identified as export controlled items under any applicable law, Licensee represents and warrants that it is not a citizen of, or otherwise located within, a nation sanctioned or embargoed by Canada, the United Nations, or the United States (including without limitation Belarus, Cote d’Ivoire, Cuba, Democratic Republic of the Congo, Egypt, Eritrea, Iran, Iraq, Lebanon, Liberia, Libya, Myanmar (Burma), North Korea, Sierra Leone, Somalia, Sudan, Syria, Tunisia, and Zimbabwe) and that it is not otherwise prohibited by law from receiving the Software. Licensee agrees not to use the Software for any military or defenserelated purpose.
f. Licensee acknowledges and agrees that the form and nature of the Software that DWAVE provides may change without prior notice to Licensee and that future versions of the Software may be incompatible with applications developed on previous versions of the Software. Licensee acknowledges and agrees that DWAVE may stop (permanently or temporarily) providing the Software (or any features within the Software) to Licensee or to users generally at DWAVE’s sole discretion, without prior notice to Licensee.
3. CONSENT TO USE OF DATA AND USER SUBMISSIONS. Licensee agrees that DWAVE and its subsidiaries and agents may collect, maintain, process and use diagnostic, technical, usage and related information, including but not limited to information about Licensee’s computer, system and application software, and peripherals, that is gathered periodically to facilitate the provision of Updates, product support and other services to Licensee (if any) related to the Software, and to verify compliance with the terms of this EULA. DWAVE may use this information in compliance with applicable privacy laws to provide and improve DWAVE’s products and services or distribute the information to DWAVE’s partners and third party developers to improve their software, hardware and services designed for use with DWAVE products. Licensee agrees that any material, information or other communication, including all data, images, sounds, text, computer code in source or object form, and other things embodied therein, Licensee transmits or posts to any DWAVE website or provides to DWAVE under this EULA or through Licensee’s use of the Software will be deemed nonconfidential (“Communications”). DWAVE shall have no confidentiality obligations with respect to the Communications. Licensee agrees that DWAVE will be free to copy, modify, create derivative works, publicly display, disclose, distribute, license and sublicense through multiple tiers of distribution and licensees, incorporate and otherwise use the Communications, including derivative works thereto, for any and all commercial or noncommercial purposes.
4. OWNERSHIP. Except for the limited license rights expressly granted to Licensee hereunder, DWAVE and its suppliers retain all right, title and interest in the Software (including any copies that Licensee makes in accordance with this EULA), including any rights under the patent, trademark, copyright, trade secrets and other intellectual property laws, and this EULA does not grant to Licensee any intellectual property rights in the Software. DWAVE reserves all rights not expressly granted to Licensee in this EULA. The structure, organization and code underlying the Software are the valuable rights of DWAVE and its suppliers. Licensee agrees that Licensee will not take any action to jeopardize, limit or interfere in any manner with such ownership by DWAVE and its suppliers.
5. THIRD PARTY SOFTWARE APPLICATIONS AND DATA SERVICES. Portions of the Software may utilize or include third party software and other copyrighted material (“Third Party Software”). Acknowledgements, licensing terms and disclaimers for such Third Party Software are contained in the Documentation, and Licensee’s use of such Third Party Software is governed by such acknowledgements, licensing terms and disclaimers. The Software may interoperate with and allow Licensee to use software applications, information and data not developed or offered by DWAVE (“Third Party Information”). Licensee’s use of any Third Party Software or Third Party Information is governed by the terms and conditions made available to Licensee by the party from whom Licensee obtained such information. Neither Third Party Software nor Third Party Information is the responsibility of DWAVE, and LICENSEE’S USE OF THIRD PARTY SOFTWARE OR THIRD PARTY INFORMATION IS AT LICENSEE’S OWN RISK. DWAVE MAKES NO WARRANTIES, CONDITIONS, INDEMNITIES, REPRESENTATIONS OR TERMS, EXPRESS OR IMPLIED, WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE AS TO ANY MATTERS, INCLUDING BUT NOT LIMITED TO NONINFRINGEMENT OF THIRD PARTY RIGHTS, TITLE, INTEGRATION, ACCURACY, SECURITY, AVAILABILITY, SATISFACTORY QUALITY, MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE WITH RESPECT TO THIRD PARTY SOFTWARE OR THIRD PARTY INFORMATION.
6. NO WARRANTY. THE SOFTWARE IS MADE AVAILABLE TO THE LICENSEE ON AN “ASIS” BASIS AND WITH ALL FAULTS. DWAVE MAKES NO WARRANTY OR REPRESENTATION AS TO THE USE OR PERFORMANCE OF THE SOFTWARE OF ANY KIND. EXCEPT TO THE EXTENT TO WHICH THE SAME MAY NOT BE EXCLUDED AND/OR LIMITED UNDER APPLICABLE LAW, DWAVE DOES NOT WARRANT THAT THE SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NONINFRINGING OF THIRD PARTY RIGHTS, AND DISCLAIMS AND EXCLUDES ALL WARRANTIES, EXPRESS OR IMPLIED (WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE), WITH RESPECT TO THE SOFTWARE, ITS USE, PERFORMANCE OR APPLICATION, OR ANY INFORMATION PROVIDED REGARDING THE SOFTWARE. DWAVE PROVIDES NO TECHNICAL SUPPORT OR REMEDIES FOR THE SOFTWARE.
7. LIMITATION OF LIABILITY. DWAVE WILL NOT BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE POSSESSION OF, USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, DATA LOSS, OR COMPUTER FAILURE OR MALFUNCTION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, AND REGARDLESS OF WHETHER THE CLAIM OR LIABILITY IS BASED UPON ANY CONTRACT, TORT, BREACH OF WARRANTY OR OTHER LEGAL OR EQUITABLE THEORY AND NOTWITHSTANDING THAT ANY REMEDY HEREIN FAILS OF ITS ESSENTIAL PURPOSE. THE MAXIMUM LIABILITY OF DWAVE TO LICENSEE SHALL IN ANY EVENT NOT EXCEED THE LESSER OF (A) THE SUM OF THE LICENSE FEE PAID BY LICENSEE FOR THE SOFTWARE; OR (B) CAD$250. THE FOREGOING LIMITATIONS WILL APPLY EVEN IF THE ABOVE STATED REMEDY FAILS OF ITS ESSENTIAL PURPOSE. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF IMPLIED WARRANTIES OR LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, AND PARAGRAPHS 3 AND 4 WILL NOT APPLY ONLY TO THE EXTENT THAT APPLICABLE LAW REQUIRES LIABILITY NOTWITHSTANDING THE LIMITATIONS OR EXCLUSIONS THEREIN.
8. LICENSEE ACKNOWLEDGES AND AGREES THAT THE SOFTWARE IS NOT DESIGNED, INTENDED, AUTHORIZED OR SUITABLE FOR USE IN ANY TYPE OF SYSTEM, APPLICATION, SITUATION OR ENVIRONMENT WHERE THE FAILURE OR TIME DELAYS OF, OR ERRORS OR INACCURACIES IN, THE CONTENT, DATA OR INFORMATION PROVIDED BY THE SOFTWARE COULD LEAD TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE, INCLUDING WITHOUT LIMITATION THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, LIFE SUPPORT, MEDICAL SYSTEMS OR WEAPONS SYSTEMS AND THAT LICENSEE WILL NOT USE THE SOFTWARE IN SUCH SYSTEM, APPLICATION, SITUATION OR ENVIRONMENT.
9. INDEMNIFICATION. To the maximum extent permitted by law, Licensee agrees to defend, indemnify and hold harmless DWAVE, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) Licensee’s use of the Software, (b) any application Licensee develops using the Software that infringes or violates any right of any person or defames any person, and (c) any noncompliance by Licensee with this EULA.
 TERMINATION.
a. This EULA is effective from the date on which the attached Software is installed or used by Licensee until terminated. This EULA will terminate automatically without notice from DWAVE if Licensee fails to comply with any provision of this EULA or if DWAVE is required to do so by law. If Licensee commences or participates in any legal proceeding against DWAVE, then DWAVE may, in its sole discretion, suspend or terminate this EULA during the pendency of such legal proceedings. Licensee may voluntarily terminate this EULA at any time by ceasing to use the Software.
b. Upon termination of this EULA at any time and for any reason, Licensee will immediately discontinue any and all use of the Software, purge the Software from all computer systems, storage media and other files, including any backup copy, and return to DWAVE the Software, including the Documentation, and all copies thereof, or at the request of DWAVE, destroy the Software, the Documentation, and all copies thereof, and deliver to DWAVE certification that Licensee has complied with these termination obligations.
c. If this EULA is terminated at any time and for any reason, Licensee will not be entitled to compensation of any kind, financial or otherwise.
d. Paragraphs 3 through 9, 13(a) and 13(f) of this EULA and such other provisions as may reasonably be expected to remain in force will survive the termination of this EULA and will remain in full force and effect following such termination.
11. NO WAIVERS. A waiver expressed or implied by a party of any default of the other party in the observance or performance of this EULA must be in writing, and such waiver does not constitute and is not to be construed as a waiver or condonation of any subsequent or other default, and a waiver of any provision of this EULA will not be effective unless in writing and signed by an authorized officer of DWAVE.
12. MODIFICATIONS AND NOTICES. No reseller, distributor or dealer of the Software is authorized to make any modifications, extensions, or additions to this EULA. DWAVE may, in its sole discretion, modify this EULA. If DWAVE elects to do so, DWAVE will notify Licensee of such change. If Licensee does not agree to the change, then this EULA automatically terminates and Licensee must stop using the Software and comply with Section 10(b) of this EULA. If Licensee does not stop using the Software, then Licensee’s use of the Software will continue under the changed EULA. DWAVE may give notices to Licensee, at DWAVE’s option, by posting on any portion of www.dwavesys.com or by electronic mail to any email address provided by Licensee to DWAVE.
 GOVERNING LAW AND GENERAL PROVISIONS.
a. Governing Law and Other General Provisions. This EULA will be governed by and construed in accordance with the substantive laws in force in the Province of British Columbia, Canada, excluding its conflict of law rules. The courts of the Province of British Columbia shall have exclusive jurisdiction over all disputes relating to this EULA. Licensee and DWAVE agree to submit to the exclusive jurisdiction of the courts of British Columbia. This EULA will not be governed by the conflict of law rules of any jurisdiction or the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded.
 Time. Time is of the essence of this EULA.
c. Severance. If any provision in this EULA should be held invalid or unenforceable, such provision shall be modified to the extent necessary to render it valid or enforceable or severed from this EULA if no such modification is possible, and the other provisions of this EULA shall remain in full force and effect.
d. Assignment. Licensee may not assign its rights or delegate its obligations under this EULA without the prior written consent of DWAVE, which consent may be withheld in the sole discretion of D WAVE. DWAVE may assign its rights or delegate its obligations under this EULA to any person in its sole discretion. This EULA shall be binding on and inure to the benefit of the parties and their successors and permitted assigns.
e. No Other EULAs. This EULA is the entire agreement of the parties with respect to the Software, and there are no other agreements, written, oral, electronic or otherwise, with respect to the Software, and it supersedes any prior representations, discussions, undertakings, communications or advertising relating to the Software.
f. Compliance with Licenses. If Licensee is a business or organization, Licensee agrees that upon request from DWAVE or DWAVE’s authorized representative, Licensee will within thirty (30) days fully document and certify that use of any and all Software at the time of the request is in conformity with Licensee’s valid licenses from DWAVE.
g. English Language. Licensee and DWAVE confirm that it is their wish that this EULA, as well as other documents relating hereto, including notices, have been and shall be written in English only. Licensee et DWAVE confirment leur desir que cet accord ainsi que tous les documents, y compris tous avis qui s’y rattachent, soient rediges en anglais.
Updated January 4, 2017
dwaveinspector¶
COPYRIGHT 2020 DWAVE SYSTEMS INC. All Rights Reserved.
DWAVE SYSTEMS INC. (“DWAVE”) ENDUSER LICENSE AGREEMENT (“EULA”)
The software distributed with this EULA is subject to the following terms.
IMPORTANT  READ CAREFULLY BEFORE COPYING, INSTALLING OR OTHERWISE USING: THIS EULA IS A LEGAL BINDING CONTRACT BETWEEN YOU AND DWAVE. DO NOT COPY, INSTALL, OR USE THIS SOFTWARE UNTIL YOU HAVE CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS. BY USING, COPYING OR DISTRIBUTING ALL OR ANY PORTION OF THE SOFTWARE YOU ACCEPT ALL THE TERMS AND CONDITIONS OF THIS EULA AND YOU AGREE THAT THIS EULA IS ENFORCEABLE LIKE ANY WRITTEN NEGOTIATED AGREEMENT SIGNED BY YOU. THIS EULA IS ENFORCEABLE AGAINST YOU AND ANY LEGAL ENTITY THAT OBTAINED THE SOFTWARE AND ON WHOSE BEHALF IT IS USED, FOR EXAMPLE, YOUR EMPLOYER. IF YOU DO NOT AGREE, DO NOT INSTALL OR USE THIS SOFTWARE.
IF YOU OR THE LEGAL ENTITY ON WHOSE BEHALF THE SOFTWARE WAS OBTAINED HAVE A SEPARATE CONTRACT WITH DWAVE (“ALTERNATE CONTRACT”), ADDITIONAL OR DIFFERENT TERMS MAY APPLY TO YOUR USE OF THIS SOFTWARE. IN THE EVENT OF A CONFLICT BETWEEN THE TERMS OF THIS EULA AND THE ALTERNATE CONTRACT, THE TERMS OF THE ALTERNATE CONTRACT APPLY.
US GOVERNMENT USERS: The Software and related documentation qualify as “commercial items,” as that term is defined at Federal Acquisition Regulation (“FAR”) (48 CFR 2.101, consisting of “commercial computer software” and “commercial computer software documentation” as such terms are used in FAR 12.212. Consistent with FAR 12.212 and DoD FAR Supp. 227.72021 through 227.72024, and notwithstanding any other FAR or other contractual clause to the contrary in any agreement into which this EULA may be incorporated, Government end users acquire the Software and related documentation with only those rights set forth in the EULA. Use of either the Software or the related documentation or both constitutes agreement by the Government that the Software and Documentation are “commercial computer software” and “commercial computer software documentation,” and constitutes acceptance of the rights and restrictions herein.
DWAVE AND ITS SUPPLIERS OWN ALL INTELLECTUAL PROPERTY IN THIS SOFTWARE. DWAVE PERMITS YOU TO COPY, INSTALL, USE AND DISTRIBUTE THE SOFTWARE ONLY IN ACCORDANCE WITH THE TERMS OF THIS EULA. USE OF SOME THIRD PARTY MATERIALS ASSOCIATED WITH THE SOFTWARE MAY BE SUBJECT TO OTHER TERMS AND CONDITIONS TYPICALLY FOUND IN A SEPARATE LICENSE AGREEMENT OR A “READ ME” OR “LICENCE.TXT” FILE PROVIDED IN ASSOCIATION WITH SUCH MATERIALS.
BY INSTALLING OR OTHERWISE USING THE SOFTWARE, YOU (THE “LICENSEE”) AGREE TO BE BOUND BY THE TERMS OF THIS EULA.
This EULA applies to the evaluation of the attached software product by Licensee during the evaluation period, which is without charge.
In this EULA, “Software” means (a) the object and/or source code version of the computer programs identified above as being subject to this EULA; (b) the object and/or source code version of any computer program related to the software of clause (a); (c) all of the contents of the files (provided either by electronic download, on physical media or any other method of distribution), disk(s), CDROM(s) or other media with which this EULA is provided; (d) related explanatory written materials, user manuals, electronic files and other documentation accompanying or published for such program or files (“Documentation”); (e) upgrades, updates, additions to, and copies of the foregoing, if any, provided to you by DWAVE or an authorized licensee, for example, downloaded software updates (collectively, “Updates”); and (f) any copies of the foregoing.
“DWAVE” means DWave Systems Inc., a Canadian corporation, 3033 Beta Avenue, Burnaby, British Columbia, Canada.
 SOFTWARE LICENSE.
a. In order to use the Software, Licensee must first agree to this EULA. Licensee may not use the Software if Licensee does not accept this EULA.
b. If Licensee is agreeing to be bound by this EULA on behalf of Licensee’s employer or other entity, Licensee represents and warrants that Licensee has full legal authority to bind Licensee’s employer or such entity to this EULA. If Licensee does not have the requisite authority, Licensee may not accept the EULA or use the Software on behalf of Licensee’s employer or other entity.
c. Licensee can accept this EULA by: i. clicking to accept or agree to the EULA before downloading the Software where this option is made available to Licensee; or ii. using the Software. d. Upon Licensee’s agreement to be bound by the terms of this EULA and subject to the terms of this EULA and Licensee’s compliance with same, DWAVE grants to Licensee a limited, nonexclusive, nontransferable, nonsublicensable copyright license to use the Software solely to develop applications to run on or with DWAVE’s product(s) for (i) noncommercial use, or (ii) Licensee’s internal product development purposes.
e. No Support. DWAVE is not obligated to provide any technical or other support for the Software to Licensee.
f. Fees. DWAVE may choose in the future to charge for use of the Software. If DWAVE in its sole discretion chooses to establish fees and payment terms for such use, DWAVE will provide notice of such terms as provided in Section 12 below, and Licensee may elect to stop using the Software rather than incurring fees.
 USE RESTRICTIONS. At all times during the term of this EULA:
a. Permitted Users. Licensee may: (i) if an individual, himself or herself use the Software as permitted by this EULA; or (ii) if a corporation or other entity, allow only its then current employees to use the Software as permitted by this EULA; but may not allow any other persons to use the Software.
b. Permitted Computers. Licensee may install the Software and make the Software available for use only on computers owned or leased by Licensee which are located at the premises of Licensee. Licensee may make one backup copy of the Software, provided that the backup copy is not installed or used on any computer. Any copy of the Software made by Licensee must contain the same copyright and other proprietary notices that appear on or in the Software and may not be provided to any other person.
c. Other Restrictions. Except to the extent required by applicable third party licenses, Licensee may not:
i. use the Software except in accordance with this EULA; ii. copy, modify, adapt, translate or create any derivative works of or based upon the Software; iii. decompile, disassemble, reverse engineer, or otherwise attempt to discover or derive the source code for the Software; iv. load any part of the Software onto a mobile handset or any other hardware device except a personal computer, combine any part of the Software with other software, or distribute any software or device incorporating a part of the Software; v. distribute, sell, rent, lease, sublicense, assign or otherwise transfer this EULA or its rights to the Software; or vi. remove or alter any trademark, logo, copyright or other proprietary notices, legends, symbols or labels on the Software.
d. Use, reproduction and distribution of components of the Software licensed under a third party license are governed solely by the terms of that third party license and not this EULA.
e. Compliance with Laws. Licensee will comply with all export laws and regulations of Canada, the United States, or any other government having jurisdiction and agrees that it will not export or reexport the Software in violation of any such laws or regulations. Licensee will also comply with all applicable laws and regulations with respect to the import into any country or the use in any country of the Software. Licensee agrees to use the Software and write applications only for purposes that are permitted by this EULA and any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from Canada, the United States or other relevant countries). In addition, if the Software is identified as export controlled items under any applicable law, Licensee represents and warrants that it is not a citizen of, or otherwise located within, a nation sanctioned or embargoed by Canada, the United Nations, or the United States (including without limitation Belarus, Cote d’Ivoire, Cuba, Democratic Republic of the Congo, Egypt, Eritrea, Iran, Iraq, Lebanon, Liberia, Libya, Myanmar (Burma), North Korea, Sierra Leone, Somalia, Sudan, Syria, Tunisia, and Zimbabwe) and that it is not otherwise prohibited by law from receiving the Software. Licensee agrees not to use the Software for any military or defenserelated purpose.
f. Licensee acknowledges and agrees that the form and nature of the Software that DWAVE provides may change without prior notice to Licensee and that future versions of the Software may be incompatible with applications developed on previous versions of the Software. Licensee acknowledges and agrees that DWAVE may stop (permanently or temporarily) providing the Software (or any features within the Software) to Licensee or to users generally at DWAVE’s sole discretion, without prior notice to Licensee.
3. CONSENT TO USE OF DATA AND USER SUBMISSIONS. Licensee agrees that DWAVE and its subsidiaries and agents may collect, maintain, process and use diagnostic, technical, usage and related information, including but not limited to information about Licensee’s computer, system and application software, and peripherals, that is gathered periodically to facilitate the provision of Updates, product support and other services to Licensee (if any) related to the Software, and to verify compliance with the terms of this EULA. DWAVE may use this information in compliance with applicable privacy laws to provide and improve DWAVE’s products and services or distribute the information to DWAVE’s partners and third party developers to improve their software, hardware and services designed for use with DWAVE products. Licensee agrees that any material, information or other communication, including all data, images, sounds, text, computer code in source or object form, and other things embodied therein, Licensee transmits or posts to any DWAVE website or provides to DWAVE under this EULA or through Licensee’s use of the Software will be deemed nonconfidential (“Communications”). DWAVE shall have no confidentiality obligations with respect to the Communications. Licensee agrees that DWAVE will be free to copy, modify, create derivative works, publicly display, disclose, distribute, license and sublicense through multiple tiers of distribution and licensees, incorporate and otherwise use the Communications, including derivative works thereto, for any and all commercial or noncommercial purposes.
4. OWNERSHIP. Except for the limited license rights expressly granted to Licensee hereunder, DWAVE and its suppliers retain all right, title and interest in the Software (including any copies that Licensee makes in accordance with this EULA), including any rights under the patent, trademark, copyright, trade secrets and other intellectual property laws, and this EULA does not grant to Licensee any intellectual property rights in the Software. DWAVE reserves all rights not expressly granted to Licensee in this EULA. The structure, organization and code underlying the Software are the valuable rights of DWAVE and its suppliers. Licensee agrees that Licensee will not take any action to jeopardize, limit or interfere in any manner with such ownership by DWAVE and its suppliers.
5. THIRD PARTY SOFTWARE APPLICATIONS AND DATA SERVICES. Portions of the Software may utilize or include third party software and other copyrighted material (“Third Party Software”). Acknowledgements, licensing terms and disclaimers for such Third Party Software are contained in the Documentation, and Licensee’s use of such Third Party Software is governed by such acknowledgements, licensing terms and disclaimers. The Software may interoperate with and allow Licensee to use software applications, information and data not developed or offered by DWAVE (“Third Party Information”). Licensee’s use of any Third Party Software or Third Party Information is governed by the terms and conditions made available to Licensee by the party from whom Licensee obtained such information. Neither Third Party Software nor Third Party Information is the responsibility of DWAVE, and LICENSEE’S USE OF THIRD PARTY SOFTWARE OR THIRD PARTY INFORMATION IS AT LICENSEE’S OWN RISK. DWAVE MAKES NO WARRANTIES, CONDITIONS, INDEMNITIES, REPRESENTATIONS OR TERMS, EXPRESS OR IMPLIED, WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE AS TO ANY MATTERS, INCLUDING BUT NOT LIMITED TO NONINFRINGEMENT OF THIRD PARTY RIGHTS, TITLE, INTEGRATION, ACCURACY, SECURITY, AVAILABILITY, SATISFACTORY QUALITY, MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE WITH RESPECT TO THIRD PARTY SOFTWARE OR THIRD PARTY INFORMATION.
6. NO WARRANTY. THE SOFTWARE IS MADE AVAILABLE TO THE LICENSEE ON AN “ASIS” BASIS AND WITH ALL FAULTS. DWAVE MAKES NO WARRANTY OR REPRESENTATION AS TO THE USE OR PERFORMANCE OF THE SOFTWARE OF ANY KIND. EXCEPT TO THE EXTENT TO WHICH THE SAME MAY NOT BE EXCLUDED AND/OR LIMITED UNDER APPLICABLE LAW, DWAVE DOES NOT WARRANT THAT THE SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NONINFRINGING OF THIRD PARTY RIGHTS, AND DISCLAIMS AND EXCLUDES ALL WARRANTIES, EXPRESS OR IMPLIED (WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE), WITH RESPECT TO THE SOFTWARE, ITS USE, PERFORMANCE OR APPLICATION, OR ANY INFORMATION PROVIDED REGARDING THE SOFTWARE. DWAVE PROVIDES NO TECHNICAL SUPPORT OR REMEDIES FOR THE SOFTWARE.
7. LIMITATION OF LIABILITY. DWAVE WILL NOT BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE POSSESSION OF, USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, DATA LOSS, OR COMPUTER FAILURE OR MALFUNCTION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, AND REGARDLESS OF WHETHER THE CLAIM OR LIABILITY IS BASED UPON ANY CONTRACT, TORT, BREACH OF WARRANTY OR OTHER LEGAL OR EQUITABLE THEORY AND NOTWITHSTANDING THAT ANY REMEDY HEREIN FAILS OF ITS ESSENTIAL PURPOSE. THE MAXIMUM LIABILITY OF DWAVE TO LICENSEE SHALL IN ANY EVENT NOT EXCEED THE LESSER OF (A) THE SUM OF THE LICENSE FEE PAID BY LICENSEE FOR THE SOFTWARE; OR (B) CAD$250. THE FOREGOING LIMITATIONS WILL APPLY EVEN IF THE ABOVE STATED REMEDY FAILS OF ITS ESSENTIAL PURPOSE. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF IMPLIED WARRANTIES OR LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, AND PARAGRAPHS 3 AND 4 WILL NOT APPLY ONLY TO THE EXTENT THAT APPLICABLE LAW REQUIRES LIABILITY NOTWITHSTANDING THE LIMITATIONS OR EXCLUSIONS THEREIN.
8. LICENSEE ACKNOWLEDGES AND AGREES THAT THE SOFTWARE IS NOT DESIGNED, INTENDED, AUTHORIZED OR SUITABLE FOR USE IN ANY TYPE OF SYSTEM, APPLICATION, SITUATION OR ENVIRONMENT WHERE THE FAILURE OR TIME DELAYS OF, OR ERRORS OR INACCURACIES IN, THE CONTENT, DATA OR INFORMATION PROVIDED BY THE SOFTWARE COULD LEAD TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE, INCLUDING WITHOUT LIMITATION THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, LIFE SUPPORT, MEDICAL SYSTEMS OR WEAPONS SYSTEMS AND THAT LICENSEE WILL NOT USE THE SOFTWARE IN SUCH SYSTEM, APPLICATION, SITUATION OR ENVIRONMENT.
9. INDEMNIFICATION. To the maximum extent permitted by law, Licensee agrees to defend, indemnify and hold harmless DWAVE, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) Licensee’s use of the Software, (b) any application Licensee develops using the Software that infringes or violates any right of any person or defames any person, and (c) any noncompliance by Licensee with this EULA.
 TERMINATION.
a. This EULA is effective from the date on which the attached Software is installed or used by Licensee until terminated. This EULA will terminate automatically without notice from DWAVE if Licensee fails to comply with any provision of this EULA or if DWAVE is required to do so by law. If Licensee commences or participates in any legal proceeding against DWAVE, then DWAVE may, in its sole discretion, suspend or terminate this EULA during the pendency of such legal proceedings. Licensee may voluntarily terminate this EULA at any time by ceasing to use the Software.
b. Upon termination of this EULA at any time and for any reason, Licensee will immediately discontinue any and all use of the Software, purge the Software from all computer systems, storage media and other files, including any backup copy, and return to DWAVE the Software, including the Documentation, and all copies thereof, or at the request of DWAVE, destroy the Software, the Documentation, and all copies thereof, and deliver to DWAVE certification that Licensee has complied with these termination obligations.
c. If this EULA is terminated at any time and for any reason, Licensee will not be entitled to compensation of any kind, financial or otherwise.
d. Paragraphs 3 through 9, 13(a) and 13(f) of this EULA and such other provisions as may reasonably be expected to remain in force will survive the termination of this EULA and will remain in full force and effect following such termination.
11. NO WAIVERS. A waiver expressed or implied by a party of any default of the other party in the observance or performance of this EULA must be in writing, and such waiver does not constitute and is not to be construed as a waiver or condonation of any subsequent or other default, and a waiver of any provision of this EULA will not be effective unless in writing and signed by an authorized officer of DWAVE.
12. MODIFICATIONS AND NOTICES. No reseller, distributor or dealer of the Software is authorized to make any modifications, extensions, or additions to this EULA. DWAVE may, in its sole discretion, modify this EULA. If DWAVE elects to do so, DWAVE will notify Licensee of such change. If Licensee does not agree to the change, then this EULA automatically terminates and Licensee must stop using the Software and comply with Section 10(b) of this EULA. If Licensee does not stop using the Software, then Licensee’s use of the Software will continue under the changed EULA. DWAVE may give notices to Licensee, at DWAVE’s option, by posting on any portion of www.dwavesys.com or by electronic mail to any email address provided by Licensee to DWAVE.
 GOVERNING LAW AND GENERAL PROVISIONS.
a. Governing Law and Other General Provisions. This EULA will be governed by and construed in accordance with the substantive laws in force in the Province of British Columbia, Canada, excluding its conflict of law rules. The courts of the Province of British Columbia shall have exclusive jurisdiction over all disputes relating to this EULA. Licensee and DWAVE agree to submit to the exclusive jurisdiction of the courts of British Columbia. This EULA will not be governed by the conflict of law rules of any jurisdiction or the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded.
 Time. Time is of the essence of this EULA.
c. Severance. If any provision in this EULA should be held invalid or unenforceable, such provision shall be modified to the extent necessary to render it valid or enforceable or severed from this EULA if no such modification is possible, and the other provisions of this EULA shall remain in full force and effect.
d. Assignment. Licensee may not assign its rights or delegate its obligations under this EULA without the prior written consent of DWAVE, which consent may be withheld in the sole discretion of D WAVE. DWAVE may assign its rights or delegate its obligations under this EULA to any person in its sole discretion. This EULA shall be binding on and inure to the benefit of the parties and their successors and permitted assigns.
e. No Other EULAs. This EULA is the entire agreement of the parties with respect to the Software, and there are no other agreements, written, oral, electronic or otherwise, with respect to the Software, and it supersedes any prior representations, discussions, undertakings, communications or advertising relating to the Software.
f. Compliance with Licenses. If Licensee is a business or organization, Licensee agrees that upon request from DWAVE or DWAVE’s authorized representative, Licensee will within thirty (30) days fully document and certify that use of any and all Software at the time of the request is in conformity with Licensee’s valid licenses from DWAVE.
g. English Language. Licensee and DWAVE confirm that it is their wish that this EULA, as well as other documents relating hereto, including notices, have been and shall be written in English only. Licensee et DWAVE confirment leur desir que cet accord ainsi que tous les documents, y compris tous avis qui s’y rattachent, soient rediges en anglais.
Updated January 4, 2017
dwave CLI¶
As part of the installation of the dwaveoceansdk a dwave executable is installed; for example, in a virtual environment it might be installed as <virtual_environment>\Scripts\dwave.exe. Running this file from your system’s console opens an interactive command line interface (CLI) that can help you set up and configure your development environment, communicate with DWave compute resources, and other useful actions.
Run dwave  help
for information on all the CLI options. For SDK
version 1.6.1 the CLI provided the following commands and options
(see the output in your installation for the latest):
$ dwave
Usage: dwave [OPTIONS] COMMAND [ARGS]...
DWave Cloud Client interactive configuration tool.
Options:
version Show the version and exit.
debug Enable debug logging.
trace Enable tracelevel debug logging.
log LEVEL Set custom numeric or symbolic log level.
help Show this message and exit.
Commands:
config Create, update or inspect cloud client configuration file(s).
install Install optional nonopensource Ocean packages.
ping Ping the QPU by submitting a singlequbit problem.
sample Submit Isingformulated problem and return samples.
setup Setup optional Ocean packages and configuration file(s).
solvers Get solver details.
upload Multipart problem upload with cold restart support.
Note
If you work in a Bash shell and want command completion for dwave, add
eval "$(_DWAVE_COMPLETE=source <path>/dwave)"
to your shell’s .bashrc configuration file, where <path> is the absolute path to the installed dwave executable, for example /home/Mary/myquantumapp/env/bin.
Below are shown example sessions for some of the commands:
Setup¶
The dwave setup
command optionally installs nonopensource packages
and configures your environment.
The output shown below includes the interactive prompts and placeholder replies for a full setup.
$ dwave setup
Optionally install nonopensource packages and configure your environment.
Do you want to select nonopensource packages to install (y/n)? [y]:
DWave Drivers
These drivers enable some automated performancetuning features.
This package is available under the 'DWave EULA' license.
The terms of the license are available online: https://docs.ocean.dwavesys.com/eula
Install (y/n)? [y]:
Installing: DWave Drivers
Successfully installed DWave Drivers.
DWave Problem Inspector
This tool visualizes problems submitted to the quantum computer and the results returned.
This package is available under the 'DWave EULA' license.
The terms of the license are available online: https://docs.ocean.dwavesys.com/eula
Install (y/n)? [y]:
Installing: DWave Problem Inspector
Successfully installed DWave Problem Inspector.
Creating the DWave configuration file.
Configuration file not found; the default location is: /home/jane/.config/dwave/dwave.conf
Confirm configuration file path [/home/jane/.config/dwave/dwave.conf]:
Profile (create new) [prod]:
API endpoint URL [skip]:
Authentication token [skip]: ABC1234567890abcdef1234567890abcdef
Default client class (qpu or sw) [qpu]:
Default solver [skip]:
Configuration saved.
Configure¶
The dwave config
command configures your environment.
The output shown below includes the interactive prompts and placeholder replies.
$ dwave config create
Configuration file not found; the default location is: /home/jane/.config/dwave/dwave.conf
Confirm configuration file path [/home/jane/.config/dwave/dwave.conf]:
Profile (create new) [prod]:
API endpoint URL [skip]:
Authentication token [skip]: ABC1234567890abcdef1234567890abcdef
Default client class (qpu or sw) [qpu]:
Default solver [skip]:
Configuration saved.
Ping¶
The dwave ping
command tests communications with the quantum computer
configured using the dwave setup
or dwave config
commands.
$ dwave ping
Using endpoint: https://cloud.dwavesys.com/sapi
Using solver: My_DWAVE_2000Q
Wall clock time:
* Solver definition fetch: 2007.239 ms
* Problem submit and results fetch: 1033.931 ms
* Total: 3041.171 ms
QPU timing:
* total_real_time = 10493 us
* anneal_time_per_run = 20 us
* post_processing_overhead_time = 128 us
* qpu_anneal_time_per_sample = 20 us
# Snipped for brevity
Solvers¶
The dwave solvers
command queries which DWave compute resources are
currently available to your account based.
$ dwave solvers
Solver: DW_2000Q_33
Parameters:
anneal_offsets: A list of anneal offsets for each working qubit (NaN if u...
anneal_schedule: A piecewise linear annealing schedule specified by a list...
annealing_time: A positive integer that sets the duration (in microsecond...
<Output snipped for brevity>
Properties:
anneal_offset_ranges: [[0.18627387668142237, 0.09542224439071689], [0.1836548...
anneal_offset_step: 0.00426679499507194
anneal_offset_step_phi0: 0.0002716837027763096
annealing_time_range: [1, 150000]
chip_id: W71_C16_472485402G4_C5R9devicecaldata18052714:27
couplers: [[0, 4], [1, 4], [2, 4], [3, 4], [0, 5], [1, 5], [2, 5], ...
<Output snipped for brevity>
Packages¶
The SDK includes the dwave CLI and the following packages:
dimod (repo)  Shared API for binary quadratic samplers. Provides a binary quadratic model (BQM) class that contains Ising and quadratic unconstrained binary optimization (QUBO) models used by samplers such as the DWave system. Also provides utilities for constructing new samplers and composed samplers. 
dwavebinarycsp (repo)  Library to construct a binary quadratic model from a constraint satisfaction problem with small constraints over binary variables. 
dwavecloudclient (repo)  Minimal implementation of the REST interface used to communicate with DWave Sampler API (SAPI) servers. 
dwavehybrid (repo)  A general, minimal Python framework for building hybrid asynchronous decomposition samplers for quadratic unconstrained binary optimization (QUBO) problems. 
dwaveinspector (repo)  A tool for visualizing problems submitted to, and answers received from, a DWave structured solver such as a DWave 2000Q quantum computer. 
dwaveneal (repo)  An implementation of a simulated annealing sampler. 
dwavenetworkx (repo)  Extension of NetworkX—a Python language package for exploration and analysis of networks and network algorithms—for users of DWave Systems. dwavenetworkx provides tools for working with Chimera graphs and implementations of graphtheory algorithms on the DWave system and other binary quadratic model samplers. 
dwaveoceansdk (repo)  Installer for DWave’s Ocean Tools. 
dwavesystem (repo)  Basic API for easily incorporating the DWave system as a sampler in the DWave Ocean software stack. It includes DWaveSampler, a dimod sampler that accepts and passes system parameters such as system identification and authentication down the stack. It also includes several useful composites—layers of pre and postprocessing—that can be used with DWaveSampler to handle minorembedding, optimize chain strength, etc. 
dwavetabu (repo)  An implementation of the MST2 multistart tabu search algorithm for quadratic unconstrained binary optimization (QUBO) problems with a dimod Python wrapper. 
penaltymodel (repo)  An approach to solve a constraint satisfaction problem (CSP) using an Ising model or a QUBO, is to map each individual constraint in the CSP to a ‘small’ Ising model or QUBO. Includes a local cache for penalty models and a factory that generates penalty models using SMT solvers. 
minorminer (repo)  A tool for finding graph minorembeddings, developed to embed Ising problems onto quantum annealers (QA). While it can be used to find minors in arbitrary graphs, it is particularly geared towards the state of the art in QA: problem graphs of a few to a few hundred variables, and hardware graphs of a few thousand qubits. 
qbsolv (repo)  A decomposing solver that finds a minimum value of a large quadratic unconstrained binary optimization (QUBO) problem by splitting it into pieces. The pieces are solved using a classical solver running the tabu algorithm. qbsolv also enables configuring a DWave system as the solver. 
dimod¶
dimod is a shared API for binary quadratic samplers. It provides a binary quadratic model (BQM) class that contains Ising and quadratic unconstrained binary optimization (QUBO) models used by samplers such as the DWave system. It also provides utilities for constructing new samplers and composed samplers and for minorembedding. Its reference examples include several samplers and composed samplers.
Introduction¶
dimod provides a binary quadratic model (BQM) class that encodes Ising and quadratic unconstrained binary optimization (QUBO) models used by samplers such as the DWave system.
It provides useful functionality for working with these models and samplers; for example generators_dimod to build BQMs and Utilities for calculating the energy of a sample or serializing dimod objects.
It includes reference samplers and composites for processing binary quadratic programs and refining sampling, and useful for testing your code during development.
It also provides an API for Samplers and Composites for constructing new samplers and composed samplers tailored for your problem.
Additionally, it provides some HigherOrder Composites and functionality such as reducing higherorder polynomials to BQMs.
 For an introduction to BQMs, see Binary Quadratic Models.
 For an introduction to samplers and composites, see Samplers and Composites.
Examples¶
Solving problems with large numbers of variables might necessitate the use of decomposition[1] methods such as branchandbound to reduce the number of variables. The following illustrative example reduces an Ising model for a small problem (the K4 complete graph), and converts the reducedvariables model to QUBO formulation.
[1]  Ocean software’s DWave Hybrid provides tools for decomposing large problems. 
>>> import dimod
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
>>> bqm_k4.vartype
<Vartype.SPIN: frozenset([1, 1])>
>>> len(bqm_k4.linear)
4
>>> bqm_k4.contract_variables(2, 3)
>>> len(bqm_k4.linear)
3
>>> bqm_no3_qubo = bqm_k4.binary
>>> bqm_no3_qubo.vartype
<Vartype.BINARY: frozenset([0, 1])>
The next example uses a composed sampler on the Boolean NOT Gate
example detailed in the Getting Started documentation.
The ExactSolver
test sampler calculates the
energy of all possible samples; the FixedVariableComposite
composite sets the value and removes specified variables from the BQM before sending it to
the sampler. Fixing variable x, the input to the NOT gate, to 1 results in valid solution
\(z=0\) having lower energy (1) than solution \(x=z=1\), which is an invalid
state for a NOT gate.
>>> from dimod import FixedVariableComposite, ExactSolver
>>> Q = {('x', 'x'): 1, ('x', 'z'): 2, ('z', 'x'): 0, ('z', 'z'): 1}
>>> composed_sampler = FixedVariableComposite(ExactSolver())
>>> sampleset = composed_sampler.sample_qubo(Q, fixed_variables={'x': 1})
>>> print(sampleset)
x z energy num_oc.
0 1 0 1.0 1
1 1 1 0.0 1
['BINARY', 2 rows, 2 samples, 2 variables]
The next example creates a dimod sampler by implementing a single method (in this example
the sample_ising()
method).
class LinearIsingSampler(dimod.Sampler):
def sample_ising(self, h, J):
sample = linear_ising(h, J) # Defined elsewhere
energy = dimod.ising_energy(sample, h, J)
return dimod.Response.from_samples([sample], {'energy': [energy]})
@property
def properties(self):
return dict()
@property
def parameters(self):
return dict()
The Sampler
ABC provides the other sample methods “for free”
as mixins.
Reference Documentation¶
Release: 2.1.0 Date: Mar 27, 2020
Binary Quadratic Models¶
Binary quadratic models (BQMs) are described under Binary Quadratic Models.
BQM Classes¶
dimod.AdjArrayBQM¶

class
AdjArrayBQM
(vartype=None, *args)¶ A binary quadratic model structured as two c++ vectors.
Can be created in several ways:
 AdjArrayBQM(vartype)
 Creates an empty binary quadratic model.
 AdjArrayBQM(bqm)
 Creates a BQM from another BQM. See copy and cls kwargs below.
 AdjArrayBQM(bqm, vartype)
 Creates a BQM from another BQM, changing to the appropriate vartype if necessary.
 AdjArrayBQM(n, vartype)
 Creates a BQM with n variables, indexed linearly from zero, setting all biases to zero.
 AdjArrayBQM(quadratic, vartype)
 Creates a BQM from quadratic biases given as a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjArrayBQM(linear, quadratic, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjArrayBQM(linear, quadratic, offset, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}, and offset is a numerical offset. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
Notes
The AdjArrayBQM is implemented using two c++ vectors. The first vector contains the linear biases and the index of the start of each variable’s neighborhood in the second vector. The second vector contains the neighboring variables and their associated quadratic biases. The vectors, once initialized, are not resized.
Advantages:
 Very fast iteration over the biases
Disadvantages:
 Does not support incremental construction
 Only supports float64 biases
Intended Use:
 When performance is important and the BQM can be treated as readonly
Examples
>>> import numpy as np >>> from dimod import AdjArrayBQM
>>> # Construct from a numpy array >>> AdjArrayBQM(np.triu(np.ones((2, 2))), 'BINARY') AdjArrayBQM({0: 1.0, 1: 1.0}, {(0, 1): 1.0}, 0.0, 'BINARY')
>>> # Construct from dicts >>> AdjArrayBQM({'a': 1}, {('a', 'b'): 1}, 'SPIN') AdjArrayBQM({a: 1.0, b: 0.0}, {('a', 'b'): 1.0}, 0.0, 'SPIN')
dtype 
The data type of the linear biases, float64. 
itype 
The data type of the indices, uint32. 
ntype 
The data type of the neighborhood indices, varies by platform. 
num_interactions 
The number of interactions in the model. 
num_variables 
The number of variables in the model. 
offset 
The constant energy offset associated with the model. 
shape 
A 2tuple, the num_variables and num_interactions . 
variables 
The variables of the binary quadratic model. 
vartype 
The variable type, Vartype.SPIN or Vartype.BINARY . 
adj 
Quadratic biases as a nested dict of dicts. 
linear 
Linear biases as a mapping. 
quadratic 
Quadratic biases as a flat mapping. 
binary 
The binaryvalued version of the binary quadratic model. 
spin 
The spinvalued version of the binary quadratic model. 
add_offset (offset) 
Add specified value to the offset of a binary quadratic model. 
change_vartype (self, vartype[, inplace]) 
Return a binary quadratic model with the specified vartype. 
copy (self) 
Return a copy. 
degree (self, v) 

degrees ([array, dtype]) 

empty (vartype) 
Create a new empty binary quadratic model. 
energies (self, samples[, dtype]) 
Determine the energies of the given samples. 
energy (sample[, dtype]) 

flip_variable (v) 
Flip variable v in a binary quadratic model. 
from_coo (obj[, vartype]) 
Deserialize a binary quadratic model from a COOrdinate format encoding. 
from_ising (h, J[, offset]) 
Create a binary quadratic model from an Ising problem. 
from_networkx_graph (G[, vartype, …]) 
Create a binary quadratic model from a NetworkX graph. 
from_numpy_matrix (mat[, variable_order, …]) 
Create a binary quadratic model from a NumPy array. 
from_numpy_vectors (linear, quadratic, …[, …]) 
Create a binary quadratic model from vectors. 
from_qubo (Q[, offset]) 
Create a binary quadratic model from a QUBO problem. 
get_linear (self, v) 

get_quadratic (self, u, v[, default]) 
Get the quadratic bias of (u, v). 
has_variable (v) 
Return True if v is a variable in the binary quadratic model. 
iter_interactions () 
Iterate over the interactions of the binary quadratic model. 
iter_linear (self) 

iter_neighbors (u) 
Iterate over the neighbors of a variable in the bqm. 
iter_quadratic (self[, variables]) 

iter_variables () 
Iterate over the variables of the binary quadratic model. 
normalize ([bias_range, quadratic_range, …]) 
Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately. 
relabel_variables 

scale (scalar[, ignored_variables, …]) 
Multiply all the biases by the specified scalar. 
set_linear (self, v, Bias b) 

set_quadratic (self, u, v, Bias b) 

shapeable () 

to_coo ([fp, vartype_header]) 
Serialize the binary quadratic model to a COOrdinate format encoding. 
to_ising () 
Converts a binary quadratic model to Ising format. 
to_networkx_graph ([node_attribute_name, …]) 
Convert a binary quadratic model to NetworkX graph format. 
to_numpy_matrix ([variable_order]) 
Convert a binary quadratic model to NumPy 2D array. 
to_numpy_vectors (self[, variable_order, …]) 
Convert to numpy vectors. 
to_qubo () 
Convert a binary quadratic model to QUBO format. 
remove_offset () 
Set the binary quadratic model’s offset to zero. 
dimod.AdjDictBQM¶

class
AdjDictBQM
(*args, vartype=None)[source]¶ A binary quadratic model structured as a dictofdicts.
Can be created in several ways:
 AdjDictBQM(vartype)
 Creates an empty binary quadratic model.
 AdjDictBQM(bqm)
 Creates a BQM from another BQM. See copy and cls kwargs below.
 AdjDictBQM(bqm, vartype)
 Creates a BQM from another BQM, changing to the appropriate vartype if necessary.
 AdjDictBQM(n, vartype)
 Creates a BQM with n variables, indexed linearly from zero, setting all biases to zero.
 AdjDictBQM(quadratic, vartype)
 Creates a BQM from quadratic biases given as a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjDictBQM(linear, quadratic, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjDictBQM(linear, quadratic, offset, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}, and offset is a numerical offset. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
Notes
The AdjDictBQM is implemented using a dictofdicts structure. The outer dict contains the BQM’s variables as keys and the neighborhoods as values. Each neighborhood dict contains the neighbors as keys and the quadratic biases as values. The linear biases are stored as selfinteractions.
Advantages:
 Pure python implementation
 Supports arbitrary python types as biases
 Low complexity for lookup operations
 Supports incremental construction
Disadvantages:
 Slow iteration
 High memory usage
Intended Use:
 For small problems or when flexibility is important
Examples
>>> import numpy as np >>> from dimod import AdjDictBQM
>>> # Construct from dicts >>> AdjDictBQM({'a': 1.0}, {('a', 'b'): 1.0}, 'SPIN') AdjDictBQM({a: 1.0, b: 0.0}, {('a', 'b'): 1.0}, 0.0, 'SPIN')
>>> # Incremental Construction >>> bqm = AdjDictBQM('SPIN') >>> bqm.add_variable('a') 'a' >>> bqm.add_variable() 1 >>> bqm.set_quadratic('a', 1, 3.0) >>> bqm AdjDictBQM({a: 0.0, 1: 0.0}, {('a', 1): 3.0}, 0.0, 'SPIN')
>>> # Supports arbitrary types >>> from fractions import Fraction >>> AdjDictBQM({('a', 'b'): Fraction(1, 3)}, 'BINARY') AdjDictBQM({a: 0.0, b: 0.0}, {('a', 'b'): 1/3}, 0.0, 'BINARY')
num_interactions 
The number of interactions in the model. 
num_variables 
The number of variables in the model. 
offset 
The constant energy offset associated with the model. 
shape 
A 2tuple, the num_variables and num_interactions . 
variables 
The variables of the binary quadratic model. 
vartype 
The vartype of the binary quadratic model. 
adj 
Quadratic biases as a nested dict of dicts. 
linear 
Linear biases as a mapping. 
quadratic 
Quadratic biases as a flat mapping. 
binary 
The binaryvalued version of the binary quadratic model. 
spin 
The spinvalued version of the binary quadratic model. 
add_offset (offset) 
Add specified value to the offset of a binary quadratic model. 
add_interaction (u, v, bias) 
Add an interaction and/or quadratic bias to a binary quadratic model. 
add_interactions_from (quadratic) 
Add interactions and/or quadratic biases to a binary quadratic model. 
add_variable ([v, bias]) 
Add a variable to the binary quadratic model. 
add_variables_from (linear) 
Add variables and/or linear biases to a binary quadratic model. 
change_vartype (vartype[, inplace]) 
Return a binary quadratic model with the specified vartype. 
contract_variables (u, v) 
Enforce u, v being the same variable in a binary quadratic model. 
copy () 
Return a copy. 
degree (v) 
The number of variables sharing an interaction with v. 
degrees ([array, dtype]) 

empty (vartype) 
Create a new empty binary quadratic model. 
energies (samples_like[, dtype]) 
Determine the energies of the given samples. 
energy (sample[, dtype]) 

fix_variables (fixed) 
Fix the value of the variables and remove them. 
flip_variable (v) 
Flip variable v in a binary quadratic model. 
from_coo (obj[, vartype]) 
Deserialize a binary quadratic model from a COOrdinate format encoding. 
from_ising (h, J[, offset]) 
Create a binary quadratic model from an Ising problem. 
from_networkx_graph (G[, vartype, …]) 
Create a binary quadratic model from a NetworkX graph. 
from_numpy_matrix (mat[, variable_order, …]) 
Create a binary quadratic model from a NumPy array. 
from_numpy_vectors (linear, quadratic, …[, …]) 
Create a binary quadratic model from vectors. 
from_qubo (Q[, offset]) 
Create a binary quadratic model from a QUBO problem. 
get_linear (v) 
Get the linear bias of v. 
get_quadratic (u, v[, default]) 
Get the quadratic bias of (u, v). 
has_variable (v) 
Return True if v is a variable in the binary quadratic model. 
iter_interactions () 
Iterate over the interactions of the binary quadratic model. 
iter_linear () 

iter_neighbors (u) 
Iterate over the neighbors of a variable in the bqm. 
iter_quadratic ([variables]) 

iter_variables () 
Iterate over the variables of the binary quadratic model. 
normalize ([bias_range, quadratic_range, …]) 
Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately. 
relabel_variables (mapping[, inplace]) 
Relabel variables of a binary quadratic model as specified by mapping. 
scale (scalar[, ignored_variables, …]) 
Multiply all the biases by the specified scalar. 
set_linear (v, bias) 
Set the linear biase of a variable v. 
set_quadratic (u, v, bias) 
Set the quadratic bias of (u, v). 
shapeable () 

to_coo ([fp, vartype_header]) 
Serialize the binary quadratic model to a COOrdinate format encoding. 
to_ising () 
Converts a binary quadratic model to Ising format. 
to_networkx_graph ([node_attribute_name, …]) 
Convert a binary quadratic model to NetworkX graph format. 
to_numpy_matrix ([variable_order]) 
Convert a binary quadratic model to NumPy 2D array. 
to_numpy_vectors ([variable_order, dtype, …]) 
The BQM as 4 numpy vectors, the offset and a list of variables. 
to_qubo () 
Convert a binary quadratic model to QUBO format. 
remove_interaction (u, v) 
Remove the interaction between variables u and v. 
remove_interactions_from (interactions) 
Remove the given interactions from the binary quadratic model. 
remove_offset () 
Set the binary quadratic model’s offset to zero. 
remove_variable ([v]) 
Remove a variable and its associated interactions. 
remove_variables_from (variables) 
Remove the given variables from the binary quadratic model. 
update (other) 
Update the binary quadratic model, adding biases from another. 
dimod.AdjMapBQM¶

class
AdjMapBQM
(vartype=None, *args)¶ A binary quadratic model where the neighborhoods are c++ maps.
Can be created in several ways:
 AdjMapBQM(vartype)
 Creates an empty binary quadratic model.
 AdjMapBQM(bqm)
 Creates a BQM from another BQM. See copy and cls kwargs below.
 AdjMapBQM(bqm, vartype)
 Creates a BQM from another BQM, changing to the appropriate vartype if necessary.
 AdjMapBQM(n, vartype)
 Creates a BQM with n variables, indexed linearly from zero, setting all biases to zero.
 AdjMapBQM(quadratic, vartype)
 Creates a BQM from quadratic biases given as a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjMapBQM(linear, quadratic, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjMapBQM(linear, quadratic, offset, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}, and offset is a numerical offset. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
Notes
The AdjMapBQM is implemented using an adjacency structure where the neighborhoods are implemented as c++ maps.
Advantages:
 Fast incremental construction and destruction
Disadvantages:
 Slower iteration than
AdjArrayBQM
andAdjVectorBQM
 Only supports float64 biases
Intended Use:
 When performance is important but the BQM’s shape is changing frequently
Examples
>>> import numpy as np >>> from dimod import AdjMapBQM
>>> # Construct from dicts >>> AdjMapBQM({'a': 1.0}, {('a', 'b'): 1.0}, 'SPIN') AdjMapBQM({a: 1.0, b: 0.0}, {('a', 'b'): 1.0}, 0.0, 'SPIN')
>>> # Incremental Construction >>> bqm = AdjMapBQM('SPIN') >>> bqm.add_variable('a') 'a' >>> bqm.add_variable() 1 >>> bqm.set_quadratic('a', 1, 3.0) >>> bqm AdjMapBQM({a: 0.0, 1: 0.0}, {('a', 1): 3.0}, 0.0, 'SPIN')
dtype 
The data type of the linear biases, float64. 
itype 
The data type of the indices, uint32. 
ntype 
The data type of the neighborhood indices, varies by platform. 
num_interactions 
The number of interactions in the model. 
num_variables 
The number of variables in the model. 
offset 
The constant energy offset associated with the model. 
shape 
A 2tuple, the num_variables and num_interactions . 
variables 
The variables of the binary quadratic model. 
vartype 
The variable type, Vartype.SPIN or Vartype.BINARY . 
adj 
Quadratic biases as a nested dict of dicts. 
linear 
Linear biases as a mapping. 
quadratic 
Quadratic biases as a flat mapping. 
binary 
The binaryvalued version of the binary quadratic model. 
spin 
The spinvalued version of the binary quadratic model. 
add_offset (offset) 
Add specified value to the offset of a binary quadratic model. 
add_interaction (u, v, bias) 
Add an interaction and/or quadratic bias to a binary quadratic model. 
add_interactions_from (quadratic) 
Add interactions and/or quadratic biases to a binary quadratic model. 
add_variable (self[, v]) 
Add a variable to the binary quadratic model. 
add_variables_from (linear) 
Add variables and/or linear biases to a binary quadratic model. 
change_vartype (self, vartype[, inplace]) 
Return a binary quadratic model with the specified vartype. 
contract_variables (u, v) 
Enforce u, v being the same variable in a binary quadratic model. 
copy (self) 
Return a copy. 
degree (self, v) 

degrees ([array, dtype]) 

empty (vartype) 
Create a new empty binary quadratic model. 
energies (self, samples[, dtype]) 
Determine the energies of the given samples. 
energy (sample[, dtype]) 

fix_variables (fixed) 
Fix the value of the variables and remove them. 
flip_variable (v) 
Flip variable v in a binary quadratic model. 
from_coo (obj[, vartype]) 
Deserialize a binary quadratic model from a COOrdinate format encoding. 
from_ising (h, J[, offset]) 
Create a binary quadratic model from an Ising problem. 
from_networkx_graph (G[, vartype, …]) 
Create a binary quadratic model from a NetworkX graph. 
from_numpy_matrix (mat[, variable_order, …]) 
Create a binary quadratic model from a NumPy array. 
from_numpy_vectors (linear, quadratic, …[, …]) 
Create a binary quadratic model from vectors. 
from_qubo (Q[, offset]) 
Create a binary quadratic model from a QUBO problem. 
get_linear (self, v) 
Get the linear bias of v. 
get_quadratic (self, u, v[, default]) 
Get the quadratic bias of (u, v). 
has_variable (v) 
Return True if v is a variable in the binary quadratic model. 
iter_interactions () 
Iterate over the interactions of the binary quadratic model. 
iter_linear (self) 

iter_neighbors (u) 
Iterate over the neighbors of a variable in the bqm. 
iter_quadratic (self[, variables]) 

iter_variables () 
Iterate over the variables of the binary quadratic model. 
normalize ([bias_range, quadratic_range, …]) 
Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately. 
relabel_variables 

scale (scalar[, ignored_variables, …]) 
Multiply all the biases by the specified scalar. 
set_linear (self, v, Bias b) 
Set the linear biase of a variable v. 
set_quadratic (self, u, v, Bias b) 
Set the quadratic bias of (u, v). 
shapeable () 

to_coo ([fp, vartype_header]) 
Serialize the binary quadratic model to a COOrdinate format encoding. 
to_ising () 
Converts a binary quadratic model to Ising format. 
to_networkx_graph ([node_attribute_name, …]) 
Convert a binary quadratic model to NetworkX graph format. 
to_numpy_matrix ([variable_order]) 
Convert a binary quadratic model to NumPy 2D array. 
to_numpy_vectors (self[, variable_order, …]) 
Convert to numpy vectors. 
to_qubo () 
Convert a binary quadratic model to QUBO format. 
remove_interaction (self, u, v) 
Remove the interaction between variables u and v. 
remove_interactions_from (interactions) 
Remove the given interactions from the binary quadratic model. 
remove_offset () 
Set the binary quadratic model’s offset to zero. 
remove_variable (self[, v]) 
Remove a variable and its associated interactions. 
remove_variables_from (variables) 
Remove the given variables from the binary quadratic model. 
update (other) 
Update the binary quadratic model, adding biases from another. 
dimod.AdjVectorBQM¶

class
AdjVectorBQM
(vartype=None, *args)¶ A binary quadratic model where the neighborhoods are c++ vectors.
Can be created in several ways:
 AdjVectorBQM(vartype)
 Creates an empty binary quadratic model.
 AdjVectorBQM(bqm)
 Creates a BQM from another BQM. See copy and cls kwargs below.
 AdjVectorBQM(bqm, vartype)
 Creates a BQM from another BQM, changing to the appropriate vartype if necessary.
 AdjVectorBQM(n, vartype)
 Creates a BQM with n variables, indexed linearly from zero, setting all biases to zero.
 AdjVectorBQM(quadratic, vartype)
 Creates a BQM from quadratic biases given as a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjVectorBQM(linear, quadratic, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
 AdjVectorBQM(linear, quadratic, offset, vartype)
 Creates a BQM from linear and quadratic biases, where linear is a onedimensional array_like or a dictionary of the form {v: b, …}, and quadratic is a square array_like or a dictionary of the form {(u, v): b, …}, and offset is a numerical offset. Note that when formed with SPINvariables, biases on the diagonal are added to the offset.
Notes
The AdjVectorBQM is implemented using an adjacency structure where the neighborhoods are implemented as c++ vectors.
Advantages:
 Supports incremental construction
 Fast iteration over the biases
Disadvantages:
 Only supports float64 biases
Intended Use:
 When performance is important and the use case requires incremental construction
 This should be the default BQM type for large problems where arbitrary types are not needed
Examples
>>> import numpy as np >>> from dimod import AdjVectorBQM
>>> # Construct from dicts >>> AdjVectorBQM({'a': 1.0}, {('a', 'b'): 1.0}, 'SPIN') AdjVectorBQM({a: 1.0, b: 0.0}, {('a', 'b'): 1.0}, 0.0, 'SPIN')
>>> # Incremental Construction >>> bqm = AdjVectorBQM('SPIN') >>> bqm.add_variable('a') 'a' >>> bqm.add_variable() 1 >>> bqm.set_quadratic('a', 1, 3.0) >>> bqm AdjVectorBQM({a: 0.0, 1: 0.0}, {('a', 1): 3.0}, 0.0, 'SPIN')
dtype 
The data type of the linear biases, float64. 
itype 
The data type of the indices, uint32. 
ntype 
The data type of the neighborhood indices, varies by platform. 
num_interactions 
The number of interactions in the model. 
num_variables 
The number of variables in the model. 
offset 
The constant energy offset associated with the model. 
shape 
A 2tuple, the num_variables and num_interactions . 
variables 
The variables of the binary quadratic model. 
vartype 
The variable type, Vartype.SPIN or Vartype.BINARY . 
adj 
Quadratic biases as a nested dict of dicts. 
linear 
Linear biases as a mapping. 
quadratic 
Quadratic biases as a flat mapping. 
binary 
The binaryvalued version of the binary quadratic model. 
spin 
The spinvalued version of the binary quadratic model. 
add_offset (offset) 
Add specified value to the offset of a binary quadratic model. 
add_interaction (u, v, bias) 
Add an interaction and/or quadratic bias to a binary quadratic model. 
add_interactions_from (quadratic) 
Add interactions and/or quadratic biases to a binary quadratic model. 
add_variable (self[, v]) 
Add a variable to the binary quadratic model. 
add_variables_from (linear) 
Add variables and/or linear biases to a binary quadratic model. 
change_vartype (self, vartype[, inplace]) 
Return a binary quadratic model with the specified vartype. 
contract_variables (u, v) 
Enforce u, v being the same variable in a binary quadratic model. 
copy (self) 
Return a copy. 
degree (self, v) 

degrees ([array, dtype]) 

empty (vartype) 
Create a new empty binary quadratic model. 
energies (self, samples[, dtype]) 
Determine the energies of the given samples. 
energy (sample[, dtype]) 

fix_variables (fixed) 
Fix the value of the variables and remove them. 
flip_variable (v) 
Flip variable v in a binary quadratic model. 
from_coo (obj[, vartype]) 
Deserialize a binary quadratic model from a COOrdinate format encoding. 
from_ising (h, J[, offset]) 
Create a binary quadratic model from an Ising problem. 
from_networkx_graph (G[, vartype, …]) 
Create a binary quadratic model from a NetworkX graph. 
from_numpy_matrix (mat[, variable_order, …]) 
Create a binary quadratic model from a NumPy array. 
from_numpy_vectors (linear, quadratic, …[, …]) 
Create a binary quadratic model from vectors. 
from_qubo (Q[, offset]) 
Create a binary quadratic model from a QUBO problem. 
get_linear (self, v) 
Get the linear bias of v. 
get_quadratic (self, u, v[, default]) 
Get the quadratic bias of (u, v). 
has_variable (v) 
Return True if v is a variable in the binary quadratic model. 
iter_interactions () 
Iterate over the interactions of the binary quadratic model. 
iter_linear (self) 

iter_neighbors (u) 
Iterate over the neighbors of a variable in the bqm. 
iter_quadratic (self[, variables]) 

iter_variables () 
Iterate over the variables of the binary quadratic model. 
normalize ([bias_range, quadratic_range, …]) 
Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately. 
relabel_variables 

scale (scalar[, ignored_variables, …]) 
Multiply all the biases by the specified scalar. 
set_linear (self, v, Bias b) 
Set the linear biase of a variable v. 
set_quadratic (self, u, v, Bias b) 
Set the quadratic bias of (u, v). 
shapeable () 

to_coo ([fp, vartype_header]) 
Serialize the binary quadratic model to a COOrdinate format encoding. 
to_ising () 
Converts a binary quadratic model to Ising format. 
to_networkx_graph ([node_attribute_name, …]) 
Convert a binary quadratic model to NetworkX graph format. 
to_numpy_matrix ([variable_order]) 
Convert a binary quadratic model to NumPy 2D array. 
to_numpy_vectors (self[, variable_order, …]) 
Convert to numpy vectors. 
to_qubo () 
Convert a binary quadratic model to QUBO format. 
remove_interaction (self, u, v) 
Remove the interaction between variables u and v. 
remove_interactions_from (interactions) 
Remove the given interactions from the binary quadratic model. 
remove_offset () 
Set the binary quadratic model’s offset to zero. 
remove_variable (self[, v]) 
Remove a variable and its associated interactions. 
remove_variables_from (variables) 
Remove the given variables from the binary quadratic model. 
update (other) 
Update the binary quadratic model, adding biases from another. 
dimod.BinaryQuadraticModel¶

class
BinaryQuadraticModel
(*args, **kwargs)[source]¶ Encodes a binary quadratic model.
Binary quadratic model is the superclass that contains the Ising model and the QUBO.
Parameters:  linear (dict[variable, bias]) – Linear biases as a dict, where keys are the variables of the binary quadratic model and values the linear biases associated with these variables. A variable can be any python object that is valid as a dictionary key. Biases are generally numbers but this is not explicitly checked.
 quadratic (dict[(variable, variable), bias]) – Quadratic biases as a dict, where keys are 2tuples of variables and values the quadratic biases associated with the pair of variables (the interaction). A variable can be any python object that is valid as a dictionary key. Biases are generally numbers but this is not explicitly checked. Interactions that are not unique are added.
 offset (number) – Constant energy offset associated with the binary quadratic model.
Any input type is allowed, but many applications assume that offset is a number.
See
BinaryQuadraticModel.energy()
.  vartype (
Vartype
/str/set) –Variable type for the binary quadratic model. Accepted input values:
Vartype.SPIN
,'SPIN'
,{1, 1}
Vartype.BINARY
,'BINARY'
,{0, 1}
 **kwargs – Any additional keyword parameters and their values are stored in
BinaryQuadraticModel.info
.
Notes
The
BinaryQuadraticModel
class does not enforce types on biases and offsets, but most applications that use this class assume that they are numeric.Examples
This example creates a binary quadratic model with three spin variables.
>>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: 1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.Vartype.SPIN)
This example creates a binary quadratic model with nonnumeric variables (variables can be any hashable object).
>>> bqm = dimod.BQM({'a': 0.0, 'b': 1.0, 'c': 0.5}, ... {('a', 'b'): 1.0, ('b', 'c'): 1.5}, ... 1.4, ... dimod.SPIN) >>> len(bqm) 3 >>> 'b' in bqm True

linear
¶ Linear biases as a dict, where keys are the variables of the binary quadratic model and values the linear biases associated with these variables.
Type: dict[variable, bias]

quadratic
¶ Quadratic biases as a dict, where keys are 2tuples of variables, which represent an interaction between the two variables, and values are the quadratic biases associated with the interactions.
Type: dict[(variable, variable), bias]

offset
¶ The energy offset associated with the model. Same type as given on instantiation.
Type: number

variables
¶ The variables in the binary quadratic model as a dictionary keys view object.
Type: keysview

adj
¶ The model’s interactions as nested dicts. In graphic representation, where variables are nodes and interactions are edges or adjacencies, keys of the outer dict (adj) are all the model’s nodes (e.g. v) and values are the inner dicts. For the inner dict associated with outerkey/node ‘v’, keys are all the nodes adjacent to v (e.g. u) and values are quadratic biases associated with the pair of inner and outer keys (u, v).
Type: dict
Examples
This example creates an instance of the
BinaryQuadraticModel
class for the K4 complete graph, where the nodes have biases set equal to their sequential labels and interactions are the concatenations of the node pairs (e.g., 23 for u,v = 2,3).>>> import dimod ... >>> linear = {1: 1, 2: 2, 3: 3, 4: 4} >>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14, ... (2, 3): 23, (2, 4): 24, ... (3, 4): 34} >>> offset = 0.0 >>> vartype = dimod.BINARY >>> bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype) >>> bqm_k4.info = {'Complete K4 binary quadratic model.'} >>> bqm_k4.info.issubset({'Complete K3 binary quadratic model.', ... 'Complete K4 binary quadratic model.', ... 'Complete K5 binary quadratic model.'}) True >>> bqm_k4.adj.viewitems() # Show all adjacencies # doctest: +SKIP [(1, {2: 12, 3: 13, 4: 14}), (2, {1: 12, 3: 23, 4: 24}), (3, {1: 13, 2: 23, 4: 34}), (4, {1: 14, 2: 24, 3: 34})] >>> bqm_k4.adj[2] # Show adjacencies for node 2 # doctest: +SKIP {1: 12, 3: 23, 4: 24} >>> bqm_k4.adj[2][3] # Show the quadratic bias for nodes 2,3 # doctest: +SKIP 23
BinaryQuadraticModel (*args, **kwargs) 
Encodes a binary quadratic model. 
AdjArrayBQM ([vartype]) 
A binary quadratic model structured as two c++ vectors. 
AdjDictBQM (*args[, vartype]) 
A binary quadratic model structured as a dictofdicts. 
AdjMapBQM ([vartype]) 
A binary quadratic model where the neighborhoods are c++ maps. 
AdjVectorBQM ([vartype]) 
A binary quadratic model where the neighborhoods are c++ vectors. 
Functions¶
Generic constructor:
as_bqm (*args[, cls, copy]) 
Convert the input to a binary quadratic model. 
Generating BQMs:
chimera_anticluster (m[, n, t, multiplier, …]) 
Generate an anticluster problem on a Chimera lattice. 
combinations (n, k[, strength, vartype]) 
Generate a bqm that is minimized when k of n variables are selected. 
frustrated_loop (graph, num_cycles[, R, …]) 
Generate a frustrated loop problem. 
randint (graph, vartype[, low, high, cls, seed]) 
Generate a bqm with random biases and offset. 
ran_r (r, graph[, cls, seed]) 
Generate an Ising model for a RANr problem. 
uniform (graph, vartype[, low, high, cls, seed]) 
Generate a bqm with random biases and offset. 
Fixing variables:
fix_variables (bqm[, sampling_mode]) 
Determine assignments for some variables of a binary quadratic model. 
Traversing as a graph:
connected_components (bqm) 
Yields sets of connected variables. 
bfs_variables (bqm, source) 
Yields variables in breadthfirst search order. 
Converting to and from other data structures:
to_networkx_graph (bqm[, …]) 
Convert a binary quadratic model to NetworkX graph format. 
from_networkx_graph (G[, vartype, …]) 
Create a binary quadratic model from a NetworkX graph. 
See also: serialization functions
Usage¶
In Ocean, there are four objects that represent BQMs, differentiated by the data structure used to encode their structure and biases.
 AdjArrayBQM: Uses c++ vectors as arrays
 AdjDictBQM: Uses python dictionaries
 AdjMapBQM: Uses c++ maps
 AdjVectorBQM: Uses c++ vectors
The documentation for each class outlines some of the advantages and disadvantages of the different representations.
All of the BQM types use an adjacency structure, in which each variable tracks its own linear bias and its neighborhood. For instance, given a BQM,
its graph and adjacency representations are
The performance of various operations will depend on which binary quadratic model implementation you are using. Let v be the number of variables in the BQM
AdjArrayBQM  AdjDictBQM  AdjMapBQM  AdjVectorBQM  

add_variable  n/a  O(1) [1]  O(1) [2]  O(1) [2] 
add_interaction  n/a  O(1) [3]  O(log v)  O(v) 
get_linear  O(1)  O(1) [1]  O(1)  O(1) 
get_quadratic  O(log v)  O(1) [3]  O(log v)  O(log v) 
num_variables  O(1)  O(1)  O(1)  O(1) 
num_interactions  O(v)  O(v)  O(v)  O(v) 
[1]  (1, 2) Average case, amortized worst case is O(v) 
[2]  (1, 2) Amortized 
[3]  (1, 2) Average case, amortized worst case is O(v^2) 
It is worth noting that although the AdjDictBQM is superior in terms of complexity, in practice it is much slower for large BQMs.
Samplers and Composites¶
Samplers¶
The dimod package includes several example samplers.
Contents
Exact Solver¶
A solver that calculates the energy of all possible samples.
Note
This sampler is designed for use in testing. Because it calculates the energy for every possible sample, it is very slow.

class
ExactSolver
[source]¶ A simple exact solver for testing and debugging code using your local CPU.
Notes
This solver becomes slow for problems with 18 or more variables.
Examples
This example solves a twovariable Ising model.
>>> h = {'a': 0.5, 'b': 1.0} >>> J = {('a', 'b'): 1.5} >>> sampleset = dimod.ExactSolver().sample_ising(h, J) >>> print(sampleset) a b energy num_oc. 0 1 1 2.0 1 2 +1 +1 1.0 1 1 +1 1 0.0 1 3 1 +1 3.0 1 ['SPIN', 4 rows, 4 samples, 2 variables]
This example solves a twovariable QUBO.
>>> Q = {('a', 'b'): 2.0, ('a', 'a'): 1.0, ('b', 'b'): 0.5} >>> sampleset = dimod.ExactSolver().sample_qubo(Q)
This example solves a twovariable binary quadratic model
>>> bqm = dimod.BinaryQuadraticModel({'a': 1.5}, {('a', 'b'): 1}, 0.0, 'SPIN') >>> sampleset = dimod.ExactSolver().sample(bqm)
ExactSolver.sample (bqm) 
Sample from a binary quadratic model. 
ExactSolver.sample_ising (h, J, **parameters) 
Sample from an Ising model using the implemented sample method. 
ExactSolver.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Null Sampler¶
A sampler that always returns an empty sample set.

class
NullSampler
(parameters=None)[source]¶ A sampler that always returns an empty sample set.
This sampler is useful for writing unit tests where the result is not important.
Parameters: parameters (iterable/dict, optional) – If provided, sets the parameters accepted by the sample methods. The values given in these parameters are ignored. Examples
>>> bqm = dimod.BinaryQuadraticModel.from_qubo({('a', 'b'): 1}) >>> sampler = dimod.NullSampler() >>> sampleset = sampler.sample(bqm) >>> len(sampleset) 0
Setting additional parameters for the null sampler.
>>> bqm = dimod.BinaryQuadraticModel.from_qubo({('a', 'b'): 1}) >>> sampler = dimod.NullSampler(parameters=['a']) >>> sampleset = sampler.sample(bqm, a=5)
NullSampler.parameters 
Keyword arguments accepted by the sampling methods 
NullSampler.sample (bqm, **kwargs) 
Return an empty sample set. 
NullSampler.sample_ising (h, J, **parameters) 
Sample from an Ising model using the implemented sample method. 
NullSampler.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Random Sampler¶
A sampler that gives random samples.
RandomSampler.parameters 
Keyword arguments accepted by the sampling methods. 
RandomSampler.sample (bqm[, num_reads]) 
Give random samples for a binary quadratic model. 
RandomSampler.sample_ising (h, J, **parameters) 
Sample from an Ising model using the implemented sample method. 
RandomSampler.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Simulated Annealing Sampler¶
A reference implementation of a simulated annealing sampler.
neal.sampler.SimulatedAnnealingSampler
is a more performant implementation of simulated annealing you can use for
solving problems.
SimulatedAnnealingSampler.parameters 
Keyword arguments accepted by the sampling methods. 
SimulatedAnnealingSampler.sample (bqm[, …]) 
Sample from lowenergy spin states using simulated annealing. 
SimulatedAnnealingSampler.sample_ising (h, J, …) 
Sample from an Ising model using the implemented sample method. 
SimulatedAnnealingSampler.sample_qubo (Q, …) 
Sample from a QUBO using the implemented sample method. 
Composites¶
The dimod package includes several example composed samplers.
Connected Components Composite¶
A composite that breaks the problem into subproblems corresponding to the connected components of the binary quadratic model graph before sending to its child sampler.

class
ConnectedComponentsComposite
(child_sampler)[source]¶ Composite to decompose a problem to the connected components and solve each.
Connected components of a bqm graph are computed (if not provided), and each subproblem is passed to the child sampler. Returned samples from each child sampler are merged. Only the best solution of each response is pick and merge with others (i.e. this composite returns a single solution).
Parameters: sampler ( dimod.Sampler
) – A dimod samplerExamples
This example uses
ConnectedComponentsComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler finds the connected components and solves each.>>> h = {1: 1.3, 2: 2.3, 3:1.2, 4: 0.5} >>> J = {(1, 4): 0.6, (1, 3): 0.6, (3, 4): 1.0, (2, 3): 1.0} >>> sampler = dimod.ConnectedComponentsComposite(dimod.ExactSolver()) >>> sampleset = sampler.sample_ising(h, J)
ConnectedComponentsComposite.child 
The child sampler. 
ConnectedComponentsComposite.children 
List of child samplers that that are used by this composite. 
ConnectedComponentsComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
ConnectedComponentsComposite.properties 
A dict containing any additional information about the sampler. 
ConnectedComponentsComposite.sample (bqm[, …]) 
Sample from the provided binary quadratic model. 
ConnectedComponentsComposite.sample_ising (h, …) 
Sample from an Ising model using the implemented sample method. 
ConnectedComponentsComposite.sample_qubo (Q, …) 
Sample from a QUBO using the implemented sample method. 
Clip Composite¶
A composite that clips problem variables below and above threshold. if lower and upper bounds is not given it does nothing.

class
ClipComposite
(child_sampler)[source]¶ Composite to clip variables of a problem
Clips the variables of a bqm and modifies linear and quadratic terms accordingly.
Parameters: sampler ( dimod.Sampler
) – A dimod samplerExamples
This example uses
ClipComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler clips linear and quadratic biases as indicated by options.>>> h = {'a': 4.0, 'b': 4.0} >>> J = {('a', 'b'): 3.2} >>> sampler = dimod.ClipComposite(dimod.ExactSolver()) >>> response = sampler.sample_ising(h, J, lower_bound=2.0, upper_bound=2.0)
ClipComposite.child 
The child sampler. 
ClipComposite.children 
List of child samplers that that are used by this composite. 
ClipComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
ClipComposite.properties 
A dict containing any additional information about the sampler. 
ClipComposite.sample (bqm[, lower_bound, …]) 
Clip and sample from the provided binary quadratic model. 
ClipComposite.sample_ising (h, J, **parameters) 
Sample from an Ising model using the implemented sample method. 
ClipComposite.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Fixed Variable Composite¶
A composite that fixes the variables provided and removes them from the binary quadratic model before sending to its child sampler.

class
FixedVariableComposite
(child_sampler)[source]¶ Composite to fix variables of a problem to provided.
Fixes variables of a bqm and modifies linear and quadratic terms accordingly. Returned samples include the fixed variable
Parameters: sampler ( dimod.Sampler
) – A dimod samplerExamples
This example uses
FixedVariableComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler fixes a variable and modifies linear and quadratic biases according.>>> h = {1: 1.3, 4: 0.5} >>> J = {(1, 4): 0.6} >>> sampler = dimod.FixedVariableComposite(dimod.ExactSolver()) >>> sampleset = sampler.sample_ising(h, J, fixed_variables={1: 1})
FixedVariableComposite.child 
The child sampler. 
FixedVariableComposite.children 
List of child samplers that that are used by this composite. 
FixedVariableComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
FixedVariableComposite.properties 
A dict containing any additional information about the sampler. 
FixedVariableComposite.sample (bqm[, …]) 
Sample from the provided binary quadratic model. 
FixedVariableComposite.sample_ising (h, J, …) 
Sample from an Ising model using the implemented sample method. 
FixedVariableComposite.sample_qubo (Q, …) 
Sample from a QUBO using the implemented sample method. 
Roof Duality Composite¶
A composite that uses the roof duality algorithm [1] [2] to fix some variables in the binary quadratic model before passing it on to its child sampler.
[1]  Boros, E., P.L. Hammer, G. Tavares. Preprocessing of Unconstrained Quadratic Binary Optimization. Rutcor Research Report 102006, April, 2006. 
[2]  Boros, E., P.L. Hammer. PseudoBoolean optimization. Discrete Applied Mathematics 123, (2002), pp. 155225 

class
RoofDualityComposite
(child_sampler)[source]¶ Uses roof duality to assign some variables before invoking child sampler.
Uses the
fix_variables()
function to determine variable assignments, then fixes them before calling the child sampler. Returned samples include the fixed variables.Parameters: child ( dimod.Sampler
) – A dimod sampler. Used to sample the bqm after variables have been fixed.
RoofDualityComposite.child 
The child sampler. 
RoofDualityComposite.children 
List of child samplers that that are used by this composite. 
RoofDualityComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
RoofDualityComposite.properties 
A dict containing any additional information about the sampler. 
RoofDualityComposite.sample (bqm[, sampling_mode]) 
Sample from the provided binary quadratic model. 
RoofDualityComposite.sample_ising (h, J, …) 
Sample from an Ising model using the implemented sample method. 
RoofDualityComposite.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Scale Composite¶
A composite that scales problem variables as directed. if scalar is not given calculates it based on quadratic and bias ranges.

class
ScaleComposite
(child_sampler)[source]¶ Composite to scale variables of a problem
Scales the variables of a bqm and modifies linear and quadratic terms accordingly.
Parameters: sampler ( dimod.Sampler
) – A dimod samplerExamples
This example uses
ScaleComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler scales linear, quadratic biases and offset as indicated by options.>>> h = {'a': 4.0, 'b': 4.0} >>> J = {('a', 'b'): 3.2} >>> sampler = dimod.ScaleComposite(dimod.ExactSolver()) >>> response = sampler.sample_ising(h, J, scalar=0.5, ... ignored_interactions=[('a','b')])
ScaleComposite.child 
The child sampler. 
ScaleComposite.children 
List of child samplers that that are used by this composite. 
ScaleComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
ScaleComposite.properties 
A dict containing any additional information about the sampler. 
ScaleComposite.sample (bqm[, scalar, …]) 
Scale and sample from the provided binary quadratic model. 
ScaleComposite.sample_ising (h, J[, offset, …]) 
Scale and sample from the problem provided by h, J, offset 
ScaleComposite.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Spin Reversal Transform Composite¶
On the DWave system, coupling \(J_{i,j}\) adds a small bias to qubits \(i\) and \(j\) due to leakage. This can become significant for chained qubits. Additionally, qubits are biased to some small degree in one direction or another. Applying a spinreversal transform can improve results by reducing the impact of possible analog and systematic errors. A spinreversal transform does not alter the Ising problem; the transform simply amounts to reinterpreting spin up as spin down, and visaversa, for a particular spin.

class
SpinReversalTransformComposite
(child)[source]¶ Composite for applying spin reversal transform preprocessing.
Spin reversal transforms (or “gauge transformations”) are applied by flipping the spin of variables in the Ising problem. After sampling the transformed Ising problem, the same bits are flipped in the resulting sample [3].
Parameters: sampler – A dimod sampler object. Examples
This example composes a dimod ExactSolver sampler with spin transforms then uses it to sample an Ising problem.
>>> # Compose the sampler >>> base_sampler = dimod.ExactSolver() >>> composed_sampler = dimod.SpinReversalTransformComposite(base_sampler) >>> base_sampler in composed_sampler.children True >>> # Sample an Ising problem >>> response = composed_sampler.sample_ising({'a': 0.5, 'b': 1.0}, {('a', 'b'): 1}) >>> print(next(response.data())) # doctest: +SKIP Sample(sample={'a': 1, 'b': 1}, energy=1.5)
References
[3] Andrew D. King and Catherine C. McGeoch. Algorithm engineering for a quantum annealing platform. https://arxiv.org/abs/1410.2628, 2014.
SpinReversalTransformComposite.child 
The child sampler. 
SpinReversalTransformComposite.children 

SpinReversalTransformComposite.parameters 

SpinReversalTransformComposite.properties 
SpinReversalTransformComposite.sample (bqm[, …]) 
Sample from the binary quadratic model. 
SpinReversalTransformComposite.sample_ising (h, …) 
Sample from an Ising model using the implemented sample method. 
SpinReversalTransformComposite.sample_qubo (Q, …) 
Sample from a QUBO using the implemented sample method. 
Structured Composite¶
A composite that structures a sampler.

class
StructureComposite
(sampler, nodelist, edgelist)[source]¶ Creates a structured composed sampler from an unstructured sampler.
Parameters: Examples
This example creates a composed sampler from the unstructure dimod ExactSolver sampler. The target structure is a square graph.
>>> import dimod ... >>> base_sampler = dimod.ExactSolver() >>> node_list = [0, 1, 2, 3] >>> edge_list = [(0, 1), (1, 2), (2, 3), (0, 3)] >>> structured_sampler = dimod.StructureComposite(base_sampler, node_list, edge_list) >>> linear = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0} >>> quadratic = {(0, 1): 1.0, (1, 2): 1.0, (0, 3): 1.0, (2, 3): 1.0} >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 1.0, dimod.Vartype.SPIN) >>> response = structured_sampler.sample(bqm) >>> print(next(response.data())) Sample(sample={0: 1, 1: 1, 2: 1, 3: 1}, energy=1.0, num_occurrences=1) >>> # Try giving the composed sampler a nonsquare model >>> del quadratic[(0, 1)] >>> quadratic[(0, 2)] = 1.0 >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 1.0, dimod.Vartype.SPIN) >>> try: response = structured_sampler.sample(bqm) # doctest: +SKIP ... except dimod.BinaryQuadraticModelStructureError as details: ... print(details) ... given bqm does not match the sampler's structure
StructureComposite.child 
The child sampler. 
StructureComposite.children 

StructureComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
StructureComposite.properties 
A dict containing any additional information about the sampler. 
StructureComposite.sample (bqm, **sample_kwargs) 
Sample from the binary quadratic model. 
StructureComposite.sample_ising (h, J, …) 
Sample from an Ising model using the implemented sample method. 
StructureComposite.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Tracking Composite¶
A composite that tracks inputs and outputs.

class
TrackingComposite
(child, copy=False)[source]¶ Composite that tracks inputs and outputs for debugging and testing.
Parameters:  child (
dimod.Sampler
) – A dimod sampler.  copy (bool, optional, default=False) – If True, the inputs/outputs are copied (with
copy.deepcopy()
) before they are stored. This is useful if the child sampler mutates the values.
Examples
>>> sampler = dimod.TrackingComposite(dimod.RandomSampler()) >>> sampleset = sampler.sample_ising({'a': 1}, {('a', 'b'): 1}, ... num_reads=5) >>> sampler.input OrderedDict([('h', {'a': 1}), ('J', {('a', 'b'): 1}), ('num_reads', 5)]) >>> sampleset == sampler.output True
If we make additional calls to the sampler, the most recent input/output are stored in
input
andoutput
respectively. However, all are tracked ininputs
andoutputs
.>>> sampleset = sampler.sample_qubo({('a', 'b'): 1}) >>> sampler.input OrderedDict([('Q', {('a', 'b'): 1})]) >>> sampler.inputs # doctest: +SKIP [OrderedDict([('h', {'a': 1}), ('J', {('a', 'b'): 1}), ('num_reads', 5)]), OrderedDict([('Q', {('a', 'b'): 1})])]
In the case that you want to nest the tracking composite, there are two patterns for retrieving the data
>>> from dimod import ScaleComposite, TrackingComposite, ExactSolver ... >>> sampler = ScaleComposite(TrackingComposite(ExactSolver())) >>> sampler.child.inputs # empty because we haven't called sample []
>>> intermediate_sampler = TrackingComposite(ExactSolver()) >>> sampler = ScaleComposite(intermediate_sampler) >>> intermediate_sampler.inputs []
 child (
TrackingComposite.input 
The most recent input to any sampling method. 
TrackingComposite.inputs 
All of the inputs to any sampling methods. 
TrackingComposite.output 
The most recent output of any sampling method. 
TrackingComposite.outputs 
All of the outputs from any sampling methods. 
TrackingComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
TrackingComposite.properties 
A dict containing any additional information about the sampler. 
TrackingComposite.clear () 
Clear all the inputs/outputs. 
TrackingComposite.sample (bqm, **parameters) 
Sample from the child sampler and store the given inputs/outputs. 
TrackingComposite.sample_ising (h, J, …) 
Sample from the child sampler and store the given inputs/outputs. 
TrackingComposite.sample_qubo (Q, **parameters) 
Sample from the child sampler and store the given inputs/outputs. 
Truncate Composite¶
A composite that truncates the response based on options provided by the user.

class
TruncateComposite
(child_sampler, n, sorted_by='energy', aggregate=False)[source]¶ Composite to truncate the returned samples
Inherits from
dimod.ComposedSampler
.Postprocessing is expensive and sometimes one might want to only treat the lowest energy samples. This composite layer allows one to preselect the samples within a multicomposite pipeline
Parameters:  child_sampler (
dimod.Sampler
) – A dimod sampler  n (int) – Maximum number of rows in the returned sample set.
 sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before truncating. Note that sample order is maintained in the underlying array.
 aggregate (bool, optional, default=False) – If True, aggregate the samples before truncating.
Note
If aggregate is True
SampleSet.record.num_occurrences
are accumulated but no other fields are. child_sampler (
TruncateComposite.child 
The child sampler. 
TruncateComposite.children 
List of child samplers that that are used by this composite. 
TruncateComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
TruncateComposite.properties 
A dict containing any additional information about the sampler. 
TruncateComposite.sample (bqm, **kwargs) 
Sample from the problem provided by bqm and truncate output. 
TruncateComposite.sample_ising (h, J, …) 
Sample from an Ising model using the implemented sample method. 
TruncateComposite.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
HigherOrder Composites¶
The dimod package includes several example higherorder composed samplers.
HigherOrderComposite¶

class
HigherOrderComposite
(child_sampler)[source]¶ Convert a binary quadratic model sampler to a binary polynomial sampler.
Energies of the returned samples do not include the penalties.
Parameters: sampler ( dimod.Sampler
) – A dimod samplerExample
This example uses
HigherOrderComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler creates a bqm from a higher order problem.>>> sampler = dimod.HigherOrderComposite(dimod.ExactSolver()) >>> h = {0: 0.5, 1: 0.3, 2: 0.8} >>> J = {(0, 1, 2): 1.7} >>> sampleset = sampler.sample_hising(h, J, discard_unsatisfied=True) >>> sampleset.first # doctest: +SKIP Sample(sample={0: 1, 1: 1, 2: 1}, energy=3.3, num_occurrences=1, penalty_satisfaction=True)
HigherOrderComposite.child 
The child sampler. 
HigherOrderComposite.children 
A list containing the wrapped sampler. 
HigherOrderComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. 
HigherOrderComposite.properties 
A dict containing any additional information about the sampler. 
HigherOrderComposite.sample_poly (poly[, …]) 
Sample from the given binary polynomial. 
HigherOrderComposite.sample_hising (h, J, …) 
Sample from a higherorder Ising model. 
HigherOrderComposite.sample_hubo (H, **kwargs) 
Sample from a higherorder unconstrained binary optimization problem. 
PolyFixedVariableComposite¶

class
PolyFixedVariableComposite
(child_sampler)[source]¶ Composite to fix variables of a problem to provided.
Fixes variables of a binary polynomial and modifies linear and klocal terms accordingly. Returned samples include the fixed variable
Parameters: sampler ( dimod.PolySampler
) – A dimod polynomial sampler.Examples
This example uses
PolyFixedVariableComposite
to instantiate a composed sampler that submits a simple high order Ising problem to a sampler. The composed sampler fixes a variable and modifies linear and klocal terms biases according.>>> h = {1: 1.3, 2: 1.2, 3: 3.4, 4: 0.5} >>> J = {(1, 4): 0.6, (1, 2, 3): 0.2, (1, 2, 3, 4): 0.1} >>> poly = dimod.BinaryPolynomial.from_hising(h, J, offset=0) >>> sampler = dimod.PolyFixedVariableComposite(dimod.ExactPolySolver()) >>> sampleset = sampler.sample_poly(poly, fixed_variables={3: 1, 4: 1})
PolyFixedVariableComposite.child 
The child sampler. 
PolyFixedVariableComposite.children 
List of child samplers that that are used by this composite. 
PolyFixedVariableComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. 
PolyFixedVariableComposite.properties 
A dict containing any additional information about the sampler. 
PolyFixedVariableComposite.sample_poly (poly) 
Sample from the provided binary quadratic model. 
PolyFixedVariableComposite.sample_hising (h, …) 
Sample from a higherorder Ising model. 
PolyFixedVariableComposite.sample_hubo (H, …) 
Sample from a higherorder unconstrained binary optimization problem. 
PolyScaleComposite¶

class
PolyScaleComposite
(child)[source]¶ Composite to scale biases of a binary polynomial.
Parameters: child ( PolySampler
) – A binary polynomial sampler.Examples
>>> linear = {'a': 4.0, 'b': 4.0} >>> quadratic = {('a', 'b'): 3.2, ('a', 'b', 'c'): 1} >>> sampler = dimod.PolyScaleComposite(dimod.HigherOrderComposite(dimod.ExactSolver())) >>> response = sampler.sample_hising(linear, quadratic, scalar=0.5, ... ignored_terms=[('a','b')])
PolyScaleComposite.child 
The child sampler. 
PolyScaleComposite.children 
The child sampler in a list 
PolyScaleComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. 
PolyScaleComposite.properties 
A dict containing any additional information about the sampler. 
PolyScaleComposite.sample_poly (poly[, …]) 
Scale and sample from the given binary polynomial. 
PolyScaleComposite.sample_hising (h, J, **kwargs) 
Sample from a higherorder Ising model. 
PolyScaleComposite.sample_hubo (H, **kwargs) 
Sample from a higherorder unconstrained binary optimization problem. 
PolyTruncateComposite¶

class
PolyTruncateComposite
(child_sampler, n, sorted_by='energy', aggregate=False)[source]¶ Composite to truncate the returned samples
Postprocessing is expensive and sometimes one might want to only treat the lowest energy samples. This composite layer allows one to preselect the samples within a multicomposite pipeline
Parameters:  child_sampler (
dimod.PolySampler
) – A dimod binary polynomial sampler.  n (int) – Maximum number of rows in the returned sample set.
 sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before truncating. Note that sample order is maintained in the underlying array.
 aggregate (bool, optional, default=False) – If True, aggregate the samples before truncating.
Note
If aggregate is True
SampleSet.record.num_occurrences
are accumulated but no other fields are. child_sampler (
PolyTruncateComposite.child 
The child sampler. 
PolyTruncateComposite.children 
List of child samplers that that are used by this composite. 
PolyTruncateComposite.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. 
PolyTruncateComposite.properties 
A dict containing any additional information about the sampler. 
PolyTruncateComposite.sample_poly (poly, **kwargs) 
Sample from the binary polynomial and truncate output. 
PolyTruncateComposite.sample_hising (h, J, …) 
Sample from a higherorder Ising model. 
PolyTruncateComposite.sample_hubo (H, **kwargs) 
Sample from a higherorder unconstrained binary optimization problem. 
API for Samplers and Composites¶
You can create your own samplers with dimod’s Sampler
abstract base class (ABC)
providing complementary methods (e.g., ‘sample_qubo’ if only ‘sample_ising’ is implemented),
consistent responses, etc.
Properties of dimod Sampler Abstract Base Classes¶
The following table describes the inheritance, properties, methods/mixins of sampler ABCs.
ABC  Inherits from  Abstract Properties  Abstract Methods  Mixins 

Sampler 
parameters , properties 
at least one of
sample() , sample_ising() , sample_qubo() 
sample() , sample_ising() , sample_qubo() 

Structured 
nodelist , edgelist 
structure , adjacency 

Composite 
children 
child 

ComposedSampler 
Sampler , Composite 
parameters , properties , children 
at least one of
sample() , sample_ising() , sample_qubo() 
sample() , sample_ising() , sample_qubo() ,
child 
PolySampler 
parameters , properties 
sample_poly() 
sample_hising() , sample_hubo() 

ComposedPolySampler 
PolySampler , Composite 
parameters , properties , children 
sample_poly() 
sample_hising() , sample_hubo() , child 
The table shows, for example, that the Sampler
class requires that you implement
the parameters
and properties
properties and at least
one sampler method; the class provides the unimplemented methods as mixins.
Creating a Sampler¶
The Sampler
abstract base class (see abc
) helps you create new
dimod samplers.
Any new dimod sampler must define a subclass of Sampler
that implements
abstract properties parameters
and properties
and one of the abstract methods sample()
, sample_ising()
,
or sample_qubo()
. The Sampler
class provides the complementary
methods as mixins and ensures consistent responses.
For example, the following steps show how to easily create a dimod sampler. It is
sufficient to implement a single method (in this example the sample_ising()
method)
to create a dimod sampler with the Sampler
class.
class LinearIsingSampler(dimod.Sampler):
def sample_ising(self, h, J):
sample = linear_ising(h, J)
energy = dimod.ising_energy(sample, h, J)
return dimod.SampleSet.from_samples([sample], energy=[energy]})
@property
def properties(self):
return dict()
@property
def parameters(self):
return dict()
For this example, the implemented sampler sample_ising()
can be based on
a simple placeholder function, which returns a sample that minimizes the linear terms:
def linear_ising(h, J):
sample = {}
for v in h:
if h[v] < 0:
sample[v] = +1
else:
sample[v] = 1
return sample
The Sampler
ABC provides the other sample methods “for free”
as mixins.
sampler = LinearIsingSampler()
response = sampler.sample_ising({'a': 1}, {}) # Implemented by class LinearIsingSampler
response = sampler.sample_qubo({('a', 'a'): 1}) # Mixin provided by Sampler class
response = sampler.sample(BinaryQuadraticModel.from_ising({'a': 1}, {})) # Mixin provided by Sampler class
Below is a more complex version of the same sampler, where the properties
and
parameters
properties return nonempty dicts.
class FancyLinearIsingSampler(dimod.Sampler):
def __init__(self):
self._properties = {'description': 'a simple sampler that only considers the linear terms'}
self._parameters = {'verbose': []}
def sample_ising(self, h, J, verbose=False):
sample = linear_ising(h, J)
energy = dimod.ising_energy(sample, h, J)
if verbose:
print(sample)
return dimod.SampleSet.from_samples([sample], energy=[energy]})
@property
def properties(self):
return self._properties
@property
def parameters(self):
return self._parameters

class
Sampler
[source]¶ Abstract base class for dimod samplers.
Provides all methods
sample()
,sample_ising()
,sample_qubo()
assuming at least one is implemented.
Sampler.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. 
Sampler.properties 
A dict containing any additional information about the sampler. 
Sampler.sample (bqm, **parameters) 
Sample from a binary quadratic model. 
Sampler.sample_ising (h, J, **parameters) 
Sample from an Ising model using the implemented sample method. 
Sampler.sample_qubo (Q, **parameters) 
Sample from a QUBO using the implemented sample method. 
Creating a Composed Sampler¶
Samplers can be composed. The composite pattern allows layers of pre and postprocessing to be applied to binary quadratic programs without needing to change the underlying sampler implementation.
We refer to these layers as composites. Each composed sampler must include at least one sampler, and possibly many composites.
Each composed sampler is itself a dimod sampler with all of the included methods and parameters. In this way complex samplers can be constructed.
The dimod ComposedSampler
abstract base class inherits from Sampler
class
its abstract methods, properties, and mixins (for example, a sample_Ising method) and from
Composite
class the children property and child mixin (children being a list of
supported samplers with child providing the first).
Examples
The dimod package’s spin_transform.py reference example creates a composed sampler, SpinReversalTransformComposite(Sampler, Composite), that performs spin reversal transforms (“gauge transformations”) as a preprocessing step for a given sampler. The reference example implements the pseudocode below:
class SpinReversalTransformComposite(Sampler, Composite):
# Updates to inherited sampler properties and parameters
# Definition of the composite's children (i.e., supported samplers):
children = None
def __init__(self, child):
self.children = [child]
# The composite's implementation of spintransformation functionality:
def sample(self, bqm, num_spin_reversal_transforms=2, spin_reversal_variables=None, **kwargs):
response = None
# Preprocessing code that includes instantiation of a sampler:
# flipped_response = self.child.sample(bqm, **kwargs)
return response
Given a sampler, sampler1, the composed sampler is used as any dimod sampler. For example, the composed sampler inherits an Ising sampling method:
>>> composed_sampler = dimod.SpinReversalTransformComposite(sampler1) # doctest: +SKIP
>>> h = {0: 1, 1: 1} # doctest: +SKIP
>>> response = composed_sampler.sample_ising(h, {}) # doctest: +SKIP

class
Composite
[source]¶ Abstract base class for dimod composites.
Provides the
Composite.child
mixin property and defines theComposite.children
abstract property to be implemented. These define the supported samplers for the composed sampler.
Composite.children 
List of child samplers that that are used by this composite. 
Composite.child 
The child sampler. 
Creating a Structured Sampler¶
A structured sampler can only sample from binary quadratic models with a specific graph.
For structured samplers you must implement the nodelist
and edgelist
properties. The Structured
abstract base class
provides access to the structure
and adjacency
properties as well as any method or properties required by the Sampler
abstract
base class. The bqm_structured
decorator verifies that any given binary quadratic
model conforms to the supported structure.
Examples
This simple example shows a structured sampler that can only sample from a binary quadratic model with two variables and one interaction.
class TwoVariablesSampler(dimod.Sampler, dimod.Structured):
@property
def nodelist(self):
return [0, 1]
@property
def edgelist(self):
return [(0, 1)]
@property
def properties(self):
return dict()
@property
def parameters(self):
return dict()
@dimod.decorators.bqm_structured
def sample(self, bqm):
# All bqm's passed in will be a subgraph of the sampler's structure
variable_list = list(bqm.linear)
samples = []
energies = []
for values in itertools.product(bqm.vartype.value, repeat=len(bqm)):
sample = dict(zip(variable_list, values))
samples.append(sample)
energies.append(bqm.energy(sample))
return dimod.SampleSet.from_samples(samples, bqm.Vartype, energies)
return response

class
Structured
[source]¶ The abstract base class for dimod structured samplers.
Provides the
Structured.adjacency
andStructured.structure
properties.Abstract properties
nodelist
andedgelist
must be implemented.
Structured.nodelist 
Nodes/variables allowed by the sampler. 
Structured.edgelist 
Edges/interactions allowed by the sampler in the form [(u, v), …]. 
Structured.adjacency 
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. 
Structured.structure 
Structure of the structured sampler formatted as a namedtuple , Structure(nodelist, edgelist, adjacency), where the 3tuple values are the nodelist , edgelist and adjacency attributes. 
Creating a Binary Polynomial Sampler¶
Samplers that handle binary polynomials: problems with binary variables that are not constrained to quadratic interactions.

class
PolySampler
[source]¶ Sampler that supports binary polynomials.
Binary polynomials are an extension of binary quadratic models that allow higherorder interactions.
PolySampler.parameters 
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. 
PolySampler.properties 
A dict containing any additional information about the sampler. 
PolySampler.sample_poly (polynomial, **kwargs) 
Sample from a higherorder polynomial. 
PolySampler.sample_hising (h, J, **kwargs) 
Sample from a higherorder Ising model. 
PolySampler.sample_hubo (H, **kwargs) 
Sample from a higherorder unconstrained binary optimization problem. 
Creating a Composed Binary Polynomial Sampler¶

class
ComposedPolySampler
[source]¶ Abstract base class for dimod composed polynomial samplers.
Inherits from
PolySampler
andComposite
.
Samples¶
Returned solutions and samples are described under Binary Quadratic Models.
sample_like Objects¶
as_samples (samples_like[, dtype, copy, order]) 
Convert a samples_like object to a NumPy array and list of labels. 
SampleSet¶

class
SampleSet
(record, variables, info, vartype)[source]¶ Samples and any other data returned by dimod samplers.
Parameters:  record (
numpy.recarray
) – A NumPy record array. Must have ‘sample’, ‘energy’ and ‘num_occurrences’ as fields. The ‘sample’ field should be a 2D NumPy array where each row is a sample and each column represents the value of a variable.  variables (iterable) – An iterable of variable labels, corresponding to columns in record.samples.
 info (dict) – Information about the
SampleSet
as a whole, formatted as a dict.  vartype (
Vartype
/str/set) –Variable type for the
SampleSet
. Accepted input values:Vartype.SPIN
,'SPIN'
,{1, 1}
Vartype.BINARY
,'BINARY'
,{0, 1}
Examples
This example creates a SampleSet out of a samples_like object (a NumPy array).
>>> import dimod >>> import numpy as np ... >>> dimod.SampleSet.from_samples(np.ones(5, dtype='int8'), 'BINARY', 0) # doctest: +SKIP SampleSet(rec.array([([1, 1, 1, 1, 1], 0, 1)], ... dtype=[('sample', 'i1', (5,)), ('energy', '<i4'), ('num_occurrences', '<i4')]), ... [0, 1, 2, 3, 4], {}, 'BINARY')
 record (
Properties¶
SampleSet.first 
Sample with the lowestenergy. 
SampleSet.info 
Dict of information about the SampleSet as a whole. 
SampleSet.record 
numpy.recarray containing the samples, energies, number of occurences, and other sample data. 
SampleSet.variables 
VariableIndexView of variable labels. 
SampleSet.vartype 
Vartype of the samples. 
Methods¶
SampleSet.aggregate () 
Create a new SampleSet with repeated samples aggregated. 
SampleSet.append_variables (samples_like[, …]) 
Create a new sampleset with the given variables and values. 
SampleSet.change_vartype (vartype[, …]) 
Return the SampleSet with the given vartype. 
SampleSet.copy () 
Create a shallow copy. 
SampleSet.data ([fields, sorted_by, name, …]) 
Iterate over the data in the SampleSet . 
SampleSet.done () 
Return True if a pending computation is done. 
SampleSet.from_future (future[, result_hook]) 
Construct a SampleSet referencing the result of a future computation. 
SampleSet.from_samples (samples_like, …[, …]) 
Build a SampleSet from raw samples. 
SampleSet.from_samples_bqm (samples_like, …) 
Build a sample set from raw samples and a binary quadratic model. 
SampleSet.from_serializable (obj) 
Deserialize a SampleSet . 
SampleSet.lowest ([rtol, atol]) 
Return a sample set containing the lowestenergy samples. 
SampleSet.resolve () 
Ensure that the sampleset is resolved if constructed from a future. 
SampleSet.relabel_variables (mapping[, inplace]) 
Relabel the variables of a SampleSet according to the specified mapping. 
SampleSet.samples ([n, sorted_by]) 
Return an iterable over the samples. 
SampleSet.slice (*slice_args, **kwargs) 
Create a new sample set with rows sliced according to standard Python slicing syntax. 
SampleSet.to_pandas_dataframe ([sample_column]) 
Convert a sample set to a Pandas DataFrame 
SampleSet.to_serializable ([use_bytes, …]) 
Convert a SampleSet to a serializable object. 
SampleSet.truncate (n[, sorted_by]) 
Create a new sample set with up to n rows. 
Utility Functions¶
concatenate (samplesets[, defaults]) 
Combine sample sets. 
HigherOrder Models¶
Sometimes it is nice to work with problems that are not restricted to quadratic interactions.
Binary Polynomials¶

class
BinaryPolynomial
(poly, vartype)[source]¶ A polynomial with binary variables and realvalued coefficients.
Parameters:  poly (mapping/iterable) – Polynomial as a mapping of form {term: bias, …}, where term is a collection of variables and bias the associated bias. It can also be an iterable of 2tuples (term, bias).
 vartype (
Vartype
/str/set) –Variable type for the binary quadratic model. Accepted input values:
Vartype.SPIN
,'SPIN'
,{1, 1}
Vartype.BINARY
,'BINARY'
,{0, 1}
Examples
Binary polynomials can be constructed in many different ways. The following are all equivalent
>>> poly = dimod.BinaryPolynomial({'a': 1, 'ab': 1}, dimod.SPIN) >>> poly = dimod.BinaryPolynomial({('a',): 1, ('a', 'b'): 1}, dimod.SPIN) >>> poly = dimod.BinaryPolynomial([('a', 1), (('a', 'b'), 1)], dimod.SPIN) >>> poly = dimod.BinaryPolynomial({'a': 1, 'ab': .5, 'ba': .5}, dimod.SPIN)
Binary polynomials act a mutable mappings but the terms can be accessed with any sequence.
>>> poly = dimod.BinaryPolynomial({'a': 1, 'ab': 1}, dimod.BINARY) >>> poly['ab'] 1 >>> poly['ba'] 1 >>> poly[{'a', 'b'}] 1 >>> poly[('a', 'b')] 1 >>> poly['cd'] = 4 >>> poly['dc'] 4
Methods¶
BinaryPolynomial.copy () 
Create a shallow copy. 
BinaryPolynomial.energies (samples_like[, dtype]) 
The energies of the given samples. 
BinaryPolynomial.energy (sample_like[, dtype]) 
The energy of the given sample. 
BinaryPolynomial.from_hising (h, J[, offset]) 
Construct a binary polynomial from a higherorder Ising problem. 
BinaryPolynomial.from_hubo (H[, offset]) 
Construct a binary polynomial from a higherorder unconstrained binary optimization (HUBO) problem. 
BinaryPolynomial.normalize ([bias_range, …]) 
Normalizes the biases of the binary polynomial such that they fall in the provided range(s). 
BinaryPolynomial.relabel_variables (mapping) 
Relabel variables of a binary polynomial as specified by mapping. 
BinaryPolynomial.scale (scalar[, ignored_terms]) 
Multiply the polynomial by the given scalar. 
BinaryPolynomial.to_binary ([copy]) 
Return a binary polynomial over {0, 1} variables. 
BinaryPolynomial.to_hising () 
Construct a higherorder Ising problem from a binary polynomial. 
BinaryPolynomial.to_hubo () 
Construct a higherorder unconstrained binary optimization (HUBO) problem from a binary polynomial. 
BinaryPolynomial.to_spin ([copy]) 
Return a binary polynomial over {1, +1} variables. 
Reducing to a Binary Quadratic Model¶
make_quadratic (poly, strength[, vartype, bqm]) 
Create a binary quadratic model from a higher order polynomial. 
Utilities¶
Contents
Energy Calculations¶
ising_energy (sample, h, J[, offset]) 
Calculate the energy for the specified sample of an Ising model. 
qubo_energy (sample, Q[, offset]) 
Calculate the energy for the specified sample of a QUBO model. 
Decorators¶
Decorators can be imported from the dimod.decorators
namespace. For
example:
>>> from dimod.decorators import vartype_argument
bqm_index_labels (f) 
Decorator to convert a BQM to indexlabels and relabel the sample set output. 
bqm_index_labelled_input (…) 
Returns a decorator that ensures BQM variable labeling and specified sample_like inputs are index labeled and consistent. 
bqm_structured (f) 
Decorator to raise an error if the given BQM does not match the sampler’s structure. 
graph_argument (*arg_names, **options) 
Decorator to coerce given graph arguments into a consistent form. 
vartype_argument (*arg_names) 
Ensures the wrapped function receives valid vartype argument(s). 
Graphlike¶
child_structure_dfs (sampler[, seen]) 
Return the structure of a composed sampler using a depthfirst search on its children. 
Serialization¶
COOrdinate¶
dump (bqm, fp[, vartype_header]) 
Dump a binary quadratic model to a string in COOrdinate format. 
dumps (bqm[, vartype_header]) 
Dump a binary quadratic model to a string in COOrdinate format. 
load (fp[, cls, vartype]) 
Load a COOrdinate formatted binary quadratic model from a file. 
loads (s[, cls, vartype]) 
Load a COOrdinate formatted binary quadratic model from a string. 
JSON¶
JSONencoding of dimod objects.
Examples
>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): 1})
>>> s = json.dumps(bqm, cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> bqm == new
True
>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> sampleset = dimod.SampleSet.from_samples({'a': 1, 'b': 1}, dimod.SPIN, energy=5)
>>> s = json.dumps(sampleset, cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> sampleset == new
True
>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> # now inside a list
>>> s = json.dumps([sampleset, bqm], cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> new == [sampleset, bqm]
True
DimodEncoder (*[, skipkeys, ensure_ascii, …]) 
Subclass the JSONEncoder for dimod objects. 
DimodDecoder (*args, **kwargs) 
Subclass the JSONDecoder for dimod objects. 
dimod_object_hook (obj) 
JSONdecoding for dimod objects. 
Testing¶
The testing subpackage contains functions for verifying and testing dimod
objects. Testing objects/functions can be imported from the dimod.testing
namespace. For example:
>>> from dimod.testing import assert_sampler_api
API Asserts¶
assert_composite_api (composed_sampler) 
Assert that an instantiated composed sampler exposes correct composite properties and methods. 
assert_sampler_api (sampler) 
Assert that an instantiated sampler exposes correct properties and methods. 
assert_structured_api (sampler) 
Assert that an instantiated structured sampler exposes correct composite properties and methods. 
Correctness Asserts¶
assert_bqm_almost_equal (actual, desired[, …]) 
Test if two binary quadratic models have almost equal biases. 
assert_response_energies (response, bqm[, …]) 
Assert that each sample in the given response has the correct energy. 
assert_sampleset_energies (sampleset, bqm[, …]) 
Assert that each sample in the given sample set has the correct energy. 
Test Case Loader¶
load_sampler_bqm_tests (sampler[, …]) 
Populate the decorated TestCase with sampler tests using small BQMs. 
Vartype Conversion¶
ising_to_qubo (h, J[, offset]) 
Convert an Ising problem to a QUBO problem. 
qubo_to_ising (Q[, offset]) 
Convert a QUBO problem to an Ising problem. 
Vartype¶
Enumeration of valid variable types for binary quadratic models.
Examples
Vartype
is an Enum
. Each vartype has a value and
a name.
>>> vartype = dimod.SPIN
>>> vartype.name
'SPIN'
>>> vartype.value == {1, +1}
True
>>> vartype = dimod.BINARY
>>> vartype.name
'BINARY'
>>> vartype.value == {0, 1}
True
The as_vartype()
function allows the user to provide several
convenient forms.
>>> from dimod import as_vartype
>>> as_vartype(dimod.SPIN) is dimod.SPIN
True
>>> as_vartype('SPIN') is dimod.SPIN
True
>>> as_vartype({1, 1}) is dimod.SPIN
True
>>> as_vartype(dimod.BINARY) is dimod.BINARY
True
>>> as_vartype('BINARY') is dimod.BINARY
True
>>> as_vartype({0, 1}) is dimod.BINARY
True