Metadata-Version: 2.1
Name: dwave-samplers
Version: 1.8.0
Summary: Ocean-compatible collection of solvers/samplers.
Author-Email: D-Wave <tools@dwavesys.com>
License:                                  Apache License
         
                                    Version 2.0, January 2004
                                    
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. 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, non-exclusive, no-charge, royalty-free, 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, non-exclusive, no-charge, royalty-free, 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
               cross-claim 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 third-party 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, NON-INFRINGEMENT, 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 third-party 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/LICENSE-2.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.
         
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Operating System :: Unix
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: Implementation :: CPython
Project-URL: Changelog, https://github.com/dwavesystems/dwave-samplers/releases
Project-URL: Documentation, https://docs.dwavequantum.com
Project-URL: Source Code, https://github.com/dwavesystems/dwave-samplers
Requires-Python: >=3.10
Requires-Dist: dimod<0.13.0,>=0.12.21
Requires-Dist: networkx<4,>=3
Requires-Dist: numpy<3.0.0,>=1.21.6
Description-Content-Type: text/x-rst

.. image:: https://img.shields.io/pypi/v/dwave-samplers.svg
    :target: https://pypi.python.org/pypi/dwave-samplers

.. image:: https://img.shields.io/pypi/pyversions/dwave-samplers.svg
    :target: https://pypi.python.org/pypi/dwave-samplers

.. image:: https://circleci.com/gh/dwavesystems/dwave-samplers.svg?style=svg
    :target: https://circleci.com/gh/dwavesystems/dwave-samplers


==============
dwave-samplers
==============

.. start_samplers_about

Ocean software provides a variety of quantum, classical, and quantum-classical
hybrid `dimod <https://docs.dwavequantum.com/en/latest/ocean/api_ref_dimod>`_
`samplers <https://docs.dwavequantum.com/en/latest/concepts/samplers.html>`_
that run either remotely (for example, in the
`Leap <https://cloud.dwavesys.com/leap/>`_ service) or locally on your CPU.

Supported Samplers
==================

*dwave-samplers* implements the following
`classical <https://docs.dwavequantum.com/en/latest/quantum_research/classical_intro.html>`_
algorithms for solving
`binary quadratic models <https://docs.dwavequantum.com/en/latest/concepts/models.html>`_
(BQM):

*   `Planar`_: an exact solver for planar Ising problems with no linear biases.
*   `Random`_: a sampler that draws uniform random samples.
*   `Simulated Annealing`_: a probabilistic heuristic for optimization and
    approximate Boltzmann sampling well suited to finding good solutions of
    large problems.
*   `Simulated Quantum Annealing`_: a heuristic for optimization or approximate
    sampling.
*   `Steepest Descent`_: a discrete analogue of gradient descent, often used in
    machine learning, that quickly finds a local minimum.
*   `Tabu`_: a heuristic that employs local search with methods to escape local
    minima.
*   `Tree Decomposition`_: an exact solver for problems with low treewidth.

Planar
------

