Example #1
0
def main(PostProcess=False, ShowPlots=True, Persistent=False, pdim=0, L=30):
    """
    Introductory example for openMPS to simulate the finite size statics of
    the transverse Ising model. Two modes are available when running the
    example from command line:

    * ``python IsingStatics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics of the Ising model. (default if
      ``--PostProcess`` not present.)
    * ``python IsingStatics.py --PostProcess=T`` : plotting the results of the
      simulation run before.
    * The option ``--ShowPlots=T`` (``--ShowPlots=F``) lets you turn on (off)
      the GUI windows with the plots. Default to on if not passed to the
      command line.
    """

    # Build spin operators for spin-1/2 system
    # Transform to perserve Z2 symmetry
    Operators = mps.BuildSpinOperators(0.5)
    Operators['sigmax'] = 2 * Operators['sz']
    Operators['sigmaz'] = (Operators['splus'] + Operators['sminus'])
    Operators['gen'] = np.array([[0, 0], [0, 1.]])
    # Define Hamiltonian of transverse Ising model
    H = mps.MPO(Operators)
    # Note the J parameter in the transverse Ising Hamiltonian
    # has been set to 1, we are modelling a ferromagnetic chain.
    H.AddMPOTerm('bond', ['sigmaz', 'sigmaz'], hparam='J', weight=-1.0)
    H.AddMPOTerm('site', 'sigmax', hparam='g', weight=-1.0)

    # Observables and convergence parameters
    myObservables = mps.Observables(Operators)
    #myObservables.AddObservable('corr', ['sigmaz', 'sigmaz'], 'zz')
    #myObservables.AddObservable('DensityMatrix_i', [])
    #myObservables.AddObservable('DensityMatrix_ij', [])
    myObservables.AddObservable('MI', True)
    myConv = mps.MPSConvParam(max_bond_dimension=200,
                              variance_tol=1E-10,
                              local_tol=1E-10,
                              max_num_sweeps=6)
    #modparam = ['max_bond_dimension', 'max_num_sweeps']
    #myConv.AddModifiedConvergenceParameters(0, modparam, [80, 4])

    # Specify constants and parameter lists
    J = 1.0
    glist = np.linspace(0.1, 2.1, 41)
    parameters = []

    for g in glist:
        parameters.append({
            'simtype':
            'Finite',
            # Directories
            'job_ID':
            'Ising_Statics',
            'unique_ID':
            'g_' + str(g),
            'Write_Directory':
            'TMP_ISING_01_L_{}/'.format(L),
            'Output_Directory':
            'OUTPUTS_ISING_01_L_{}/'.format(L),
            # System size and Hamiltonian parameters
            'L':
            L,
            'J':
            J,
            'g':
            g,
            # ObservablesConvergence parameters
            'verbose':
            1,
            'MPSObservables':
            myObservables,
            'MPSConvergenceParameters':
            myConv,
            'logfile':
            True,
            # Z2 symmetry
            'Discrete_generators': ['gen'],
            'Discrete_quantum_numbers': [0]
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if we are not just Post
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # PostProcess
    # -----------
    dmat_list = []
    MI_list = []
    Outputs = mps.ReadStaticObservables(parameters)
    for Output in Outputs:
        print(Output['converged'])
        if Persistent:
            netmeasures = nm.pearson(Output['MI'])
            dist = 1.0 - np.abs(netmeasures[0])
            for i in range(L):
                dist[i, i] = 0.0
            dmat_list.append(dist)
        MI_list.append(Output['MI'][3][26])
    plt.style.use('seaborn-colorblind')
    #plt.style.use('seaborn-whitegrid')
    plt.rc('font', family='serif')
    plt.rc('mathtext', fontset='cm')

    timestamp = int(time.time() * 1000.0)

    if (not Persistent):
        plt.scatter(glist, MI_list)
        plt.xlabel(r"transverse field coupling  " r"$g$", fontsize=16)
        plt.ylabel(r"Mutual information (4,27)", fontsize=16)
        plt.savefig('MI_L_{}_{}.pdf'.format(L, timestamp), bbox_inches='tight')
        plt.show()
        return

    npent_list, pent_list, pnorm_list = ph.compute_ph(
        out_path='./diagrams_{}_{}'.format(L, timestamp),
        fig_path='./figs_{}_{}'.format(L, timestamp),
        basename='ising',
        dmat_list=dmat_list,
        plot=True,
        pdim=pdim)

    # Save txt
    np.savetxt('stats_L_{}_{}.txt'.format(L, timestamp),
               list(zip(glist, npent_list, pent_list, pnorm_list)),
               fmt='%.18g')

    # Plot
    fig, ax1 = plt.subplots()
    ax1.scatter(glist, pnorm_list, c='red')
    ax1.set_xlabel(r"transverse field coupling  " r"$g$", fontsize=16)
    ax1.set_ylabel(r"p-norm persistence", fontsize=16)
    ax2 = ax1.twinx()
    ax2.set_ylabel('normalize persistent entropy', fontsize=16)
    ax2.scatter(glist, npent_list, c='blue')
    #plt.xlim((0, 2))
    #plt.ylim((0, 1))
    if (ShowPlots):
        plt.savefig('IsingStatic_L_{}_ph_dim_{}_{}.pdf'.format(
            L, pdim, timestamp),
                    bbox_inches='tight')
        plt.show()

    return
def main(PostProcess=False, muvals=50, tvals=50):
    """
    Simulation of an infinite HC dipolar model executed with MPI as data
    parallel simulation.

    **Arguments**

    PostProcess : boolean, optional
        ``False`` means we are running a simulation and so write files and a
        pbs script. ``True`` means we are just postprocessing a simulation,
        and so only generate the internal data we need for extracting
        observables.
    """

    # Build operators
    Operators = mps.BuildBoseOperators(1)

    # Define Hamiltonian MPO
    H = mps.MPO(Operators, PostProcess=PostProcess)
    H.AddMPOTerm('site', 'nbtotal', hparam='mu', weight=-1.0)
    H.AddMPOTerm('bond', ['bdagger', 'b'], hparam='t', weight=-1.0)
    invrcube = lambda x : 1.0 / (x**3)
    H.AddMPOTerm('InfiniteFunction', ['nbtotal','nbtotal'], hparam='U',
                 weight=1.0, func=invrcube, L=1000, tol=1e-9)
    H.printMPO()

    # ground state observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'nbtotal', 'n')
    # correlation functions
    myObservables.AddObservable('corr', ['nbtotal', 'nbtotal'], 'nn')
    myObservables.AddObservable('corr', ['bdagger', 'b'], 'spdm')
    # Get correlation functions out to a distance of 1000
    myObservables.SpecifyCorrelationRange(1000)

    # Convergence setup
    bond_dimensions = [12, 16, 20, 32]
    myConv = mps.iMPSConvParam(max_bond_dimension=bond_dimensions[0],
                               variance_tol=-1.0, max_num_imps_iter=1000)
    for ii in range(1, len(bond_dimensions)):
        myConv.AddModifiedConvergenceParameters(0, ['max_bond_dimension',
                                                    'max_num_imps_iter'],
                                                [bond_dimensions[ii], 500])

    L = 2
    U = 1.0
    mumin = 0.5
    mumax = 1.8
    muiter = np.linspace(mumin, mumax, muvals)

    tmin = 0.01
    tmax = 0.4
    titer = np.linspace(tmin, tmax, tvals)

    parameters = []

    for ii in range(muiter.shape[0]):
        mu = muiter[ii]

        for jj in range(titer.shape[0]):
            tt = titer[jj]

            parameters.append({
                'simtype'                   : 'Infinite',
                # Directories
                'job_ID'                    : 'HCDipolar',
                'unique_ID'                 : '_mu%2.4f_t%2.4f'%(mu, tt),
                'Write_Directory'           : 'TMP_09/',
                'Output_Directory'          : 'OUTPUTS_09/',
                # System size and Hamiltonian parameters
                'L'                         : L,
                'U'                         : U,
                'mu' : mu,
                't' : tt,
                #Convergence parameters
                'MPSObservables'            : myObservables,
                'MPSConvergenceParameters'  : myConv,
                'logfile'                   : True
            })

    comp_info = {
        'queueing' : 'slurm',
        'time' : '12:00:00',
        'nodes' : ['128'],
        'mpi' : 'srun',
        'ThisFileName' : os.path.abspath( __file__ )
    }

    MainFiles = mps.WriteMPSParallelFiles(parameters,
                                          Operators, H, comp_info,
                                          PostProcess=PostProcess)

    ## For serial a run as comparison
    # MainFiles = mps.WriteFiles(parameters, Operators, H,
    #                           PostProcess=PostProcess)
    # if(not PostProcess):
    #     if os.path.isfile('./Execute_MPSMain'):
    #         RunDir = './'
    #     else:
    #         RunDir = None
    #     mps.runMPS(MainFiles, RunDir=RunDir)
    #     return

    if(PostProcess):
        # extract observables
        Outputs = mps.ReadStaticObservables(parameters)

        # heading for where postprocessing is to be written
        outputstub = 'HCDOut/' + parameters[0]['job_ID']
        if(not os.path.isdir('./HCDOut')): os.makedirs('./HCDOut')

        scalarfilenames = []
        scalarfile = []
        i = 0

        # create a scalar file and file name for each \chi
        for chi in bond_dimensions:
            scalarfilenames.append(outputstub + 'chi' + str(chi) + 'scalar.dat')
            scalarfile.append(open(scalarfilenames[i], 'w+'))
            i += 1

        for Output in Outputs:
            mu = Output['mu']
            t = Output['t']
            if((Output['mu'] == mu) and (Output['t'] == t)):
                # Simulation metadata
                state = Output['state']
                chi = Output['bond_dimension']
                error_code = Output['error_code']
                Number_of_Ground_States = Output['N_Ground_States']
                of = Output['Orthogonality_Fidelity']
                trunc = Output['Truncation_error']
                tolerance = Output['Fixed_Point_Tolerance']
                converged = Output['converged']
                energy_density = Output['energy_density']
                correlation_length = Output['Correlation_length']

                if(error_code != 0):
                    print('Warning! Parameters ' + str(mu) + ' ' + str(t) + ' '
                          + str(state) + ' ' + str(chi) + ' have error code '
                          + str(error_code))
                if(not converged):
                    print('Warning! Parameters ' + str(mu) + ' ' + str(t) + ' '
                          + str(state) + ' ' + str(chi) + ' did not converge ', of,
                          trunc, tolerance)

                # average density of unit cell
                number = Output['n']
                ucdensity = sum(number) / Output['L']
                print('mu t n', mu, t, number, ucdensity)

                # connected correlation function
                raw_nn = Output['nn']
                nn_connected = []

                for ii in range(len(raw_nn)):
                    nn_connected.append(raw_nn[ii] - 0.0 * ucdensity**2)

                # Single-particle density matrix
                spdm = Output['spdm']

                # Scalar quantities
                if(state == 0):
                    sfile = scalarfile[Output['convergence_parameter'] - 1]
                    sfile.write('%30.15E'%(mu) + '%30.15E'%(t)
                                + '%30.15E'%(ucdensity) + '%30.15E'%(energy_density)
                                + '%30.15E'%(correlation_length)
                                + '%30.15E'%(1.0 * Number_of_Ground_States)
                                + '%30.15E'%(of) + '%30.15E'%(trunc) + '\n')

                # correlation functions
                corrfilename = outputstub + 'mu' + str(mu) + 't' + str(t) \
                               + 'chi' + str(chi) + str(state) + 'corr.dat'
                corrfile = open(corrfilename, 'w')
                for ii in range(1, myObservables.correlation_range):
                    corrfile.write('%16i'%(ii) + '%30.15E'%(nn_connected[ii])
                                   + '%30.15E'%(spdm[ii]) + '\n')
                corrfile.close()

        for ii in range(len(scalarfile)):
            scalarfile[ii].close()
def main(PostProcess=False):

    # Build operators
    Operators = mps.BuildSpinOperators(spin=0.5)

    # Define Hamiltonian MPO
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['splus', 'sminus'], hparam='J_xy', weight=0.5)
    H.AddMPOTerm('bond', ['sz', 'sz'], hparam='J_z', weight=1.0)

    # Ground state observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'sz', 'z')
    # correlation functions
    myObservables.AddObservable('corr', ['sz', 'sz'], 'zz')
    myObservables.AddObservable('corr', ['splus', 'sminus'], 'pm')
    # Get correlation functions out to a distance of 1000
    myObservables.SpecifyCorrelationRange(1000)

    myConv = mps.iMPSConvParam(max_bond_dimension=12,
                               variance_tol=-1.0,
                               max_num_imps_iter=1000)
    mod_list = ['max_bond_dimension', 'max_num_imps_iter']
    myConv.AddModifiedConvergenceParameters(0, mod_list, [20, 500])
    myConv.AddModifiedConvergenceParameters(0, mod_list, [40, 250])

    # Long run time (Enable if you prefer)
    #myConv.AddModifiedConvergenceParameters(0, mod_list, [60, 250])
    #myConv.AddModifiedConvergenceParameters(0, mod_list, [80, 250])

    L = 2
    # Define statics
    parameters = [{
        # Directories
        'job_ID': 'Spin0.5Heisenberg',
        'Write_Directory': 'TMP_07/',
        'Output_Directory': 'OUTPUTS_07/',
        # System size and Hamiltonian parameters
        'L': L,
        'J_z': 1.0,
        'J_xy': 1.0,
        'simtype': 'Infinite',
        # Convergence parameters
        'MPSObservables': myObservables,
        'MPSConvergenceParameters': myConv,
        'logfile': True
    }]

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)
    # Run the simulations
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing and plotting
    # ---------------------------

    Outputs = mps.ReadStaticObservables(parameters)
    clfilename = parameters[0]['job_ID'] + 'correlationLength.dat'
    clfile = open(clfilename, 'w')

    for Output in Outputs:
        chi = Output['max_bond_dimension']
        state = Output['state']
        print('Chi', chi, 'state', state, 'energy density',
              Output['energy_density'], 0.25 - np.log(2.0))

        if (state == 0):
            corrfilename = parameters[0]['job_ID'] + 'chi' + str(chi) \
                           + 'corr.dat'
            corrfile = open(corrfilename, 'w')
            for ii in range(0, myObservables.correlation_range):
                corrfile.write('%16i' % (ii) + '%30.15E' % (Output['zz'][ii]) +
                               '%30.15E' % (Output['pm'][ii]) + '\n')

            corrfile.close()
            clfile.write('%16i' % (chi) + '%30.15E' %
                         (Output['Correlation_length']) + '\n')
            print(sum(Output['z']), Output['zz'][0:6])

    clfile.close()

    return
