
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/QUBO_Solver.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_QUBO_Solver.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_QUBO_Solver.py:


Example of using the QUBO solver on a pool of small random instances.
=====================================================================

.. GENERATED FROM PYTHON SOURCE LINES 15-87

.. code-block:: Python


    # pylint: disable=invalid-name

    import numpy as np

    from qtealeaves.optimization import QUBOConvergenceParameters, QUBOSolver


    def main(qubo_size: int | None = 8, n_instances: int | None = 10) -> None:
        """Example of a QUBO solver routine on random instances."""

        # Create a small pool of small random (integer) QUBO problems
        np.random.seed(11)
        qubo_problems = [
            np.random.randint(-50, 50, (qubo_size, qubo_size)) for _ in range(n_instances)
        ]
        qubo_problems = [qubo + qubo.T for qubo in qubo_problems]

        # Solve the QUBOs and benchmarking with brute-force
        print("\n\n")
        separator = "-" * 60
        for jj, qprob in enumerate(qubo_problems):
            my_solver = QUBOSolver(qprob)
            print(separator)
            print(f"Solving QUBO problem instance n° {jj + 1}......")

            ## Brute-force for benchmarking
            my_solver.solve("brute-force")
            bf_config = my_solver.best_config
            bf_cost = my_solver.best_cost

            print(
                f"  Brute-force solution in {my_solver.runtimes['time-to-solution']:.2f} s"
            )
            print(f"\t Cost --> {bf_cost}")
            print(f"\t Solution --> {bf_config}")

            ## Tensor-network based solver:
            ## define user's parameters for solving the QUBO
            my_conv_params = QUBOConvergenceParameters(
                max_bond_dimension=8,
                tn_ansatz="MPS",  # can be 'TTN'
                data_type="D",
                max_iter=10,
                transverse_field_ratio=1e9,
                tn_io_tag=f"{jj + 1}",
                # the two following parameters automatically define
                # the tensor backend from qtaleaves and / or redtea
                linalg_backend_library="numpy",  # Can be 'torch'
                device="cpu",  # can be 'gpu'
            )

            ## Tensor-network based solver:
            ## call the TN-based solver
            my_solver.solve(tn_conv_params=my_conv_params)

            ## Tensor-network based solver:
            ## process results
            print(
                f"  Tensor-network solution in {my_solver.runtimes['time-to-solution']:.2f} s"
            )
            print(f"\t Cost --> {my_solver.best_cost}")
            print(f"\t Solution --> {my_solver.best_config}")
            print(f"Solving QUBO problem instance n° {jj + 1}......done")
            print(separator, "\n\n")

        # Output
        print(f"\nExample `{__file__}` ran successfully; no asserts implemented.")


    if __name__ == "__main__":
        main()


.. _sphx_glr_download_auto_examples_QUBO_Solver.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: QUBO_Solver.ipynb <QUBO_Solver.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: QUBO_Solver.py <QUBO_Solver.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: QUBO_Solver.zip <QUBO_Solver.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
