S += np.dot(xi**2, np.log(xi))
            
        E = (-czz - h*mx) / n
        mz /= n
        return [mz, S, E]
        
    return test_fct_impl


basepath = "output_tfi_polish/"
f = open(basepath + "h_mz_E_D={:d}_chi={:d}.dat".format(D, chi), "w")
lut = util.build_lattice_lookup_table([[1,0],[1,0]], [4,4])
env_contractor = tebd.CTMRGEnvContractor(lut, chi, test_fct, 1e-12, 1e-15)

for filename in sorted(os.listdir(basepath)):
    if filename.endswith(".peps"):
        _D = int(filter(lambda s: s.find("D=") != -1, filename[:-5].split("_"))[0].split("=")[-1])
        _chi = int(filter(lambda s: s.find("chi=") != -1, filename[:-5].split("_"))[0].split("=")[-1])
        h = float(filter(lambda s: s.find("h=") != -1, filename[:-5].split("_"))[0].split("=")[-1])
        _tau = float(filter(lambda s: s.find("tau=") != -1, filename[:-5].split("_"))[0].split("=")[-1])
        _trotter2 = "trotter2" in filename
        
        if _D == D and _chi == chi:
            print filename
            a, _ = peps.load(basepath + filename)
            env_contractor.update(a)
            mz, _, E = env_contractor.get_test_values()
            f.write("{:.15e} {:.15e} {:.15e}\n".format(h, mz, E))
f.close()

            norm = e2.contract(AT[j], AT[lut[j, 0, 1]])
            czz += e2.contract(ZT[j], ZT[lut[j, 0, 1]]) / norm

            w1 = np.dot(e.c1[j], e.c2[lut[j, 1, 0]])
            w2 = np.dot(e.c3[lut[j, 1, 1]], e.c4[lut[j, 0, 1]])
            xi = np.linalg.svd(np.dot(w1, w2))[1]
            xi = xi[np.nonzero(xi)]
            S += np.dot(xi ** 2, np.log(xi))

        E = (-czz - h * mx) / n
        mz /= n
        return [mz, S, E]

    return test_fct_impl


a, nns = peps.load(basepath_in + statefile)
lut = util.build_lattice_lookup_table(nns, [4, 4])


def save_callback(a):
    peps.save(a, lut, basepath_out + statefile[statefile.rfind("/") + 1 :])


ecf = tebd.CTMRGEnvContractorFactory(lut, chi, test_fct, 1e-12, 1e-15)
a = polish(a, lut, ecf, num_workers=num_workers, peps_save_callback=save_callback)

peps.save(a, lut, basepath_out + statefile[statefile.rfind("/") + 1 :])

print "tfi_gs_polish.py done; needed {0:f} seconds".format(time() - t0)
import sys
import os

statefile = sys.argv[1]
outfile = sys.argv[2]
chi = int(sys.argv[3])
Lmax = int(sys.argv[4])

def test_fct(e):
    mz = [0]*n
    for j in xrange(n):
        e1 = e.get_site_environment(j)
        mz[j] = e1.contract(Z[j]) / e1.contract(A[j])
    return mz

a, nns = peps.load(statefile)
n = len(a)
lut = util.build_lattice_lookup_table(nns, [4,4])
A = map(peps.make_double_layer, a)
Z = map(lambda b: peps.make_double_layer(b, o=gates.sigmaz), a)

tester = ctm.CTMRGTester(test_fct, 1e-12, 1e-15)
env = ctm.ctmrg(A, lut, chi, "random", tester)

m = np.empty((3, n))
sigma = [gates.sigmax, np.imag(gates.sigmay), gates.sigmaz]
# note: handle take sigmay/i instead of sigmay and multiply with (1/i)^2 = -1

for j in xrange(n):
    e1 = env.get_site_environment(j)
    for k in xrange(3):
        
    return test_fct_impl

def get_gates(dt):
    if trotter_second_order:
        g1 = gates.exp_sigmax(0.5*tau*h)
        g1pre = g1post = [(0, g1), (1, g1)]
    else:
        g1 = gates.exp_sigmax(tau*h)
        g1pre = [(0, g1), (1, g1)]
        g1post = []
    g2 = gates.exp_sigmaz_sigmaz(tau)
    g2 = [(0, 0, g2), (0, 1, g2), (1, 0, g2), (1, 1, g2)]
    return g1pre, g2, g1post

a = peps.load(basepath_varpeps + statefile)[0][0]
a = [a, a]
lut = util.build_lattice_lookup_table([[1,0],[1,0]], [4,4])

env_contractor = tebd.CTMRGEnvContractor(lut, chi, test_fct, 1e-12, 1e-15, ctmrg_verbose=True)
simulation_name = "D={:d}_chi={:d}_h={:f}_tau={:.6f}{:s}".format(D, chi, h, tau, "_trotter2" if trotter_second_order else "")
backup_interval = 100
tebd.itebd_v2(a, lut, 0, tau, maxiterations*tau, get_gates, env_contractor, basepath, simulation_name, backup_interval)


"""
if trotter_second_order:
    g1 = gates.exp_sigmax(0.5*tau*h)
else:
    g1 = gates.exp_sigmax(tau*h)
g1 = [(0, g1), (1, g1)]
            norm = e2.contract(AT[j], AT[lut[j, 0, 1]])
            c_xx += e2.contract(XT[j], XT[lut[j, 0, 1]]) / norm
            c_yy += np.real(e2.contract(YT[j], YT[lut[j, 0, 1]]) / norm)
            c_zz += e2.contract(ZT[j], ZT[lut[j, 0, 1]]) / norm

        c_xx /= 2 * n
        c_yy /= 2 * n
        c_zz /= 2 * n
        E = 2 * J * (c_xx + c_yy + c_zz) + h * 0.5 * (mz[0] + mz[1])

        return mz + [c_xx, c_yy, c_zz, E]

    return test_fct_impl


a, nns = peps.load(statefile, dtype=complex)
lut = util.build_lattice_lookup_table(nns, [4, 4])

if np.all(map(lambda b: (np.imag(b) < 1e-15).all(), a)):
    a = map(lambda b: np.real(b), a)

# env_contractor = tebd.CTMRGEnvContractor(lut, chi, test_fct, 1e-12, 1e-15)
# a = tebd.polish(a, lut, env_contractor, pepsfilename=(basepath + statefile[statefile.rfind("/")+1:]))

# a = tebd.polish(a, lut, chi, test_fct, pepsfilename=(basepath + statefile[statefile.rfind("/")+1:]))


def save_callback(a):
    peps.save(a, lut, basepath + statefile[statefile.rfind("/") + 1 :])