def main(PostProcess=False):
    """
    Introductory example for openMPS to simulate a fermionic system with
    long-range interactions. Two modes are available when running the
    example from command line:

    * ``python LongRangeTunneling.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics (initial state).
      (default if ``--PostProcess`` not present.)
    * ``python LongRangeTunneling.py --PostProcess=T`` : printing the results
      of the simulation run before.
    """

    # Build operators
    Operators = mps.BuildFermiOperators()

    # Define Hamiltonian MPO
    H = mps.MPO(Operators)
    H.AddMPOTerm('FiniteFunction', ['fdagger', 'f'],
                 f=[1.0, -0.2],
                 hparam='t',
                 weight=-1.0,
                 Phase=True)

    # Observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'nftotal', 'n')
    # Correlation functions
    myObservables.AddObservable('corr', ['fdagger', 'f'], 'spdm', Phase=True)

    # Convergence parameters
    myConv = mps.MPSConvParam(max_bond_dimension=30, max_num_sweeps=2)
    myConv.AddModifiedConvergenceParameters(
        0, ['max_bond_dimension', 'local_tol'], [50, 1E-14])

    # Specify constants and parameter list
    t = 1.0
    L = 10
    N = 5

    parameters = [{
        'simtype': 'Finite',
        # Directories
        'job_ID': 'LongRangeTunneling_',
        'unique_ID': 'L_' + str(L) + 'N' + str(N),
        'Write_Directory': 'TMP_05/',
        'Output_Directory': 'OUTPUTS_05/',
        # System size and Hamiltonian parameters
        'L': L,
        't': t,
        # Specification of symmetries and good quantum numbers
        'Abelian_generators': ['nftotal'],
        'Abelian_quantum_numbers': [N],
        'MPSObservables': myObservables,
        'MPSConvergenceParameters': myConv,
        'logfile': True
    }]

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if not just post processing
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing
    # --------------

    Outputs = mps.ReadStaticObservables(parameters)

    # Get observables of state computed with most stringent convergence criteria
    fullyconvergedOutputs = mps.GetObservables(Outputs,
                                               'convergence_parameter', 2)
    spdm = fullyconvergedOutputs[0]['spdm']
    spdmeigs, U = np.linalg.eigh(spdm)
    print('Eigenvalues of <f^{\dagger}_i f_j>', spdmeigs)

    return
