
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/SpinGlass_1d_groundstate.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_SpinGlass_1d_groundstate.py>`
        to download the full example code.

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

.. _sphx_glr_auto_examples_SpinGlass_1d_groundstate.py:


Ground state simulation of a spin-glass model.
==============================================

Example contains the ground state of the spin-glass, conversion from TTN to MPS,
and sampling.

.. GENERATED FROM PYTHON SOURCE LINES 19-142

.. code-block:: Python


    # pylint: disable=invalid-name

    import os

    import matplotlib.pyplot as plt
    import numpy as np

    import qtealeaves as qtl
    import qtealeaves.emulator as qtltn
    from qtealeaves import modeling


    # pylint: disable-next=too-many-locals
    def main(tn_type=5, output_folder=None, plot=True):
        """
        Main method for the ground state simulation of 1d spin glass model. Spin
        glass models usually do not conserve any symmetry.

        **Arguments**

        tn_type : int, optional
            Choose 5 for python-TTN, 6 for python-MPS.
            Default to 5.

        output_folder : str | None, optional
            Output folder. Default to None.

        plot : bool, optional
            If True, plot the results at the end of the example. Default tot True
        """
        # Set seed for random number generator
        np.random.seed([11, 13, 17, 19])

        # For the spin glass, we have to fix the system size in the moment
        system_sizes = [8]
        get_xrand = lambda params: np.random.rand(params["L"], params["L"])
        get_zrand = lambda params: np.random.rand(params["L"])

        if output_folder is None:
            output_folder = lambda params: "SG1d_%03d" % (params["L"])
            ttn_file = lambda params: "SG1d/ttn_gs_%03d" % (params["L"])
        else:
            ttn_file = lambda params: os.path.join(
                output_folder, "ttn_gs_%03d" % (params["L"])
            )

        model = modeling.QuantumModel(1, "L", name="SpinGlass")
        model += modeling.RandomizedLocalTerm("sz", get_zrand)
        model += modeling.TwoBodyAllToAllTerm1D(["sx", "sx"], get_xrand)

        my_conv = qtl.convergence_parameters.TNConvergenceParameters(
            max_iter=7, max_bond_dimension=20
        )
        my_ops = qtl.operators.TNSpin12Operators()

        my_obs = qtl.observables.TNObservables()
        my_obs += qtl.observables.State2File(ttn_file, "F")

        simulation = qtl.QuantumGreenTeaSimulation(
            model,
            my_ops,
            my_conv,
            my_obs,
            tn_type=tn_type,
            folder_name_output=output_folder,
            has_log_file=False,
            store_checkpoints=False,
        )

        params = []
        for system_size in system_sizes:
            params.append({"L": system_size})

        simulation.run(params, delete_existing_folder=True)

        mps_conv_params = qtl.convergence_parameters.TNConvergenceParameters(
            max_bond_dimension=16
        )

        for elem in params:
            ttn_filename = simulation.get_static_obs(elem)[ttn_file(elem)]
            psi_ttn = qtltn.TTN.read(ttn_filename, qtl.tensors.TensorBackend())
            psi_mps = qtltn.MPS.from_tensor_list(
                psi_ttn.to_mps_tensor_list(conv_params=mps_conv_params)[0],
                conv_params=mps_conv_params,
            )

            nsamples = 10
            bound_probabilities = psi_mps.meas_unbiased_probabilities(nsamples)

            if plot:
                fig = plt.figure()
                ax1 = fig.add_subplot(111)

                accumulated = 0.0
                for sample, bounds in bound_probabilities.items():
                    accumulated += bounds[1] - bounds[0]
                    ax1.fill_between(bounds, [0, 0], [1, 1], label=sample)

                ax1.set_ylim([0, 4])
                ax1.set_xlabel("Probability interval")
                ax1.set_yticks([])
                fig.legend(loc="center", ncol=3)
                plt.savefig("SG1d/samples_L%03d.pdf" % (elem["L"]))

                print(
                    "Accumulated probability of %d" % (len(bound_probabilities))
                    + " samples: %2.6f" % (accumulated)
                    + " (L=%d)" % (elem["L"])
                )

        print(
            f"\nExample `{__file__}` ran successfully; "
            + "pdf-plots are saved to SG1d folder; "
            + "no asserts implemented."
        )

        return


    if __name__ == "__main__":
        main()


.. _sphx_glr_download_auto_examples_SpinGlass_1d_groundstate.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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