"""Finite six-vertex rows, a perturbed torus, and local spin-chain charges.

Requires Python 3 and NumPy. Site 0 is the leftmost tensor factor;
the auxiliary state crosses sites in increasing order.
"""

from itertools import combinations, product
from math import cos, pi, sin

import numpy as np


def vertex(a, b, c):
    return np.array([[a, 0, 0, 0], [0, b, c, 0],
                     [0, c, b, 0], [0, 0, 0, a]])


def row(vertices):
    """Trace the two-dimensional auxiliary index at fixed lower and upper arrows."""
    states = list(product((0, 1), repeat=len(vertices)))
    transfer = np.zeros((len(states), len(states)), dtype=np.result_type(*vertices))
    for col, lower in enumerate(states):
        for ix, upper in enumerate(states):
            horizontal = np.eye(2, dtype=transfer.dtype)
            for R, top, bottom in zip(vertices, upper, lower):
                horizontal = R[top::2, bottom::2] @ horizontal
            transfer[ix, col] = horizontal.trace()
    return transfer


def direct_torus(R):
    """Sum all 2^8 edge assignments on a 2-by-2 torus."""
    counts = {}
    for edges in product((0, 1), repeat=8):
        horizontal = np.array(edges[:4]).reshape(2, 2)
        vertical = np.array(edges[4:]).reshape(2, 2)
        weight = 1
        marked = False
        for y, x in product(range(2), repeat=2):
            # Stored variables point away from their vertex to the right and above.
            left, right = horizontal[y, x - 1], horizontal[y, x]
            lower, upper = vertical[y - 1, x], vertical[y, x]
            weight *= R[2 * right + upper, 2 * left + lower]
            if (y, x) == (0, 0):
                marked = (left, right, lower, upper) == (0, 0, 0, 0)
        if weight:
            counts[marked, int(weight)] = counts.get((marked, int(weight)), 0) + 1
    return counts


def torus_check():
    R = vertex(2, 1, 3)
    configs = direct_torus(R)
    raw = sum(w * n for (_, w), n in configs.items())
    affected = {w: n for (marked, w), n in configs.items() if marked}
    perturbed = R.copy()
    perturbed[0, 0] *= 2
    T = row([R, R])
    assert sum(configs.values()) == 18
    assert raw == np.trace(T @ T) == 244
    assert affected == {16: 1, 4: 3}
    assert np.trace(row([perturbed, R]) @ T) == raw + sum(w*n for w, n in affected.items()) == 272
    print("2x2 torus: 18 allowed assignments; Z=244; marked all-up vertex doubled: Z=272")


def finite_operators(L, delta):
    states = list(product((0, 1), repeat=L))
    index = {s: i for i, s in enumerate(states)}
    shift = np.zeros((2**L, 2**L))
    bonds = [np.zeros_like(shift) for _ in range(L)]
    swaps = [np.zeros_like(shift) for _ in range(L)]
    for i, s in enumerate(states):
        shift[index[(s[-1],) + s[:-1]], i] = 1
        for j in range(L):
            k = (j + 1) % L
            moved = list(s)
            moved[j], moved[k] = moved[k], moved[j]
            target = index[tuple(moved)]
            swaps[j][target, i] = 1
            if s[j] != s[k]:
                bonds[j][i, i] -= delta / 2
                bonds[j][target, i] += 1 / 2
    return states, shift, bonds, swaps


def insertions(base, derivative, L, sites):
    return row([derivative if i in sites else base for i in range(L)])


def xxz_check():
    L, eta = 4, pi / 3
    a, d = sin(eta), cos(eta)
    R = vertex(a, 0, a)
    Rp = vertex(d, 1, 0)
    transfer = row([R] * L)
    derivative = sum(insertions(R, Rp, L, [i]) for i in range(L))
    states, shift, bonds, _ = finite_operators(L, d)
    identity = np.eye(2**L)
    H = (a / 2) * np.linalg.solve(transfer, derivative) - (L * d / 2) * identity
    direct = sum(bonds)
    assert np.linalg.norm(transfer - a**L * shift, np.inf) < 1e-13
    assert np.linalg.norm(H - direct, np.inf) < 1e-13
    psi = np.array([(-1)**s.index(1) / 2 if sum(s) == 1 else 0 for s in states])
    assert np.linalg.norm(H[:, 0]) < 1e-13 and np.linalg.norm(H @ psi + 1.5 * psi) < 1e-13
    print("L=4 XXZ: full-matrix row/bond infinity-norm error", np.linalg.norm(H-direct, np.inf))
    print("E(all up)=0, E(pi one-flip)=-1.5")


def xxx_charge_check():
    L = 5
    _, shift, _, Ps = finite_operators(L, 1)
    P = vertex(1, 0, 1)
    identity = np.eye(4)
    first = shift.T @ sum(insertions(P, identity, L, (i,)) for i in range(L))
    second = shift.T @ (2 * sum(insertions(P, identity, L, pair)
                                for pair in combinations(range(L), 2)))
    oriented = sum(Ps[j] @ Ps[(j+1) % L] - Ps[(j+1) % L] @ Ps[j] for j in range(L))
    connected = second - first @ first + L * np.eye(2**L)
    assert np.array_equal(first, sum(Ps))
    assert np.array_equal(connected, -oriented)
    assert np.array_equal(first @ oriented, oriented @ first)
    print("L=5 XXX: logarithmic second derivative and energy-current commutator exact")


if __name__ == "__main__":
    torus_check()
    xxz_check()
    xxx_charge_check()