Example #5
0
import MPSPyLib as mps
import numpy as np
from sys import version_info
import matplotlib.pyplot as plt
import sys

# Build operators
Operators = mps.BuildBoseOperators(5)
Operators['interaction'] = 0.5 * (
    np.dot(Operators['nbtotal'], Operators['nbtotal']) - Operators['nbtotal'])

# Define Hamiltonian MPO
H = mps.MPO(Operators)
H.AddMPOTerm('bond', ['bdagger', 'b'], hparam='t', weight=-1.0)
H.AddMPOTerm('site', 'interaction', hparam='U', weight=1.0)

myObservables = mps.Observables(Operators)
myObservables.AddObservable('site', 'nbtotal', 'n')
myObservables.AddObservable('Lambda', [])

myConv = mps.MPSConvParam(max_bond_dimension=20, max_num_sweeps=6)
myConv.AddModifiedConvergenceParameters(0, ['max_bond_dimension', 'local_tol'],
                                        [50, 1E-14])

myKrylovConv = mps.KrylovConvParam(max_num_lanczos_iter=20, lanczos_tol=1E-6)

dynObservables = mps.Observables(Operators)
dynObservables.AddObservable('site', 'nbtotal', name='n')
dynObservables.AddObservable('Lambda', [])

tau = 10
    'Output_Directory': 'Output/',
    'L': L,
    'J': 0, #JWi(Wi),
    'U': UWi(Wi),
    'Abelian_generators': ['nbtotal'],
    'Abelian_quantum_numbers': [L],
    'verbose': 0,
    'MPSObservables': myObservables,
    'MPSConvergenceParameters': myConv,
    'Quenches': Quenches,
    'DynamicsObservables': dynObservables
})

MainFiles=mps.WriteFiles(parameters,Operators,H,PostProcess=PostProcessOnly)
# input()
mps.runMPS(MainFiles)

Outputs = mps.ReadDynamicObservables(parameters)
# Outputs = mps.ReadStaticObservables(parameters)

# print Outputs

# print Outputs[0][0]['time']
# print Outputs[0][0]['n']
# print Outputs[0][0]['n2']
# print Outputs[0][-1]['time']
# print Outputs[0][-1]['n']
# print Outputs[0][-1]['n2']


t = []
def main(PostProcess=False):
    """
    Introductory example for spinless fermions showing the effect of the phase
    term in the correlation measurement of the single particle density matrix.
    Two modes are available when running the example from command line:

    * ``python IsingStatics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics of the Ising model and print them.
      (default if ``--PostProcess`` not present.)
    * ``python IsingStatics.py --PostProcess=T`` : printing the results of the
      simulation run before.
    """

    # Build operators
    Operators = mps.BuildFermiOperators()

    # Define Hamiltonian MPO
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['fdagger', 'f'], hparam='t', weight=-1.0, Phase=True)

    # Observables
    myObservables = mps.Observables(Operators)
    # Correlation functions
    myObservables.AddObservable('corr', ['fdagger', 'f'], 'bspdm')
    myObservables.AddObservable('corr', ['fdagger', 'f'], 'spdm', Phase=True)

    # Convergence data
    myConv = mps.MPSConvParam(max_bond_dimension=30, max_num_sweeps=2)

    t = 1.0
    L = 10
    N = 5

    # Define statics
    parameters = [{
        # Directories
        'simtype': 'Finite',
        'job_ID': 'SpinlessFermions_',
        'unique_ID': 'L_' + str(L) + 'N' + str(N),
        'Write_Directory': 'TMP_04/',
        'Output_Directory': 'OUTPUTS_04/',
        # System size and Hamiltonian parameters
        'L': L,
        't': t,
        'verbose': 2,
        'logfile': True,
        # Specification of symmetries and good quantum numbers
        'Abelian_generators': ['nftotal'],
        'Abelian_quantum_numbers': [N],
        'MPSObservables': myObservables,
        'MPSConvergenceParameters': myConv
    }]

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing
    # --------------

    Outputs = mps.ReadStaticObservables(parameters)

    spdm = Outputs[0]['spdm']
    spdmeigs, U = np.linalg.eigh(spdm)
    bspdm = Outputs[0]['bspdm']
    bspdmeigs, U = np.linalg.eigh(bspdm)

    print('Eigenvalues of <f^{\dagger}_i f_j> with Fermi phases', spdmeigs)
    print('Eigenvalues of <f^{\dagger}_i f_j> without Fermi phases', bspdmeigs)

    return