There are polynomial-time algorithms for finding the ground state of a planar
Ising model [#]_.

.. [#] Nicol Schraudolph, Dmitry Kamenetsky. *Efficient Exact Inference in
    Planar Ising Models*.
    Advances in Neural Information Processing Systems 21 (NIPS 2008).

>>> from dwave.samplers import PlanarGraphSolver
>>> solver = PlanarGraphSolver()

Get the ground state of a planar Ising model

>>> h = {}
>>> J = {(0, 1): -1, (1, 2): -1, (0, 2): 1}

>>> sampleset = solver.sample_ising(h, J)

Random
------

Random samplers provide a useful baseline performance comparison. The variable
assignments in each sample are chosen by a coin flip.

>>> from dwave.samplers import RandomSampler
>>> sampler = RandomSampler()

Create a random binary quadratic model.

>>> import dimod
>>> bqm = dimod.generators.gnp_random_bqm(100, .5, 'BINARY')

Get the best 5 sample found in .1 seconds.

>>> sampleset = sampler.sample(bqm, time_limit=.1, max_num_samples=5)
>>> num_reads = sampleset.info['num_reads']  # the total number of samples generated

Simulated Annealing
-------------------

`Simulated annealing <https://en.wikipedia.org/wiki/Simulated_annealing>`__ can
be used for heuristic optimization or approximate Boltzmann sampling. The
*dwave-samplers* implementation approaches the equilibrium distribution by
performing updates at a sequence of decreasing temperatures, terminating at the
target `β`.\ [#]_ Each spin is updated once in a fixed (by default) or
randomized order per point per temperature according to a customizable (by default
Metropolis-Hastings) update. When the temperature
is low the target distribution concentrates, at equilibrium, over ground states
of the model. Samples are guaranteed to match the equilibrium for long, smooth
temperature schedules. Schedules are customizable so that the sampler can be used
for standard Metropolis, Gibbs, Block-Gibbs or reverse annealing dynamics.

.. [#] `β` represents the inverse temperature, `1/(k T)`, of a
    `Boltzmann distribution <https://en.wikipedia.org/wiki/Boltzmann_distribution>`_
    where `T` is the thermodynamic temperature in kelvin and `k` is Boltzmann's
    constant.

>>> from dwave.samplers import SimulatedAnnealingSampler
>>> sampler = SimulatedAnnealingSampler()

Create a random binary quadratic model.

>>> import dimod
>>> bqm = dimod.generators.gnp_random_bqm(100, .5, 'BINARY')

Sample using simulated annealing with both the default temperature schedule
and a custom one.

>>> sampleset = sampler.sample(bqm)
>>> sampleset = sampler.sample(bqm, beta_range=[.1, 4.2], beta_schedule_type='linear')

Simulated Quantum Annealing
---------------------------

Simulated quantum annealing can be used for heuristic optimization or approximate
sampling. The *dwave-samplers* implementation performs dynamics defined by a schedule
for the driver(transverse) and problem(diagonal, binary quadratic model) Hamiltonian terms.
Each spin is updated according to a model-appropriate update as the schedule is
stepped through in discretized time (by sweep).
Using these methods equilibrated (thermalized) quantum Boltzmann distributions can be
approached, or the QPU schedule can be provided to simulate by classical dynamics
the annealing process. Although out-of-equilibrium dynamics and dynamical timescales
cannot be simulated by these classical methods, some phenomena can be emulated beyond
what is possible with simulated annealing. For algorithm details see [1]

[1] https://doi.org/10.1038/s41467-021-20901-5

>>> from dwave.samplers import PathIntegralAnnealingSampler
>>> sampler = PathIntegralAnnealingSampler()  # or RotorModelAnnealingSampler()

Create a random binary quadratic model.

>>> import dimod
>>> bqm = dimod.generators.gnp_random_bqm(100, .5, 'BINARY')

Sample projected states from a quantum process with a linear schedule

>>> sampleset = sampler.sample(bqm, beta_schedule_type="custom", Hp_field=[0, 10],  Hd_field=[10, 0])


Steepest Descent
----------------

`Steepest descent <https://en.wikipedia.org/wiki/Gradient_descent>`__ is the
discrete analogue of gradient descent, but the best move is computed using a
local minimization rather rather than computing a gradient. The dimension along
which to descend is determined, at each step, by the variable flip that causes
the greatest reduction in energy.

Steepest descent is fast and effective for unfrustrated problems, but it can get
stuck in local minima.

The quadratic unconstrained binary optimization (QUBO)
`E(x, y) = x + y - 2.5 * x * y`, for example, has two local minima:
`(0, 0)` with an energy of `0` and `(1, 1)` with an energy of `-0.5`.

>>> from dwave.samplers import SteepestDescentSolver
>>> solver = SteepestDescentSolver()

Construct the QUBO:

>>> from dimod import Binaries
>>> x, y = Binaries(['x', 'y'])
>>> qubo = x + y - 2.5 * x * y

If the solver starts uphill from the global minimum, it takes the steepest path
and finds the optimal solution.

>>> sampleset = solver.sample(qubo, initial_states={'x': 0, 'y': 1})
>>> print(sampleset)
   x  y energy num_oc. num_st.
0  1  1   -0.5       1       1
['BINARY', 1 rows, 1 samples, 2 variables]

If the solver starts in a local minimum, it gets stuck.

>>> sampleset = solver.sample(qubo, initial_states={'x': 0, 'y': 0})
>>> print(sampleset)
   x  y energy num_oc. num_st.
0  0  0    0.0       1       0
['BINARY', 1 rows, 1 samples, 2 variables]

Tabu
----

`Tabu search <https://en.wikipedia.org/wiki/Tabu_search>`_ is a heuristic that
employs local search and can escape local minima by maintaining a "tabu list" of
recently explored states that it does not revisit. The length of this tabu list
is called the "tenure". *dwave-samplers* implements the
`MST2 multistart tabu search algorithm <https://link.springer.com/article/10.1023/B:ANOR.0000039522.58036.68>`_
for quadratic unconstrained binary optimization (QUBO) problems.

Each read of the tabu algorithm consists of many starts. The solver takes the
best non-tabu step repeatedly until it does not improve its energy any more.

>>> from dwave.samplers import TabuSampler
>>> sampler = TabuSampler()

Construct a simple problem.

>>> from dimod import Binaries
>>> a, b = Binaries(['a', 'b'])
>>> qubo = -.5 * a + b - a * b

Sample using both default and custom values of tenure and number of restarts.

>>> sampleset0 = sampler.sample(qubo)
>>> sampleset1 = sampler.sample(qubo, tenure=1, num_restarts=1)

Tree Decomposition
------------------

`Tree decomposition <https://en.wikipedia.org/wiki/Tree_decomposition>`__-based
solvers have a runtime that is exponential in the
`treewidth <https://en.wikipedia.org/wiki/Treewidth>`_ of the problem graph. For
problems with low treewidth, the solver can find ground states very quickly.
However, for even moderately dense problems, performance is very poor.

>>> from dwave.samplers import TreeDecompositionSolver
>>> solver = TreeDecompositionSolver()

Construct a large, tree-shaped problem.

>>> import dimod
>>> import networkx as nx
>>> tree = nx.balanced_tree(2, 5)  # binary tree with a height of five
>>> bqm = dimod.BinaryQuadraticModel('SPIN')
>>> bqm.set_linear(0, .5)
>>> for u, v in tree.edges:
...     bqm.set_quadratic(u, v, 1)

Because the BQM is a binary tree, it has a treewidth of 1 and can be solved
exactly.

>>> sampleset = solver.sample(bqm)
>>> print(sampleset)
   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 ... 62 energy num_oc.
0 -1 +1 +1 -1 -1 -1 -1 +1 +1 +1 +1 +1 +1 +1 +1 -1 -1 -1 ... +1  -62.5       1
['SPIN', 1 rows, 1 samples, 63 variables]

.. end_samplers_about

Installation
============

To install the core package:

.. code-block:: bash

    pip install dwave-samplers

During package development, it is often convenient to use an editable install.
See `meson-python's editable installs
<https://meson-python.readthedocs.io/en/latest/how-to-guides/editable-installs.html>`_
for more details.

.. code-block:: bash

    pip install --group dev
    pip install --editable . \
        --no-build-isolation \
        --config-settings=editable-verbose=true

To run the C++ tests, first install the project dependencies, then setup a
``meson`` build directory. You must configure the build as a debug build for
the tests to run.

.. code-block:: bash

    pip install --group dev
    meson setup build -Dbuildtype=debug

You can then run the tests using
`meson's test framework <https://mesonbuild.com/Unit-tests.html>`_.

.. code-block:: bash

    meson test -Cbuild
