"""Periodic four-site XX Gibbs trace in two tensor directions. Python 3 + NumPy."""
from itertools import product
from math import cosh, sinh
import numpy as np


def gate(t):
    matrix = np.eye(4)
    matrix[1,1] = matrix[2,2] = cosh(t)
    matrix[1,2] = matrix[2,1] = -sinh(t)
    return matrix


def row_layer(local, length, parity):
    states = np.array(list(product((0,1), repeat=length)))
    layer = np.ones((len(states),len(states)))
    for site in range(parity,length,2):
        index = 2*states[:,site]+states[:,(site+1)%length]
        layer *= local[index[:,None],index[None,:]]
    return layer


def spatial_transfer(local, steps):
    # Each site carries one track of 2M spins with periodic imaginary time.
    tracks = np.array(list(product((0,1),repeat=2*steps)))
    left, right = tracks[:,None,:], tracks[None,:,:]
    pairs = 2*left+right
    columns = []
    for parity in (0,1):
        weights = np.ones(pairs.shape[:2])
        for substep in range(parity,2*steps,2):
            weights *= local[pairs[:,:,(substep+1)%(2*steps)],pairs[:,:,substep]]
        columns.append(weights)
    return columns[0] @ columns[1]


def hamiltonian(length, exchange):
    # Independent bit-basis hopping Hamiltonian, including the boundary bond.
    dimension = 2**length
    result = np.zeros((dimension,dimension))
    for state in range(dimension):
        for site in range(length):
            neighbor = (site+1) % length
            if ((state>>site) ^ (state>>neighbor)) & 1:
                target = state ^ (1<<site) ^ (1<<neighbor)
                result[target,state] += exchange/2
    return result


def check():
    length, beta, exchange = 4, 0.7, 1.0
    exact = np.exp(-beta*np.linalg.eigvalsh(hamiltonian(length,exchange))).sum()
    print(f"Direct Gibbs trace: {exact:.13f}")
    for steps in (1,2,3,4,8,16,32,64):
        local = gate(beta*exchange/(2*steps))
        row = row_layer(local,length,0) @ row_layer(local,length,1)
        zrow = np.trace(np.linalg.matrix_power(row,steps))
        if steps <= 4:
            # Conjugate alternate sites by sigma_z, making every gate nonnegative.
            qtm = spatial_transfer(np.abs(local),steps)
            zcolumn = np.trace(np.linalg.matrix_power(qtm,length//2))
            assert abs(zrow-zcolumn) < 5e-12
            print(f"M={steps:2}  rows={zrow:.12f}  columns={zcolumn:.12f}")
        else:
            print(f"M={steps:2}  rows={zrow:.12f}")
        if steps==4:
            offset = 0.3
            shifted_row = row_layer(np.exp(-beta*offset/steps)*local,length,0)
            shifted_row = shifted_row @ row_layer(np.exp(-beta*offset/steps)*local,length,1)
            zshift = np.trace(np.linalg.matrix_power(shifted_row,steps))
            assert abs(zshift/zrow-np.exp(-beta*offset*length)) < 2e-14
    assert abs(zrow-exact) < 3e-5
    assert np.trace(np.linalg.matrix_power(spatial_transfer(gate(0),2),length//2)) == 2**length


if __name__ == "__main__":
    check()
