示例#1
0
def example_exact_diagonalization(L, Jz):
    xxz_pars = dict(L=L, Jxx=1., Jz=Jz, hz=0.0, bc_MPS='finite')
    M = XXZChain(xxz_pars)

    product_state = ["up", "down"] * (xxz_pars['L'] // 2)  # this selects a charge sector!
    psi_DMRG = MPS.from_product_state(M.lat.mps_sites(), product_state)
    charge_sector = psi_DMRG.get_total_charge(True)  # ED charge sector should match

    ED = ExactDiag(M, charge_sector=charge_sector, max_size=2.e6)
    ED.build_full_H_from_mpo()
    # ED.build_full_H_from_bonds()  # whatever you prefer
    print("start diagonalization")
    ED.full_diagonalization()  # the expensive part for large L
    E0_ED, psi_ED = ED.groundstate()  # return the ground state
    print("psi_ED =", psi_ED)

    print("run DMRG")
    dmrg.run(psi_DMRG, M, {'verbose': 0})  # modifies psi_DMRG in place!
    # first way to compare ED with DMRG: convert MPS to ED vector
    psi_DMRG_full = ED.mps_to_full(psi_DMRG)
    print("psi_DMRG_full =", psi_DMRG_full)
    ov = npc.inner(psi_ED, psi_DMRG_full, axes='range', do_conj=True)
    print("<psi_ED|psi_DMRG_full> =", ov)
    assert (abs(abs(ov) - 1.) < 1.e-13)

    # second way: convert ED vector to MPS
    psi_ED_mps = ED.full_to_mps(psi_ED)
    ov2 = psi_ED_mps.overlap(psi_DMRG)
    print("<psi_ED_mps|psi_DMRG> =", ov2)
    assert (abs(abs(ov2) - 1.) < 1.e-13)
    assert (abs(ov - ov2) < 1.e-13)
    # -> advantage: expectation_value etc. of MPS are available!
    print("<Sz> =", psi_ED_mps.expectation_value('Sz'))
示例#2
0
def example_DMRG_finite(L, g):
    print("finite DMRG, L={L:d}, g={g:.2f}".format(L=L, g=g))
    model_params = dict(L=L,
                        J=1.,
                        g=g,
                        bc_MPS='finite',
                        conserve=None,
                        verbose=0)
    M = TFIChain(model_params)
    psi = MPS.from_product_state(M.lat.mps_sites(), [0] * L, bc='finite')
    dmrg_params = {
        'mixer': None,
        'trunc_params': {
            'chi_max': 30,
            'svd_min': 1.e-10
        },
        'max_E_err': 1.e-10,
        'verbose': 1
    }
    dmrg.run(psi, M, dmrg_params)
    E = np.sum(psi.expectation_value(M.H_bond[1:]))
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    if L < 20:  # compare to exact result
        E_exact = tfi_exact.finite_gs_energy(L, 1., g)
        print("Exact diagonalization: E = {E:.13f}".format(E=E_exact))
        print("relative error: ", abs((E - E_exact) / E_exact))
    return E, psi, M
示例#3
0
def example_DMRG_infinite(g):
    print("infinite DMRG, g={g:.2f}".format(g=g))
    model_params = dict(L=2,
                        J=1.,
                        g=g,
                        bc_MPS='infinite',
                        conserve=None,
                        verbose=0)
    M = TFIChain(model_params)
    psi = MPS.from_product_state(M.lat.mps_sites(), [0] * 2, bc='infinite')
    dmrg_params = {
        'mixer': True,
        'trunc_params': {
            'chi_max': 30,
            'svd_min': 1.e-10
        },
        'max_E_err': 1.e-10,
        'verbose': 1
    }
    dmrg.run(psi, M, dmrg_params)
    E = np.mean(psi.expectation_value(M.H_bond))
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    print("correlation length:", psi.correlation_length())
    # compare to exact result
    E_exact = tfi_exact.infinite_gs_energy(1., g)
    print("Analytic result: E/L = {E:.13f}".format(E=E_exact))
    print("relative error: ", abs((E - E_exact) / E_exact))
    return E, psi, M
示例#4
0
def main():
    L = 80
    delta = 0.9064

    file_name="L"+str(L) + \
      "_D"+str(int(delta*10000))+\
      "E0" + \
      "_CHIall.pkl"

    verbose_model = 0
    verbose_dmrg = 0

    t = 1.0
    alpha = 0.5
    beta = 0.02

    cnsrv_bsn = 'Sz'
    cnsrv_spn = None

    model_params = {
        'L': L,
        'bc_MPS': 'finite',
        't': t,
        'alpha': alpha,
        'delta': delta,
        'beta': beta,
        'conserve_fermionic_boson': cnsrv_bsn,
        'conserve_spin': cnsrv_spn,
        'verbose': verbose_model
    }
    M = FermionOnSpinLattice(model_params)
    initial_state = [0] * (L // 2) + [2] * (L // 2)

    pkl_pack = [model_params, M]

    chi_start = np.arange(10) + 5
    chi_end = np.arange(35) * 2 + 15

    #chis = np.concatenate((chi_start, chi_end))
    # extra chi for 80
    chis = np.arange(10) * 2 + 85
    for chi in chis:
        psi = MPS.from_product_state(M.lat.mps_sites(),
                                     initial_state,
                                     bc='finite')
        dmrg_params = {'mixer': None, 'verbose': verbose_dmrg, \
              'trunc_params': {'chi_max': chi, 'svd_min': 1.e-10}}
        start_time = time.time()
        dmrg.run(psi, M, dmrg_params)
        end_time = time.time()
        print("D max = {c}\tDMRG time = {b}".format(c=chi,
                                                    b=end_time - start_time))
        pkl_pack += [[psi, chi]]

    with open(file_name, 'wb') as g:
        pickle.dump(pkl_pack, g)

    return 0
示例#5
0
def main():
    L = 60
    chi = 80
    U = 10.0
    beta = 0.02

    file_name = "U" + str(int(U)) +\
      "_L"+str(L)+\
      "_Ds_ch"+str(chi)+\
      ".pkl"

    verbose_model = 0
    verbose_dmrg = 0

    t = 1.0
    Mu = 16.0
    alpha = 0.5

    cnsrv_bsn = 'N'
    cnsrv_spn = None
    pkl_pack = []

    for ddelta in range(51):
        delta = 0.50 + ddelta * 0.01
        model_params = {
            'n_max': 2,
            'L': L,
            'bc_MPS': 'finite',
            'filling': 0.5,
            't': t,
            'U': U,
            'mu': Mu,
            'alpha': alpha,
            'delta': delta,
            'beta': beta,
            'conserve_boson': cnsrv_bsn,
            'conserve_spin': cnsrv_spn,
            'verbose': verbose_model
        }
        M = BosonSpin(model_params)
        initial_state = [0] * (L // 2) + [2] * (L // 2)
        psi = MPS.from_product_state(M.lat.mps_sites(),
                                     initial_state,
                                     bc='finite')
        dmrg_params = {'mixer': None, 'verbose': verbose_dmrg, \
              'trunc_params': {'chi_max': chi, 'svd_min': 1.e-10}}
        start_time = time.time()
        dmrg.run(psi, M, dmrg_params)
        end_time = time.time()
        print("$\Delta = {a:.04f}$\tDMRG time = {b}".format(a=delta,
                                                            b=end_time -
                                                            start_time))
        pkl_pack += [[psi, model_params, dmrg_params]]

    with open(file_name, 'wb') as g:
        pickle.dump(pkl_pack, g)

    return 0
示例#6
0
def main():
    L = 46
    chi = 50

    file_name = "L" + str(L) + "_D09E_CHI" + str(chi) + ".pkl"

    verbose_model = 0
    verbose_dmrg = 0

    t = 1.0
    alpha = 0.5
    beta = 0.02

    cnsrv_bsn = 'Sz'
    cnsrv_spn = None
    pkl_pack = []

    for ddelta in range(101):
        delta = 0.9063 + ddelta * 0.000063
        model_params = {
            'L': L,
            'bc_MPS': 'finite',
            'filling': 0.5,
            't': t,
            'alpha': alpha,
            'delta': delta,
            'beta': beta,
            'conserve_fermionic_boson': cnsrv_bsn,
            'conserve_spin': cnsrv_spn,
            'verbose': verbose_model
        }
        M = FermionOnSpinLattice(model_params)
        initial_state = [0] * (L // 2) + [2] * (L // 2)
        psi = MPS.from_product_state(M.lat.mps_sites(),
                                     initial_state,
                                     bc='finite')
        dmrg_params = {'mixer': None, 'verbose': verbose_dmrg, \
              'trunc_params': {'chi_max': chi, 'svd_min': 1.e-10}}
        start_time = time.time()
        dmrg.run(psi, M, dmrg_params)
        end_time = time.time()
        print("Delta = {a:.04f}\tDMRG time = {b}".format(a=delta,
                                                         b=end_time -
                                                         start_time))
        pkl_pack += [[psi, model_params, dmrg_params]]

    with open(file_name, 'wb') as g:
        pickle.dump(pkl_pack, g)

    return 0
示例#7
0
def test_ToricCode(Lx=1, Ly=2):
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        model_params = {'Lx': Lx, 'Ly': Ly}
        M = ToricCode(model_params)
        psi = MPS.from_product_state(M.lat.mps_sites(), [0] * M.lat.N_sites,
                                     bc='infinite')
        dmrg_params = {
            'mixer': True,
            'trunc_params': {
                'chi_max': 10,
                'svd_min': 1.e-10
            },
            'max_E_err': 1.e-10,
            'N_sweeps_check': 4,
            'verbose': 1
        }
        result = dmrg.run(psi, M, dmrg_params)
        E = result['E']
        print("E =", E)
        psi.canonical_form()
        # energy per "cell"=2 -> energy per site in the dual lattice = 1
        assert abs(E - (-1.)) < dmrg_params['max_E_err']
        print("chi=", psi.chi)
        if Ly == 2:
            assert tuple(psi.chi[:4]) == (2, 4, 4, 4)
        assert abs(
            psi.entanglement_entropy(bonds=[0])[0] - np.log(2) *
            (Ly - 1)) < 1.e-5
示例#8
0
def example_DMRG_tf_ising_finite(L, g, verbose=True):
    print("finite DMRG, transverse field Ising model")
    print("L={L:d}, g={g:.2f}".format(L=L, g=g))
    model_params = dict(L=L, J=1., g=g, bc_MPS='finite', conserve=None, verbose=verbose)
    M = TFIChain(model_params)
    product_state = ["up"] * M.lat.N_sites
    psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS)
    dmrg_params = {
        'mixer': None,  # setting this to True helps to escape local minima
        'max_E_err': 1.e-10,
        'trunc_params': {
            'chi_max': 30,
            'svd_min': 1.e-10
        },
        'verbose': verbose,
    }
    info = dmrg.run(psi, M, dmrg_params)  # the main work...
    E = info['E']
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    mag_x = np.sum(psi.expectation_value("Sigmax"))
    mag_z = np.sum(psi.expectation_value("Sigmaz"))
    print("magnetization in X = {mag_x:.5f}".format(mag_x=mag_x))
    print("magnetization in Z = {mag_z:.5f}".format(mag_z=mag_z))
    if L < 20:  # compare to exact result
        from tfi_exact import finite_gs_energy
        E_exact = finite_gs_energy(L, 1., g)
        print("Exact diagonalization: E = {E:.13f}".format(E=E_exact))
        print("relative error: ", abs((E - E_exact) / E_exact))
    return E, psi, M
def DMRG_tf_ising_finite(Lx, Ly, g, verbose=True):
    print("finite DMRG, transverse field Ising model")
    print("Lx={Lx:d}, Ly={Ly:d}, g={g:.2f}".format(Lx=Lx, Ly=Ly, g=g))
    M = TFIModel(
        dict(g=g,
             J=1.,
             lattice='Triangular',
             bc_MPS='finite',
             Lx=Lx,
             Ly=Ly,
             conserve=None,
             verbose=verbose))
    product_state = ["up"] * M.lat.N_sites
    psi = MPS.from_product_state(M.lat.mps_sites(),
                                 product_state,
                                 bc=M.lat.bc_MPS)
    dmrg_params = {
        'mixer': None,
        'max_E_err': 1.e-10,
        'trunc_params': {
            'chi_max': 30,
            'svd_min': 1.e-10
        },
        'verbose': verbose,
        'combine': True
    }
    info = dmrg.run(psi, M, dmrg_params)
    E = info['E']
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    mag_x = np.sum(psi.expectation_value("Sigmax"))
    mag_z = np.sum(psi.expectation_value("Sigmaz"))
    print("magnetization in X = {mag_x:.5f}".format(mag_x=mag_x))
    print("magnetization in Z = {mag_z:.5f}".format(mag_z=mag_z))
    return E, psi, M
示例#10
0
def example_DMRG_heisenberg_xxz_finite(L, Jz, chi, conserve='best', verbose=True):
    print("finite DMRG, Heisenberg XXZ chain")
    print("L={L:d}, Jz={Jz:.2f}".format(L=L, Jz=Jz))
    model_params = dict(L=L, S=0.5, Jx=1., Jy=1., Jz=Jz,
                        bc_MPS='finite', conserve=conserve, verbose=verbose)
    M = SpinModel(model_params)
    product_state = ["up", "down"] * (M.lat.N_sites // 2)
    psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS)
    dmrg_params = {
        'mixer': True,  # setting this to True helps to escape local minima
        'max_E_err': 1.e-16,
        'trunc_params': {
            'chi_max': chi,
            'svd_min': 1.e-16
        },
        'verbose': verbose,
    }
    info = dmrg.run(psi, M, dmrg_params)  # the main work...
    E = info['E']
    E = E * 4
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    Sz = psi.expectation_value("Sz")  # Sz instead of Sigma z: spin-1/2 operators!
    mag_z = np.mean(Sz)
    print("<S_z> = [{Sz0:.5f}, {Sz1:.5f}]; mean ={mag_z:.5f}".format(Sz0=Sz[0],
                                                                     Sz1=Sz[1],
                                                                     mag_z=mag_z))
    # note: it's clear that mean(<Sz>) is 0: the model has Sz conservation!
    corrs = psi.correlation_function("Sz", "Sz", sites1=range(10))
    print("correlations <Sz_i Sz_j> =")
    print(corrs)
    return E, psi, M
示例#11
0
def example_DMRG_tf_ising_finite(L, g, h=0, chi=2, verbose=True):
    print("finite DMRG, transverse field Ising model")
    print("L={L:d}, g={g:.2f}, h={h:.2f}".format(L=L, g=g, h=h))
    model_params = dict(L=L, J=1., g=g, bc_MPS='finite', h=h)
    M = IsingChain(model_params)

    # model_params = dict(L=L, J=1., g=g, bc_MPS='finite', conserve=None, verbose=verbose)
    # M = TFIChain(model_params)

    product_state = ["up"] * M.lat.N_sites
    psi = MPS.from_product_state(M.lat.mps_sites(),
                                 product_state,
                                 bc=M.lat.bc_MPS)
    dmrg_params = {
        'mixer': None,  # setting this to True helps to escape local minima
        'max_E_err': 1.e-16,
        'trunc_params': {
            'chi_max': chi,
            'svd_min': 1.e-16
        },
        'verbose': verbose,
    }
    info = dmrg.run(psi, M, dmrg_params)  # the main work...
    E = info['E']
    print("E = {E:.16f}".format(E=E))
    print("final bond dimensions: ", psi.chi)
    mag_x = np.sum(psi.expectation_value("Sigmax"))
    mag_z = np.sum(psi.expectation_value("Sigmaz"))
    print("magnetization in X = {mag_x:.5f}".format(mag_x=mag_x))
    print("magnetization in Z = {mag_z:.5f}".format(mag_z=mag_z))
    return E, psi, M
示例#12
0
 def example_DMRG_heisenberg_xxz_infinite(Jx=1,
                                          Jy=1,
                                          Jz=1,
                                          hx=0,
                                          hy=0,
                                          hz=0,
                                          conserve='best',
                                          verbose=False,
                                          chi_max=100,
                                          S=0.5):
     if verbose:
         print("infinite DMRG, Heisenberg XXZ chain")
         print("Jz={Jz:.2f}, conserve={conserve!r}".format(
             Jz=Jz, conserve=conserve))
     model_params = dict(
         L=2,
         S=S,  # spin 1/2
         Jx=Jx,
         Jy=Jy,
         Jz=Jz,  # couplings
         hx=hx,
         hy=hy,
         hz=hz,
         bc_MPS='infinite',
         conserve=conserve,
         verbose=verbose)
     M = SpinModel(model_params)
     product_state = ["up", "up"]  # initial Neel state
     psi = MPS.from_product_state(M.lat.mps_sites(),
                                  product_state,
                                  bc=M.lat.bc_MPS)
     dmrg_params = {
         'mixer': True,  # setting this to True helps to escape local minima
         'trunc_params': {
             'chi_max': chi_max,
             'svd_min': 1.e-10,
         },
         'max_E_err': 1.e-10,
         'verbose': verbose,
     }
     info = dmrg.run(psi, M, dmrg_params)
     E = info['E']
     if verbose:
         print("E = {E:.13f}".format(E=E))
         print("final bond dimensions: ", psi.chi)
     Sz = psi.expectation_value(
         "Sz")  # Sz instead of Sigma z: spin-1/2 operators!
     mag_z = np.mean(Sz)
     if verbose:
         print("<S_z> = [{Sz0:.5f}, {Sz1:.5f}]; mean ={mag_z:.5f}".format(
             Sz0=Sz[0], Sz1=Sz[1], mag_z=mag_z))
     # note: it's clear that mean(<Sz>) is 0: the model has Sz conservation!
     if verbose:
         print("correlation length:", psi.correlation_length())
     corrs = psi.correlation_function("Sz", "Sz", sites1=range(10))
     if verbose:
         print("correlations <Sz_i Sz_j> =")
         print(corrs)
     return E, psi, M
示例#13
0
def test_dmrg(bc_MPS, combine, mixer, n, g=1.2):
    L = 2 if bc_MPS == 'infinite' else 8
    model_params = dict(L=L, J=1., g=g, bc_MPS=bc_MPS, conserve=None, verbose=0)
    M = TFIChain(model_params)
    state = [0] * L  # Ferromagnetic Ising
    psi = mps.MPS.from_product_state(M.lat.mps_sites(), state, bc=bc_MPS)
    dmrg_pars = {
        'verbose': 5,
        'combine': combine,
        'mixer': mixer,
        'chi_list': {
            0: 10,
            5: 30
        },
        'max_E_err': 1.e-12,
        'max_S_err': 1.e-8,
        'N_sweeps_check': 4,
        'mixer_params': {
            'disable_after': 15,
            'amplitude': 1.e-5
        },
        'trunc_params': {
            'svd_min': 1.e-10,
        },
        'max_N_for_ED': 20,  # small enough that we test both diag_method=lanczos and ED_block!
        'max_sweeps': 40,
        'active_sites': n,
    }
    if not mixer:
        del dmrg_pars['mixer_params']  # avoid warning of unused parameter
    if bc_MPS == 'infinite':
        # if mixer is not None:
        #     dmrg_pars['mixer_params']['amplitude'] = 1.e-12  # don't actually contribute...
        dmrg_pars['start_env'] = 1
    res = dmrg.run(psi, M, dmrg_pars)
    if bc_MPS == 'finite':
        ED = ExactDiag(M)
        ED.build_full_H_from_mpo()
        ED.full_diagonalization()
        E_ED, psi_ED = ED.groundstate()
        ov = npc.inner(psi_ED, ED.mps_to_full(psi), 'range', do_conj=True)
        print("E_DMRG={Edmrg:.14f} vs E_exact={Eex:.14f}".format(Edmrg=res['E'], Eex=E_ED))
        print("compare with ED: overlap = ", abs(ov)**2)
        assert abs(abs(ov) - 1.) < 1.e-10  # unique groundstate: finite size gap!
        var = M.H_MPO.variance(psi)
        assert var < 1.e-10
    else:
        # compare exact solution for transverse field Ising model
        Edmrg = res['E']
        Eexact = e0_tranverse_ising(g)
        print("E_DMRG={Edmrg:.12f} vs E_exact={Eex:.12f}".format(Edmrg=Edmrg, Eex=Eexact))
        print("relative energy error: {err:.2e}".format(err=abs((Edmrg - Eexact) / Eexact)))
        print("norm err:", psi.norm_test())
        Edmrg2 = np.mean(psi.expectation_value(M.H_bond))
        Edmrg3 = M.H_MPO.expectation_value(psi)
        assert abs((Edmrg - Eexact) / Eexact) < 1.e-10
        assert abs((Edmrg - Edmrg2) / Edmrg2) < max(1.e-10, np.max(psi.norm_test()))
        assert abs((Edmrg - Edmrg3) / Edmrg3) < max(1.e-10, np.max(psi.norm_test()))
示例#14
0
def check_dmrg(L=4, bc_MPS='finite', engine='EngineCombine', mixer=None, g=1.5):
    model_params = dict(L=L, J=1., g=g, bc_MPS=bc_MPS, conserve=None, verbose=0)
    M = TFIChain(model_params)
    state = [0] * L  # Ferromagnetic Ising
    psi = mps.MPS.from_product_state(M.lat.mps_sites(), state, bc=bc_MPS)
    dmrg_pars = {
        'verbose': 5,
        'engine': engine,
        'mixer': mixer,
        'chi_list': {
            0: 10,
            5: 30
        },
        'max_E_err': 1.e-12,
        'max_S_err': 1.e-8,
        'N_sweeps_check': 4,
        'mixer_params': {
            'disable_after': 6,
            'amplitude': 1.e-5
        },
        'trunc_params': {
            'svd_min': 1.e-10,
        },
        'lanczos_params': {
            'reortho': True,
            'N_cache': 20
        },
        'max_sweeps': 40,
    }
    if mixer is None:
        del dmrg_pars['mixer_params']  # avoid warning of unused parameter
    if bc_MPS == 'infinite':
        if mixer is not None:
            dmrg_pars['mixer_params']['amplitude'] = 1.e-12  # don't actually contribute...
        dmrg_pars['start_env'] = 1
    res = dmrg.run(psi, M, dmrg_pars)
    if bc_MPS == 'finite':
        ED = ExactDiag(M)
        ED.build_full_H_from_mpo()
        ED.full_diagonalization()
        psi_ED = ED.groundstate()
        ov = npc.inner(psi_ED, ED.mps_to_full(psi), do_conj=True)
        print("E_DMRG={Edmrg:.14f} vs E_exact={Eex:.14f}".format(Edmrg=res['E'], Eex=np.min(ED.E)))
        print("compare with ED: overlap = ", abs(ov)**2)
        assert abs(abs(ov) - 1.) < 1.e-10  # unique groundstate: finite size gap!
    else:
        # compare exact solution for transverse field Ising model
        Edmrg = res['E']
        Eexact = e0_tranverse_ising(g)
        print("E_DMRG={Edmrg:.12f} vs E_exact={Eex:.12f}".format(Edmrg=Edmrg, Eex=Eexact))
        print("relative energy error: {err:.2e}".format(err=abs((Edmrg - Eexact) / Eexact)))
        print("norm err:", psi.norm_test())
        Edmrg2 = np.mean(psi.expectation_value(M.H_bond))
        assert abs((Edmrg - Eexact) / Eexact) < 1.e-10
        assert abs((Edmrg - Edmrg2) / Edmrg2) < max(1.e-10, np.max(psi.norm_test()))
示例#15
0
def example_run_dmrg():
    """Use iDMRG to extract information about the ground state of the system."""
    model_params = dict(L=2, Jxx=1, Jz=1.5, xi=0.8, verbose=1)
    model = ExponentiallyDecayingHeisenberg(model_params)
    psi = MPS.from_product_state(model.lat.mps_sites(), ["up", "down"], bc='infinite')
    dmrg_params = {'mixer': True,
                   'chi_list': {0: 100},
                   'trunc_params': {'svd_min': 1.e-10},
                   'verbose': 1}
    results = dmrg.run(psi, model, dmrg_params)
    print("Energy per site: ", results['E'])
    print("<Sz>: ", psi.expectation_value('Sz'))
示例#16
0
def test_ToricCode(Lx=1, Ly=2):
    model_params = {'Lx': Lx, 'Ly': Ly, 'bc_MPS': 'infinite'}
    M = ToricCode(model_params)
    psi = MPS.from_product_state(M.lat.mps_sites(), [0] * M.lat.N_sites, bc='infinite')
    dmrg_params = {
        'mixer': True,
        'trunc_params': {
            'chi_max': 10,
            'svd_min': 1.e-10
        },
        'P_tol_to_trunc': None,  # avoid warning about unused "P_tol" lanczos
        'max_E_err': 1.e-10,
        'N_sweeps_check': 4,
    }
    result = dmrg.run(psi, M, dmrg_params)
    E = result['E']
    print("E =", E)
    psi.canonical_form()
    # energy per "cell"=2 -> energy per site in the dual lattice = 1
    assert abs(E - (-1.)) < dmrg_params['max_E_err']
    print("chi=", psi.chi)
    if Ly == 2:
        assert tuple(psi.chi[:4]) == (2, 2, 2, 2)
    assert abs(psi.entanglement_entropy(bonds=[0])[0] - np.log(2) * (Ly - 1)) < 1.e-5
示例#17
0
def test_mixed_spinless():
    """
    compare a small system of spinless fermions in real and mixed space
    """
    Lx, Ly = 2, 4
    J, V = 1., 10
    chimax = 100
    #real space
    model_params = dict(J=J,
                        V=V,
                        lattice='Square',
                        Lx=Lx,
                        Ly=Ly,
                        bc_x='open',
                        bc_y='cylinder',
                        bc_MPS='finite')
    M = FermionModel(model_params)

    dmrg_params = {
        'mixer': True,
        'max_E_err': 1.e-12,
        'max_S_err': 1.e-8,
        'trunc_params': {
            'chi_max': chimax,
            'svd_min': 1.e-10
        },
    }
    product_state = [[['full'], ['empty'], ['full'], ['empty']],
                     [['full'], ['empty'], ['full'], ['empty']]]  # half filling
    psi = MPS.from_lat_product_state(M.lat, product_state)
    info = dmrg.run(psi, M, dmrg_params)
    E_real = info['E']

    #measure particle number and Cd C correlators
    N_real = M.lat.mps2lat_values(psi.expectation_value('N'))
    CdC_real = M.lat.mps2lat_values(psi.correlation_function('Cd', 'C')[0, :])

    #mixed space
    model_params = dict(t=J, V=V, Lx=Lx, Ly=Ly, bc_MPS='finite', conserve_k=True)
    M = SpinlessMixedXKSquare(model_params)

    #initial product state with momentum 0
    product_xk = [['full', 'empty', 'full', 'empty'], ['full', 'empty', 'full', 'empty']]
    psi_xk = MPS.from_lat_product_state(M.lat, product_xk)
    info = dmrg.run(psi_xk, M, dmrg_params)  # the main work...
    E_mixed = info['E']

    #measure particle number and Cd C correlators
    N_mixed = np.zeros((Lx, Ly), dtype='complex')
    CdC_mixed = np.zeros((Lx, Ly), dtype='complex')
    for i in range(Lx):
        for j in range(Ly):
            terms_N = M.real_to_mixed_onsite([[1]], (i, j))
            N_mixed[i, j] = psi_xk.expectation_value_terms_sum(terms_N)[0]
            terms_CdC = M.real_to_mixed_correlations_any(['Cd', 'C'], [(1., [0, 0])], [(0, 0),
                                                                                       (i, j)])
            CdC_mixed[i, j] = psi_xk.expectation_value_terms_sum(terms_CdC)[0]

    assert np.abs(E_real - E_mixed) < 1e-10
    assert np.all(np.abs(N_real - N_mixed) < 1e-10)
    assert np.all(np.abs(CdC_real - CdC_mixed) < 1e-10)
示例#18
0
def dmrg_wrapper(model_par,
                 sim_par,
                 run_par,
                 args,
                 psi=None,
                 sim_filename=None,
                 reload_sim=False):
    """Run DMRG ("Walk this way...").

    Args:
        model_par (dict): Model parameters
        args (Namespace): All command line options
        psi (MPS, optional): Initial state. If None, random state is iinitialized based on model_par and args.

    Returns:
        psi (MPS): Ground state
        out (dict): DMRG output
        num_ini (array): Density profile for the initial state
        M (model): model

    """
    print("chi's in use:", sim_par['CHI_LIST'])
    print("minimum no. of sweeps:", sim_par['MIN_STEPS'])
    print('dmrg_wrapper has bc={}'.format(model_par['bc_MPS']))

    # Check if there is already a data file from a finished run
    try:
        with open('fh_dmrg_' + sim_par['identifier'] + '.dat', 'rb') as f:
            a = pickle.load(f)
        if data['out']['shelve_flag']:
            print("Simulation was shelved. Restarting soon.")
        else:
            print("Finished data file found. Skipping.")
            print('Check for {skip:True}')
            return None, {
                'skip': True
            }, None, None, None  # Not very clean but haven't found anything better
    except IOError:
        print("No data file found. Starting new sim.")
        pass

    if reload_sim:
        with open(sim_filename + '.sim', 'rb') as f:
            save_sim = pickle.load(f)
        sim_par[
            'STARTING_ENV_FROM_PSI'] = 0  # Make sure to use old environments.
        sim_par['CHI_LIST'] = {
            0: max(sim_par['CHI_LIST'].values())
        }  # Assume saved sim had reached max chi.
        sim_par['MIN_STEPS'] = 20
        sim_par['LP'] = save_sim['LP']
        sim_par['RP'] = save_sim['RP']
        psi = save_sim['psi']
        M = save_sim['M']
        num_ini = save_sim['num_ini']
        initial_state = save_sim['initial_state']
    else:
        M = mod.HofstadterFermions(model_par)
        initial_state = build_initial_state(
            M.lat.N_sites, (0, 1),
            (1 - run_par['filling'], run_par['filling']),
            mode='random',
            seed=args.seed)
        if psi == None:
            print("Generating new psi.")
            #L = model_par['Lx'] * model_par['Ly']
            # upfilling, dnfilling = get_filling(run_par, L)
            # prod = random_list(L, upfilling, dnfilling)
            psi = MPS.from_product_state(M.lat.mps_sites(),
                                         initial_state,
                                         bc=model_par['bc_MPS'])
        else:
            print("Using user-specified psi.")
        num_ini = psi.expectation_value('N')
        print('Initial density profile:', num_ini)
    t0 = time.time()
    print("Starting DMRG...")
    out = dmrg.run(psi, M, sim_par)
    print("DMRG took {} seconds.".format(time.time() - t0))
    out['time'] = time.time() - t0

    # sim = simulation.simulation(psi, M)

    # sim.dmrg_par = sim_par
    # sim.ground_state()
    # out = sim.sim_stats[-1]

    # if out['shelve_flag']:  # DMRG did not end before time ran out; save sim to disk
    #     save_sim = {
    #         'LP': out['LP'],
    #         'RP': out['RP'],
    #         'psi': psi,
    #         'M': M,
    #         'num_ini': num_ini,
    #         'initial_state': initial_state,
    #         'model_par': model_par,
    #         'sim_par': sim_par,
    #     }
    #     with open('fh_dmrg_' + identifier + '.sim', 'wb') as f:
    #         pickle.dump(save_sim, f)

    out['skip'] = False

    return psi, out, num_ini, M, initial_state
示例#19
0
"""Call of infinite DMRG."""
# Copyright 2019 TeNPy Developers, GNU GPLv3

from tenpy.networks.mps import MPS
from tenpy.models.tf_ising import TFIChain
from tenpy.algorithms import dmrg

N = 2  # number of sites in unit cell
model = TFIChain({"L": N, "J": 1., "g": 1.1, "bc_MPS": "infinite"})
sites = model.lat.mps_sites()
psi = MPS.from_product_state(sites, ['up'] * N, "infinite")
dmrg_params = {
    "trunc_params": {
        "chi_max": 100,
        "svd_min": 1.e-10
    },
    "mixer": True
}
info = dmrg.run(psi, model, dmrg_params)
print("E =", info['E'])
# E = -1.342864022725017
print("max. bond dimension =", max(psi.chi))
# max. bond dimension = 56
print("corr. length =", psi.correlation_length())
# corr. length = 4.915809146764157
示例#20
0
def fDMRG_KL(
    Jx=1.,
    Jy=1.,
    Jz=1.,
    L=3,
    chi=100,
    verbose=True,
    order='default',
    bc_MPS='finite',
    bc='open',
    # to extract the low-lying excitation
    orthogonal_to={},
):
    """
        The finite DMRG for Kitaev Ladders
    """

    print("finite DMRG, Kitaev ladder model")
    print("L = {L:d}, Jx = {Jx:.2f}, Jy = {Jy:.2f}, Jz = {Jz:.2f}, ".format(
        L=L, Jx=Jx, Jy=Jy, Jz=Jz))
    model_params = dict(L=L,
                        Jx=Jx,
                        Jy=Jy,
                        Jz=Jz,
                        bc_MPS=bc_MPS,
                        bc=bc,
                        conserve=None,
                        order=order,
                        verbose=verbose)
    M = KitaevLadderModel(model_params)

    print("bc_MPS = ", M.lat.bc_MPS)

    product_state = [
        np.random.choice(["up", "down"]) for i in range(M.lat.N_sites)
    ]
    psi = MPS.from_product_state(M.lat.mps_sites(),
                                 product_state,
                                 bc=M.lat.bc_MPS)
    dmrg_params = {
        #         'mixer': None,  # setting this to True helps to escape local minima
        'mixer': True,
        'mixer_params': {
            'amplitude': 1.e-4,
            'decay': 1.2,
            'disable_after': 50
        },
        'max_E_err': 1.e-10,
        'trunc_params': {
            'chi_max': chi,
            'svd_min': 1.e-10
        },
        'verbose': verbose,
        'combine': True,
        'orthogonal_to': orthogonal_to,
    }
    info = dmrg.run(psi, M, dmrg_params)  # the main work...
    E = info['E']
    print("E = {E:.13f}".format(E=E))
    print("final bond dimensions: ", psi.chi)

    return E, psi, M
示例#21
0
def test_mixed_hubbard():
    """
    compare the Hubbard model on a small square lattice in in real and mixed space
    """
    Lx, Ly = 2, 3
    t, U = 1., 10
    chimax = 100
    #real space
    model_params = dict(t=t,
                        U=U,
                        lattice='Square',
                        Lx=Lx,
                        Ly=Ly,
                        bc_x='open',
                        bc_y='cylinder',
                        bc_MPS='finite')
    M = FermiHubbardModel(model_params)

    dmrg_params = {
        'mixer': True,
        'max_E_err': 1.e-12,
        'max_S_err': 1.e-8,
        'trunc_params': {
            'chi_max': chimax,
            'svd_min': 1.e-10
        },
    }
    product_state = [[['full'], ['empty'], ['full']],
                     [['full'], ['empty'], ['empty']]]  #yapf: disable
    psi = MPS.from_lat_product_state(M.lat, product_state)
    info = dmrg.run(psi, M, dmrg_params)
    E_real = info['E']

    #measure Sz onsite and SpSm correlators
    Sz_real = M.lat.mps2lat_values(psi.expectation_value('Sz'))
    SpSm_real = M.lat.mps2lat_values(psi.correlation_function('Sp', 'Sm')[0, :])

    #mixed space
    #implemented with two spinless fermion sites for up/down !
    model_params = dict(t=t, U=U, Lx=Lx, Ly=Ly, bc_MPS='finite', conserve_k=True)
    M2 = HubbardMixedXKSquare(model_params)

    #initial product state with momentum 0
    product_xk = [['full', 'full', 'full', 'empty', 'empty', 'empty'],
                  ['full', 'full', 'empty', 'empty', 'empty', 'full']]
    psi_xk = MPS.from_lat_product_state(M2.lat, product_xk)
    info = dmrg.run(psi_xk, M2, dmrg_params)  # the main work...
    E_mixed = info['E']

    #measure Sz onsite and SpSm correlators
    Sz_mixed = np.zeros((Lx, Ly), dtype='complex')
    SpSm_mixed = np.zeros((Lx, Ly), dtype='complex')
    Sp = np.array([[0, 1], [0, 0]])
    Sm = np.array([[0, 0], [1, 0]])
    Sz = np.array([[1, 0], [0, -1]]) * 0.5
    for i in range(Lx):
        for j in range(Ly):
            terms_Sz = M2.real_to_mixed_onsite(Sz, (i, j))
            Sz_mixed[i, j] = psi_xk.expectation_value_terms_sum(terms_Sz)[0]
            terms_SpSm = M2.real_to_mixed_two_site(Sp, (0, 0), Sm, (i, j))
            SpSm_mixed[i, j] = psi_xk.expectation_value_terms_sum(terms_SpSm)[0]

    assert np.abs(E_real - E_mixed) < 1e-7
    assert np.all(np.abs(Sz_real - Sz_mixed) < 1e-7)
    assert np.all(np.abs(SpSm_real - SpSm_mixed) < 1e-7)