def simulate(L, ExpName, PostProcess=False, ShowPlot=True):
    """
    PostProcess = False:
        Runs the MPSFortLib to determine the ground state statics of the Ising model
    PostProcess = True:
        Obtain the simulated results from the already run simulation
    """

    # Build spin operators for spin-1/2 system
    # Transform to perserve Z2 symmetry
    Operators = mps.BuildSpinOperators(0.5)
    Operators['sigmax'] = 2 * Operators['sz']
    Operators['sigmaz'] = (Operators['splus'] + Operators['sminus'])
    Operators['gen'] = np.array([[0, 0], [0, 1.]])
    # Define Hamiltonian of transverse Ising model
    H = mps.MPO(Operators)
    # Note the J parameter in the transverse Ising Hamiltonian
    # has been set to 1, we are modelling a ferromagnetic chain.
    H.AddMPOTerm('bond', ['sigmaz', 'sigmaz'], hparam='J', weight=-1.0)
    H.AddMPOTerm('site', 'sigmax', hparam='g', weight=-1.0)

    # Observables and convergence parameters
    myObservables = mps.Observables(Operators)
    #myObservables.AddObservable('corr', ['sigmaz', 'sigmaz'], 'zz')
    myObservables.AddObservable('DensityMatrix_i', [])
    myObservables.AddObservable('DensityMatrix_ij', [])
    myObservables.AddObservable('MI', True)
    myConv = mps.MPSConvParam(max_bond_dimension=200,
                              variance_tol=1E-10,
                              local_tol=1E-10,
                              max_num_sweeps=6)
    #modparam = ['max_bond_dimension', 'max_num_sweeps']
    #myConv.AddModifiedConvergenceParameters(0, modparam, [80, 4])

    # Specify constants and parameter lists
    J = 1.0
    glist = np.linspace(0.1, 2.1, 81)
    parameters = []

    for g in glist:
        parameters.append({
            'simtype':
            'Finite',
            # Directories
            'job_ID':
            'Ising_Statics',
            'unique_ID':
            'g_' + str(g),
            'Write_Directory':
            '{}/TMP_ISING_01_L_{}/'.format(ExpName, L),
            'Output_Directory':
            '{}/OUTPUTS_ISING_01_L_{}/'.format(ExpName, L),
            # System size and Hamiltonian parameters
            'L':
            L,
            'J':
            J,
            'g':
            g,
            # ObservablesConvergence parameters
            'verbose':
            1,
            'MPSObservables':
            myObservables,
            'MPSConvergenceParameters':
            myConv,
            'logfile':
            True,
            # Z2 symmetry
            'Discrete_generators': ['gen'],
            'Discrete_quantum_numbers': [0]
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if we are not just Post
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return None, None

    # PostProcess
    # -----------
    MI_list = []
    Outputs = mps.ReadStaticObservables(parameters)
    for Output in Outputs:
        print(Output['converged'])
        MI_list.append(Output['MI'][3][26])

    timestamp = int(time.time() * 1000.0)
    if ShowPlot:
        plt.style.use('seaborn-colorblind')
        #plt.style.use('seaborn-whitegrid')
        plt.rc('font', family='serif')
        plt.rc('mathtext', fontset='cm')
        plt.scatter(glist, MI_list)
        plt.xlabel(r"transverse field coupling  " r"$g$", fontsize=16)
        plt.ylabel(r"Mutual information (4,27)", fontsize=16)
        plt.savefig('{}/MI_L_{}_{}.pdf'.format(exp_name, L, timestamp),
                    bbox_inches='tight')
        plt.show()

    return Outputs, glist
Example #9
0
def main():
    """
    Example for a variational steady state search comparing the MPDO
    result to ED. Excited states are enabled as well for the variational
    OQS, but do not return the real part of the gap of the Liouvillian
    as we are using Ldagger L.
    """

    # Build spin operators for spin-1/2 system
    Ops = mps.BuildSpinOperators(0.5)
    Ops['sigmaz'] = 2 * Ops['sz']
    Ops['sigmax'] = (Ops['splus'] + Ops['sminus'])

    # Define Hamiltonian of transverse Ising model
    Ham = mps.MPO(Ops)
    Ham.AddMPOTerm('bond', ['sigmaz', 'sigmaz'], hparam='J', weight=-1.0)
    Ham.AddMPOTerm('site', 'sigmax', hparam='g', weight=-1.0)
    Ham.AddMPOTerm('lind1', 'splus', hparam='gamma', weight=1.0)

    # Convergence parameters 
    myConv = mps.MPDOConvParam(max_bond_dimension=64)
    ExConv = mps.MPSConvParam(max_bond_dimension=64)

    # Observables
    myObs = mps.Observables(Ops)
    myObs.AddObservable('site', 'sigmax', 'x')
    myObs.AddObservable('site', 'sigmaz', 'z')
    myObs.AddObservable('corr', ['sigmaz', 'sigmaz'], 'zz')

    # Set parameters.
    J = 1.0
    g = 1.5
    gamma = 0.1
    ll = 5

    parameters = []
    parameters.append({
        'simtype'                   : 'Finite',
        # Directories
        'job_ID'                    : 'Ising_Statics',
        'unique_ID'                 : 'g_' + str(g),
        'Write_Directory'           : 'TMP_36/',
        'Output_Directory'          : 'OUTPUTS_36/',
        # System size and Hamiltonian parameters
        'L'                         : ll,
	'J'                         : J,
        'g'                         : g,
        'gamma'                     : gamma,
        # ObservablesConvergence parameters
        'verbose'                   : 1,
        'MPSObservables'            : myObs,
        'MPSConvergenceParameters'  : myConv,
        'n_excited_states'          : 1,
        'eMPSConvergenceParameters' : ExConv,
        'logfile'                   : True
    })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters, Ops, Ham,
                               PostProcess=False)

    # Run the simulations and quit if we are not just Post
    if(not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Do some ED measures
    # -------------------

    # Get Hamiltonian for energy measure and Liouville operator
    Hmat = Ham.build_hamiltonian(parameters[0], None, False, 33)
    Lmat = Ham.build_liouville(parameters[0], None, False, 2025)

    tmp = np.dot(np.transpose(np.conj(Lmat)), Lmat)
    [vals, vecs] = la.eigh(tmp)
    rvals = np.real(vals)

    idx = np.argsort(rvals)

    print('Two smallest eigenvalues', vals[idx[0]], vals[idx[1]])

    rho = np.reshape(vecs[:, idx[0]], [2**ll, 2**ll])
    rho /= np.trace(rho)

    energy_ED = np.real(np.trace(np.dot(Hmat, rho)))

    rho = ed.DensityMatrix(rho, 2, ll, None)
    xlist = []
    zlist = []
    zzlist = []
    zz = np.kron(Ops['sigmaz'], Ops['sigmaz'])

    for ii in range(ll):
        rhoii = rho.getset_rho((ii,))
        obsii = np.real(np.trace(np.dot(rhoii.rho, Ops['sigmax'])))
        xlist.append(obsii)

        obsii = np.real(np.trace(np.dot(rhoii.rho, Ops['sigmaz'])))
        zlist.append(obsii)

        if(ii == ll - 1): continue
        rhoij = rho.getset_rho((ii, ii + 1))
        obsii = np.real(np.trace(np.dot(rhoij.rho, zz)))
        zzlist.append(obsii)


    # PostProcess
    # -----------

    energy_MPS = []
    Outputs = mps.ReadStaticObservables(parameters)

    print('Eigenvalue from MPDOs', Outputs[0]['LdL_eigenvalue'],
          Outputs[1]['LdL_eigenvalue'])

    for Output in Outputs[:1]:
        energy_MPS.append(Output['energy'])
        print('x', Output['x'])
        print('z', Output['z'])

    zz = np.diag(Outputs[0]['zz'][1:, :-1])

    print('zz nearest neighbor', zz)
        
    print('energy MPS', energy_MPS)
    print('energy ED', energy_ED)

    print('')

    print('Error energy', np.abs(energy_MPS - energy_ED))
    print('Error x', np.abs(np.array(xlist) - Outputs[0]['x']))
    print('Error z', np.abs(np.array(zlist) - Outputs[0]['z']))
    print('Error NN zz', np.abs(zz - zzlist))

    return
def simulate(L, ExpName, PostProcess=False, ShowPlot=True):
    """
    PostProcess = False:
        Runs the MPSFortLib to simulate the finite size statics of the BoseHubbard model
        using number conservation
    PostProcess = True:
        Obtain the simulated results from the already run simulation
    """

    # Build operators
    Operators = mps.BuildBoseOperators(6)
    Operators['interaction'] = 0.5 * (np.dot(
        Operators['nbtotal'], Operators['nbtotal']) - Operators['nbtotal'])
    # Define Hamiltonian of transverse Ising model
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['bdagger', 'b'], hparam='t', weight=-1.0)
    H.AddMPOTerm('site', 'interaction', hparam='U', weight=1.0)
    #H.AddMPOTerm('bond', ['nbtotal', 'nbtotal'], hparam='V', weight=1.0)

    # ground state observables
    myObservables = mps.Observables(Operators)
    # site terms
    myObservables.AddObservable('site', 'nbtotal', name='n')
    #myObservables.AddObservable('DensityMatrix_i', [])
    #myObservables.AddObservable('DensityMatrix_ij', [])
    myObservables.AddObservable('MI', True)
    myConv = mps.MPSConvParam(max_bond_dimension=200,
                              variance_tol=1E-8,
                              local_tol=1E-8,
                              max_num_sweeps=7)
    #modparam = ['max_bond_dimension', 'max_num_sweeps']
    #myConv.AddModifiedConvergenceParameters(0, modparam, [80, 4])

    # Specify constants and parameter lists
    U = 1.0
    tlist = np.linspace(0.02, 1.00, 50)
    #tlist = np.linspace(0.01, 0.41, 41)
    #tlist = np.linspace(0.1, 0.4, 5)
    parameters = []
    N = L

    for t in tlist:
        parameters.append({
            'simtype':
            'Finite',
            # Directories
            'job_ID':
            'Bose_Hubbard_Statics',
            'unique_ID':
            't_' + str(t) + 'N_' + str(N),
            'Write_Directory':
            '{}/TMP_BoseHubbard_L_{}/'.format(ExpName, L),
            'Output_Directory':
            '{}/OUTPUTS_BoseHubbard_L_{}/'.format(ExpName, L),
            # System size and Hamiltonian parameters
            'L':
            L,
            't':
            t,
            'U':
            U,
            # Specification of symmetries and good quantum numbers
            'Abelian_generators': ['nbtotal'],
            # Define filling
            'Abelian_quantum_numbers': [N],
            # Convergence parameters
            'verbose':
            1,
            'logfile':
            True,
            'MPSObservables':
            myObservables,
            'MPSConvergenceParameters':
            myConv
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if we are not just Post
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return None, tlist

    # PostProcess
    # -----------
    MI_list = []
    Outputs = mps.ReadStaticObservables(parameters)
    M = int(L / 2)
    for Output in Outputs:
        print(Output['converged'])
        MI_list.append(Output['MI'][3][M])

    timestamp = int(time.time() * 1000.0)
    if ShowPlot:
        plt.style.use('seaborn-colorblind')
        #plt.style.use('seaborn-whitegrid')
        plt.rc('font', family='serif')
        plt.rc('mathtext', fontset='cm')
        plt.scatter(tlist, MI_list)
        plt.xlabel(r"Tunneling " r"$J/U$", fontsize=16)
        plt.ylabel(r"Mutual information (4,L/2+1)", fontsize=16)
        plt.savefig('{}/BoseHubbard_MI_L_{}_{}.pdf'.format(
            exp_name, L, timestamp),
                    bbox_inches='tight')
        plt.show()

    return Outputs, tlist
Example #11
0
def main(PostProcess=False):
    """

    """
    epsilon_e = 0.5
    epsilon_nuc = 0.5

    exchange = 0

    eigenstate = 0
    totalstate = eigenstate + 1

    specflag = 'S'

    t = 1.0
    L = 12
    N = 6
    eefactor = 1
    nfactor = 2

    testflag = 'Finite'
    max_sweep = 10
    int_range = L
    lambda_up = 20
    lambda_lo = 0
    itr = 21

    # Build operators
    Operators = mps.BuildFermiOperators()

    # Hopping terms
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['fdagger', 'f'], hparam='t', weight=1.0, Phase=True)

    # Adding the electron-electron interaction

    eeinvr = []

    for eerange in range(int_range):
        eeinvr.append(1.0 / (eerange + 1.0 + epsilon_e))

    H.AddMPOTerm('FiniteFunction', ['nftotal', 'nftotal'],
                 f=eeinvr,
                 hparam='lambda_e',
                 weight=1.0)

    nucinvr = []

    for nucrange in range(int_range):
        nucinvr.append(1.0 / (nucrange + 1.0 + epsilon_nuc))

    H.AddMPOTerm('FiniteFunction', ['nftotal', 'I'],
                 f=nucinvr,
                 hparam='lambda_nuc',
                 weight=-1.0)
    '''



    # Adding the nucleus-electron interaction
    
    # infinite function for the nuclear interaction

    eeinvr = lambda x : 1.0 /(x+epsilon_e)
    H.AddMPOTerm('InfiniteFunction', ['nftotal','nftotal'], func=eeinvr, hparam='lambda_e', weight=1.0, L=1000, tol=1e-12, maxnterms=100) 



    nucinvr = lambda x : 1.0 /(x+epsilon_nuc)
    H.AddMPOTerm('InfiniteFunction', ['nftotal','I'], func=nucinvr, hparam='lambda_nuc', weight= -1.0, L=1000, tol=1e-12, maxnterms=100) 
    
    # Alternative way of defining the term using Finite functions

    
    '''

    H.printMPO()

    # Observables
    myObservables = mps.Observables(Operators)
    # Correlation functions
    #myObservables.AddObservable('corr', ['fdagger','f'], 'bspdm')
    #myObservables.AddObservable('corr', ['fdagger','f'], 'spdm', Phase=True)

    # Convergence data
    myConv = mps.MPSConvParam(max_bond_dimension=500,
                              max_num_sweeps=max_sweep,
                              max_num_lanczos_iter=100,
                              variance_tol=1e-12,
                              method=specflag,
                              warmup_bond_dimension=500)

    #lambda_list = np.logspace(lambda_lo, lambda_up, itr)
    #lambda_list=np.linspace(lambda_lo,lambda_up,itr)

    lambda_list = np.array([
        0.0, 0.03, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5,
        1.75, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20, 30, 40, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000,
        50000
    ])

    if not eefactor:
        lambda_list = np.array([
            0, 0.03, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5,
            1.75, 2, 10, 20, 30, 40, 50, 100, 200, 500, 1000
        ])

    if not nfactor:
        lambda_list = np.array([
            0, 0.03, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5,
            1.75, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
            18, 19, 20, 30, 40, 50, 100
        ])

    parameters = []

    start_time = time.time()

    for lambda_e in lambda_list:

        # Define statics
        lambda_nuc = lambda_e

        ID = 'var' + testflag + 'L_' + str(L) + 'N' + str(N) + 'int' + str(int_range) +  'lambda' + str(lambda_nuc) + 'exc' + str(exchange) + 'eig' + \
         str(eigenstate) + 'factor' + str(eefactor) + '_' + str(nfactor)  + specflag


        dirID = 'var' + testflag + 'L_' + str(L) + 'N' + str(N) + 'int' + str(int_range)  + 'exc' + str(exchange) + 'eig' + \
         str(eigenstate) + 'factor' + str(eefactor) + '_' + str(nfactor) + specflag +  '/'

        parameters.append({
            # Directories
            'simtype': testflag,
            'job_ID': 'GWB_ET',
            'unique_ID': ID,
            'Write_Directory': dirID,
            'Output_Directory': 'OUTPUTS' + dirID,
            # System size and Hamiltonian parameters
            'L': L,
            't': t,
            'lambda_e': eefactor * (1 - exchange) * lambda_e,
            'lambda_nuc': nfactor * lambda_nuc,
            'n_excited_states': eigenstate,
            'verbose': 2,
            'logfile': True,
            # Specification of symmetries and good quantum numbers
            'Abelian_generators': ['nftotal'],
            'Abelian_quantum_numbers': [N],
            'MPSObservables': myObservables,
            'MPSConvergenceParameters': myConv
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing
    # --------------
    #Outputs = mps.Result(parameters, 'eMPS', 1)
    Outputs = mps.ReadStaticObservables(parameters)
    energies = np.zeros(lambda_list.shape[0] * totalstate)

    end_time = time.time()

    elapsed_time = end_time - start_time

    print(elapsed_time)
    #print(len(Outputs))

    itr_count = min(100, lambda_list.shape[0])
    #print(itr_count)
    for lambda_i in range(itr_count * totalstate):
        '''
        spdm = Outputs[lambda_i]['spdm']
        spdmeigs, U = np.linalg.eigh(spdm)
        bspdm = Outputs[lambda_i]['bspdm']
        bspdmeigs, U = np.linalg.eigh(bspdm)
        '''

        energies[lambda_i] = Outputs[lambda_i]['energy']

        #print('Eigenvalues of <f^{\dagger}_i f_j> with Fermi phases', spdmeigs)
        #$print('Eigenvalues of <f^{\dagger}_i f_j> without Fermi phases', bspdmeigs)
        #print(Outputs[lambda_i]['energy'])
        #print(Outputs[lambda_i]['state'])

    gsenergy = np.zeros(itr_count)
    newenergy = np.zeros((totalstate, itr_count))
    for state in range(totalstate):
        for lambda_i in range(itr_count):
            newenergy[state][lambda_i] = energies[lambda_i * totalstate +
                                                  state] - energies[lambda_i *
                                                                    totalstate]
            gsenergy[lambda_i] = energies[lambda_i * totalstate]
    print(lambda_list)
    print(gsenergy)

    file_name = testflag + str(L) + '_' + str(N) + 'res_ex_' + str(
        exchange) + '_eig' + str(eigenstate) + '_range' + str(
            int_range) + '_' + str(max_sweep) + '.dat'
    gs_name = 'gsvar' + testflag + str(L) + '_' + str(N) + 'int' + str(
        int_range) + '_ex_' + str(exchange) + '_eescale_' + str(
            eefactor) + '_nscale_' + str(nfactor) + specflag + '.dat'
    plot_name = testflag + str(L) + '_' + str(N) + 'energy_ex_' + str(
        exchange) + '_eig' + str(eigenstate) + '_range' + str(
            int_range) + '_' + str(max_sweep) + '.png'

    np.savetxt(file_name, newenergy, fmt='%10.5f')
    np.savetxt(gs_name, gsenergy, fmt='%8.5f')
    #eplot(lambda_list, newenergy, plot_name, itr_count)

    return
def main(PostProcess=False, ShowPlots=True):
    """
    Introductory example for openMPS to simulate the finite size dynamics of
    the Bose-Hubbard model with number conservation. Two modes are available
    when running the example from command line:

    * ``python BoseHubbardDynamics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics (initial state) and then the dynamics.
      (default if ``--PostProcess`` not present.)
    * ``python BoseHubbardDynamics.py --PostProcess=T`` : plotting the results
      of the simulation run before.
    * The option ``--ShowPlots=T`` (``--ShowPlots=F``) lets you turn on (off)
      the GUI windows with the plots. Default to on if not passed to the
      command line.
    """

    # Build operators
    Operators = mps.BuildBoseOperators(5)
    Operators['interaction'] = 0.5 * (np.dot(
        Operators['nbtotal'], Operators['nbtotal']) - Operators['nbtotal'])

    # Define Hamiltonian MPO
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['bdagger', 'b'], hparam='t', weight=-1.0)
    H.AddMPOTerm('site', 'interaction', hparam='U', weight=1.0)

    # Ground state observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'nbtotal', 'n')
    # Correlation functions
    myObservables.AddObservable('corr', ['nbtotal', 'nbtotal'], 'nn')
    myObservables.AddObservable('corr', ['bdagger', 'b'], 'spdm')

    # Convergence parameters
    myConv = mps.MPSConvParam(max_bond_dimension=20, max_num_sweeps=6)
    myConv.AddModifiedConvergenceParameters(
        0, ['max_bond_dimension', 'local_tol'], [50, 1E-14])

    myDynConv = mps.TDVPConvParam(max_num_lanczos_iter=20, lanczos_tol=1E-6)

    # Dynamics time evolution observables
    dynObservables = mps.Observables(Operators)
    # Site terms
    dynObservables.AddObservable('site', 'nbtotal', name='n')

    # Specify constants and parameter lists
    U = 10.0
    t = 1.0
    staticsParameters = []
    L = 6
    tlist = [5.0, 20.0]

    for tau in tlist:
        # Quench function ramping down
        def Ufuncdown(t, tau=tau):
            return 10.0 + 2.0 * (1.0 - 10.0) * t / tau

        # Quench function ramping back up
        def Ufuncup(t, tau=tau):
            return 1.0 + 2.0 * (10.0 - 1.0) * (t - 0.5 * tau) / tau

        Quenches = mps.QuenchList(H)
        Quenches.AddQuench(['U'],
                           0.5 * tau,
                           min(0.5 * tau / 100.0, 0.1), [Ufuncdown],
                           ConvergenceParameters=myDynConv)
        Quenches.AddQuench(['U'],
                           0.5 * tau,
                           min(0.5 * tau / 100.0, 0.1), [Ufuncup],
                           ConvergenceParameters=myDynConv)

        staticsParameters.append({
            'simtype': 'Finite',
            # Directories
            'job_ID': 'Bose_Hubbard_mod',
            'unique_ID': 'tau_' + str(tau),
            'Write_Directory': 'TMP_03/',
            'Output_Directory': 'OUTPUTS_03/',
            # System size and Hamiltonian parameters
            'L': L,
            't': t,
            'U': U,
            # Specification of symmetries and good quantum numbers
            'Abelian_generators': ['nbtotal'],
            'Abelian_quantum_numbers': [L],
            # Convergence parameters
            'verbose': 1,
            'logfile': True,
            'MPSObservables': myObservables,
            'MPSConvergenceParameters': myConv,
            'Quenches': Quenches,
            'DynamicsObservables': dynObservables
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(staticsParameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if not just post processing
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing and plotting
    # ---------------------------

    Outputs = mps.ReadStaticObservables(staticsParameters)
    DynOutputs = mps.ReadDynamicObservables(staticsParameters)

    ii = 0
    le_list = [[], []]

    for t in tlist:
        myfile = 'outmod' + str(t) + '.dat'
        hfile = open(myfile, 'w')
        for p in DynOutputs[ii]:
            hfile.write('%30.15E' % (p['time']) + '%30.15E' % (p['U']) +
                        '%30.15E' % (p['Loschmidt_Echo'].real) + '%30.15E' %
                        (p['Loschmidt_Echo'].imag) + '%30.15E' %
                        (p['bond_dimension']) + '\n')
            le_list[ii].append(abs(p['Loschmidt_Echo'])**2)

        hfile.close()
        ii += 1

    plt.rc('font', family='serif')
    plt.rc('mathtext', fontset='cm')
    plt.plot(np.linspace(0, 1, len(le_list[0])),
             le_list[0],
             'r-',
             label="tq=5")
    plt.plot(np.linspace(0, 1, len(le_list[1])),
             le_list[1],
             'g-',
             label="tq=20")
    plt.xlabel(r"Time in percent " r"$t / t_q$", fontsize=16)
    plt.ylabel(r"Loschmidt Echo "
               r"$| \langle \psi(t) | \psi(0) \rangle |^2$",
               fontsize=16)
    plt.legend(loc="lower left")
    if (ShowPlots):
        plt.savefig('03_BoseHubbardDynamics.pdf', bbox_inches='tight')
        plt.show()

    return
def main(PostProcess=False, ShowPlots=True):
    """
    Introductory example for openMPS to simulate the finite size statics of
    the Bose-Hubbard model using number conservation. Two modes are available
    when running the example from command line:

    * ``python BoseHubbardStatics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics (initial state) and then the dynamics.
      (default if ``--PostProcess`` not present.)
    * ``python BoseHubbardStatics.py --PostProcess=T`` : plotting the results
      of the simulation run before.
    * The option ``--ShowPlots=T`` (``--ShowPlots=F``) lets you turn on (off)
      the GUI windows with the plots. Default to on if not passed to the
      command line.
    """
    # Cannot use time.clock as it does not capture subprocesses
    t0 = time()

    # Build operators
    Operators = mps.BuildBoseOperators(6)
    Operators['interaction'] = 0.5 * (np.dot(
        Operators['nbtotal'], Operators['nbtotal']) - Operators['nbtotal'])
    # Define Hamiltonian MPO
    H = mps.MPO(Operators)
    H.AddMPOTerm('bond', ['bdagger', 'b'], hparam='t', weight=-1.0)
    H.AddMPOTerm('site', 'interaction', hparam='U', weight=1.0)

    # ground state observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'nbtotal', 'n')
    # correlation functions
    myObservables.AddObservable('corr', ['nbtotal', 'nbtotal'], 'nn')
    myObservables.AddObservable('corr', ['bdagger', 'b'], 'spdm')

    myConv = mps.MPSConvParam(max_num_sweeps=7)

    U = 1.0
    tlist = np.linspace(0, 0.4, 21)
    parameters = []
    L = 10
    Nlist = np.linspace(1, 11, 11)

    for t in tlist:
        for N in Nlist:
            parameters.append({
                'simtype': 'Finite',
                # Directories
                'job_ID': 'Bose_Hubbard_statics',
                'unique_ID': 't_' + str(t) + 'N_' + str(N),
                'Write_Directory': 'TMP_02/',
                'Output_Directory': 'OUTPUTS_02/',
                # System size and Hamiltonian parameters
                'L': L,
                't': t,
                'U': U,
                # Specification of symmetries and good quantum numbers
                'Abelian_generators': ['nbtotal'],
                # Define Filling
                'Abelian_quantum_numbers': [N],
                # Convergence parameters
                'verbose': 1,
                'logfile': True,
                'MPSObservables': myObservables,
                'MPSConvergenceParameters': myConv
            })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)
    # Run the simulations and quit if we are not just Post
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing and plotting
    # ---------------------------

    Outputs = mps.ReadStaticObservables(parameters)

    depletion = np.zeros((Nlist.shape[0], tlist.shape[0]))
    energies = np.zeros((Nlist.shape[0], tlist.shape[0]))
    tinternal = np.zeros((Nlist.shape[0], tlist.shape[0]))
    chempotmu = np.zeros((Nlist.shape[0], tlist.shape[0]))

    kk = -1
    for ii in range(tlist.shape[0]):
        tinternal[:, ii] = tlist[ii]

        for jj in range(Nlist.shape[0]):
            kk += 1

            spdm = np.linalg.eigh(Outputs[kk]['spdm'])[0]
            depletion[jj, ii] = 1.0 - np.max(spdm) / np.sum(spdm)

            energies[jj, ii] = Outputs[kk]['energy']

        chempotmu[0, ii] = energies[0, ii]
        chempotmu[1:, ii] = energies[1:, ii] - energies[:-1, ii]

    if (ShowPlots):
        plotIt(tinternal, chempotmu, depletion)

    return
Example #14
0
def main(PostProcess=False):
    """
    Introductory example for openMPS to simulate the Haldana Shastry model with
    infinite MPS. Two modes are available when running the example from command
    line:

    * ``python IsingStatics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics of the Ising model. (default if
      ``--PostProcess`` not present.)
    * ``python IsingStatics.py --PostProcess=T`` : plotting the results of the
      simulation run before.
    """

    # Build operators
    Operators = mps.BuildSpinOperators(spin=0.5)

    # Define Hamiltonian MPO
    H = mps.MPO(Operators, PostProcess=PostProcess)
    invrsq = lambda x: 1.0 / (x**2)
    H.AddMPOTerm('InfiniteFunction', ['splus', 'sminus'],
                 hparam='J_xy',
                 weight=0.5,
                 func=invrsq,
                 L=1000,
                 tol=1e-9)
    H.AddMPOTerm('InfiniteFunction', ['sz', 'sz'],
                 hparam='J_z',
                 weight=1.0,
                 func=invrsq,
                 L=1000,
                 tol=1e-9)

    # Ground state observables
    myObservables = mps.Observables(Operators)
    # Site terms
    myObservables.AddObservable('site', 'sz', 'z')
    # Correlation functions
    myObservables.AddObservable('corr', ['sz', 'sz'], 'zz')
    myObservables.AddObservable('corr', ['splus', 'sminus'], 'pm')
    # Get correlation functions out to a distance of 1000
    myObservables.SpecifyCorrelationRange(1000)

    # Convergence parameters
    myConv = mps.iMPSConvParam(max_bond_dimension=12,
                               variance_tol=-1.0,
                               max_num_imps_iter=1000)

    mod_list = ['max_bond_dimension', 'max_num_imps_iter']
    myConv.AddModifiedConvergenceParameters(0, mod_list, [20, 500])
    myConv.AddModifiedConvergenceParameters(0, mod_list, [40, 250])

    # Long run time (Enable if you prefer)
    #myConv.AddModifiedConvergenceParameters(0, mod_list, [60, 250])
    #myConv.AddModifiedConvergenceParameters(0, mod_list, [80, 250])

    L = 2
    parameters = [{
        'simtype': 'Infinite',
        # Directories
        'job_ID': 'HaldaneShastry',
        'Write_Directory': 'TMP_06/',
        'Output_Directory': 'OUTPUTS_06/',
        # System size and Hamiltonian parameters
        'L': L,
        'J_z': 1.0,
        'J_xy': 1.0,
        # Convergence parameters
        'MPSObservables': myObservables,
        'MPSConvergenceParameters': myConv,
        'logfile': True
    }]

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)
    # Run the simulations
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # Postprocessing and plotting
    Outputs = mps.ReadStaticObservables(parameters)
    clfilename = parameters[0]['job_ID'] + 'correlationLength.dat'
    clfile = open(clfilename, 'w')

    for Output in Outputs:
        chi = Output['bond_dimension']
        print('Chi', chi)
        print('energy density', Output['energy_density'])

        corrfilename = parameters[0]['job_ID'] + 'chi' + str(chi) + 'corr.dat'
        corrfile = open(corrfilename, 'w')

        for ii in range(1, myObservables.correlation_range):
            (tmp, ci) = sici((ii) * pi)
            ex = tmp / (4.0 * pi * (ii))
            corrfile.write('%16i' % (ii) + '%30.15E' % (Output['zz'][ii]) +
                           '%30.15E' % (Output['pm'][ii]) + '%30.15E' % (ex) +
                           '\n')
        corrfile.close()
        clfile.write('%16i' % (chi) + '%30.15E' %
                     (Output['Correlation_length']) + '\n')
        (tmp, ci) = sici((1.0) * pi)
        ex = tmp / (4.0 * pi * (1.0))

        print(sum(Output['z']), Output['zz'][1], Output['zz'][2], ex)

    clfile.close()

    return
Example #15
0
    'g': Ng,
    'W': Wi,
    'pen': 1e12,
    'Abelian_generators': ['ntotal'],
    'Abelian_quantum_numbers': [L],
    'verbose': 0,
    # 'n_excited_states': 5,
    'MPSObservables': myObservables,
    'eMPSObservables': myObservables,
    'MPSConvergenceParameters': myConv,
    'Quenches': Quenches,
    'DynamicsObservables': dynObservables
})

MainFiles=mps.WriteFiles(parameters,Operators,H,PostProcess=PostProcessOnly)
mps.runMPS(MainFiles,RunDir='./')

Outputs = mps.ReadDynamicObservables(parameters)
Outputs2 = mps.ReadStaticObservables(parameters)

print Outputs2[0]['np']
# print Outputs2[0]['npp']
# print Outputs2[0]['npm']
print Outputs2[0]['np2']
print Outputs2[0]['na']
print Outputs2[0]['nS12']
print Outputs2[0]['nS13']
print Outputs2[0]['nS14']
print Outputs2[0]['na2']
print Outputs2[0]['nS122']
print Outputs2[0]['nS132']
Example #16
0
def main(PostProcess=False, ShowPlots=True):
    """
    Introductory example for openMPS to simulate the finite size statics of
    the transverse Ising model. Two modes are available when running the
    example from command line:

    * ``python IsingStatics.py --PostProcess=F`` : runs the MPSFortLib to
      determine the ground state statics of the Ising model. (default if
      ``--PostProcess`` not present.)
    * ``python IsingStatics.py --PostProcess=T`` : plotting the results of the
      simulation run before.
    * The option ``--ShowPlots=T`` (``--ShowPlots=F``) lets you turn on (off)
      the GUI windows with the plots. Default to on if not passed to the
      command line.
    """

    # Build spin operators for spin-1/2 system
    Operators = mps.BuildSpinOperators(0.5)
    Operators['sigmax'] = 2 * Operators['sz']
    Operators['sigmaz'] = -(Operators['splus'] + Operators['sminus'])
    Operators['gen'] = np.array([[0, 0], [0, 1.]])
    # Define Hamiltonian of transverse Ising model
    H = mps.MPO(Operators)
    # Note the J parameter in the transverse Ising Hamiltonian
    # has been set to 1, we are modelling a ferromagnetic chain.
    H.AddMPOTerm('bond', ['sigmaz', 'sigmaz'], hparam='J', weight=-1.0)
    H.AddMPOTerm('site', 'sigmax', hparam='g', weight=-1.0)

    # Observables and convergence parameters
    myObservables = mps.Observables(Operators)
    myObservables.AddObservable('MI', True)

    myConv = mps.MPSConvParam(max_bond_dimension=60,
                              max_num_sweeps=6,
                              local_tol=1E-14)

    # Specify constants and parameter lists
    J = 1.0
    glist = np.linspace(0.1, 2.1, 21)
    parameters = []
    L = 128

    for g in glist:
        parameters.append({
            'simtype': 'Finite',
            # Directories
            'job_ID': 'Ising_Statics',
            'unique_ID': 'g_' + str(g),
            'Write_Directory': 'MI_TMP_01_L_{}/'.format(L),
            'Output_Directory': 'MI_OUTPUTS_01_L_{}/'.format(L),
            # System size and Hamiltonian parameters
            'L': L,
            'J': J,
            'g': g,
            # ObservablesConvergence parameters
            'verbose': 1,
            'MPSObservables': myObservables,
            'MPSConvergenceParameters': myConv,
            'logfile': True,
            # Z2 symmetry
            'Discrete_generators': ['gen'],
            'Discrete_quantum_numbers': [0]
        })

    # Write Fortran-readable main files
    MainFiles = mps.WriteFiles(parameters,
                               Operators,
                               H,
                               PostProcess=PostProcess)

    # Run the simulations and quit if we are not just Post
    if (not PostProcess):
        if os.path.isfile('./Execute_MPSMain'):
            RunDir = './'
        else:
            RunDir = None
        mps.runMPS(MainFiles, RunDir=RunDir)
        return

    # PostProcess
    # -----------

    MI_list = []
    Outputs = mps.ReadStaticObservables(parameters)
    for Output in Outputs:
        print(Output['converged'])

        # Get mutual information
        MI_list.append(Output['MI'][3][26])

    plt.rc('font', family='serif')
    plt.rc('mathtext', fontset='cm')
    plt.scatter(glist, MI_list)
    plt.xlabel(r"transverse field coupling  " r"$g$", fontsize=16)
    plt.ylabel(r"Mutual information " r"(4, 27)", fontsize=16)
    if (ShowPlots):
        plt.savefig('MI_check_IsingStatics_L_{}.pdf'.format(L),
                    bbox_inches='tight')
        plt.show()

    return