"""Checks for the Library article "The Yang–Baxter equation and commuting transfer matrices".

Zero-field eight-vertex R-matrix in the basis uu, ud, du, dd, as in the Library article
"Rational, trigonometric and elliptic R-matrices":
    R = [[a, 0, 0, d], [0, b, c, 0], [0, c, b, 0], [d, 0, 0, a]],
with Baxter's elliptic weights a = sn(u + eta)/sn(eta), b = sn(u)/sn(eta), c = 1 and
d = k sn(u) sn(u + eta), Jacobi parameter m = k^2. The periodic transfer matrix is
tau(u) = tr_a R_{aN}(u) ... R_{a1}(u) on N spins.

1. Invariants. Delta = (a^2 + b^2 - c^2 - d^2)/(2(ab + cd)) and Gamma = (ab - cd)/(ab + cd) are the
   same at every u, with Delta = cn(eta) dn(eta)/(1 + k sn(eta)^2) and
   Gamma = (1 - k sn(eta)^2)/(1 + k sn(eta)^2).
2. The Yang–Baxter equation R12(u - v) R13(u) R23(v) = R23(v) R13(u) R12(u - v).
3. Commuting transfer matrices on N = 4, 5, 6 sites, also for weights on the same (Delta, Gamma)
   curve that are produced by solving for them rather than by the parametrization.
4. Intertwiners. The 4x4 matrices X with X R_an(w) R_bn(w') = R_bn(w') R_an(w) X form a
   one-dimensional space when w and w' share (Delta, Gamma), spanned by R(u - v) on the family.
5. The XYZ chain. H = sum_n (Jx sx sx + Jy sy sy + Jz sz sz) with Jx : Jy : Jz = 1 : Gamma : Delta
   commutes with every tau(u). The logarithmic derivative of tau at the regular point u = 0 is
   exactly the sum of P R'(0) over the bonds, which has these ratios.
6. Twists. tr_a K_a T_a(u) still commute when K x K commutes with R: K = sigma^z for eight vertices,
   any diagonal K for six vertices.
Controls: weights with Delta moved by 5 percent (Gamma fixed) give noncommuting transfer matrices
and no intertwiner; Jz scaled by 1.1 does not commute; a diagonal phase twist breaks the eight-vertex
family. The six-vertex limit k -> 0 gives Gamma = 1 and Delta = cos(eta).
Run with Python 3, NumPy and SciPy:  python3 commuting_family.py
"""
import numpy as np
from scipy.special import ellipj

K_MOD, ETA = 0.5, 0.9          # modulus k (Jacobi parameter k^2) and crossing parameter
SAMPLES = (0.2, 0.5, 0.8)      # spectral parameters with positive weights


def jac(u, k=K_MOD):
    sn, cn, dn, _ = ellipj(u, k**2)
    return sn, cn, dn


def weights(u, k=K_MOD, eta=ETA):
    s_eta = jac(eta, k)[0]
    a = jac(u + eta, k)[0] / s_eta
    b = jac(u, k)[0] / s_eta
    d = k * jac(u, k)[0] * jac(u + eta, k)[0]
    return np.array([a, b, 1.0, d])


def r_matrix(w):
    a, b, c, d = w
    return np.array([[a, 0, 0, d], [0, b, c, 0], [0, c, b, 0], [d, 0, 0, a]], dtype=complex)


def invariants(w):
    a, b, c, d = w
    return (a * a + b * b - c * c - d * d) / (2 * (a * b + c * d)), (a * b - c * d) / (a * b + c * d)


def closed_form_invariants(k=K_MOD, eta=ETA):
    sn, cn, dn = jac(eta, k)
    return cn * dn / (1 + k * sn**2), (1 - k * sn**2) / (1 + k * sn**2)


def weights_on_curve(delta, gamma, a, b):
    """Weights (a, b, c, d) with the given invariants, solving for c and d."""
    cd = a * b * (1 - gamma) / (1 + gamma)
    s = a * a + b * b - 2 * delta * (a * b + cd)          # c^2 + d^2
    disc = np.sqrt(complex(s * s - 4 * cd * cd))
    c2, d2 = (s + disc) / 2, (s - disc) / 2
    c = np.sqrt(c2)
    return np.array([a, b, c, cd / c])


def embed(M, i, j, n):
    """The 2^n x 2^n operator acting with the 4x4 matrix M on tensor factors i, j (in that order)."""
    dim = 2**n
    T = np.eye(dim, dtype=complex).reshape([2] * n + [dim])
    T = np.moveaxis(T, (i, j), (0, 1))
    T = np.tensordot(M.reshape(2, 2, 2, 2), T, axes=([2, 3], [0, 1]))
    return np.moveaxis(T, (0, 1), (i, j)).reshape(dim, dim)


def transfer(w, n_sites, derivative_at=None, twist=None):
    """tau = tr_a K_a R_{aN} ... R_{a1}; factor 0 is auxiliary and K = twist (identity if None).
    With derivative_at = (R0, R0prime), return the product-rule derivative sum_n tr_a(... R'_{an} ...)."""
    n = n_sites + 1
    dim = 2**n_sites
    if derivative_at is None:
        mats = [[embed(r_matrix(w), 0, s, n) for s in range(1, n)]]
    else:
        R0, R1 = derivative_at
        mats = [[embed(R1 if s == t else R0, 0, s, n) for s in range(1, n)] for t in range(1, n)]
    total = np.zeros((dim, dim), complex)
    for row in mats:
        T = np.eye(2 * dim, dtype=complex)
        for M in row:                      # site 1 acts first, so it is the rightmost factor
            T = M @ T
        if twist is not None:
            T = np.kron(twist, np.eye(dim)) @ T
        total += np.trace(T.reshape(2, dim, 2, dim), axis1=0, axis2=2)
    return total


PAULI = {'x': np.array([[0, 1], [1, 0]], complex), 'y': np.array([[0, -1j], [1j, 0]], complex),
         'z': np.array([[1, 0], [0, -1]], complex)}


def xyz_hamiltonian(J, n_sites):
    h = sum(Jc * np.kron(PAULI[c], PAULI[c]) for Jc, c in zip(J, 'xyz'))
    return sum(embed(h, s, (s + 1) % n_sites, n_sites) for s in range(n_sites))


def rel_comm(A, B):
    return np.linalg.norm(A @ B - B @ A) / (np.linalg.norm(A) * np.linalg.norm(B))


def intertwiner_dimension(w1, w2, tol=1e-9):
    """Dimension of {X : X_ab R_an(w1) R_bn(w2) = R_bn(w2) R_an(w1) X_ab} on factors (a, b, n)."""
    A, B = embed(r_matrix(w1), 0, 2, 3), embed(r_matrix(w2), 1, 2, 3)
    left, right = A @ B, B @ A
    columns = []
    for idx in range(16):
        E = np.zeros(16, complex)
        E[idx] = 1
        X = embed(E.reshape(4, 4), 0, 1, 3)
        columns.append((X @ left - right @ X).ravel())
    s = np.linalg.svd(np.array(columns).T, compute_uv=False)
    return int(np.sum(s < tol * s[0])), s


def ybe_residual(u, v):
    R = lambda x, i, j: embed(r_matrix(weights(x)), i, j, 3)
    lhs = R(u - v, 0, 1) @ R(u, 0, 2) @ R(v, 1, 2)
    rhs = R(v, 1, 2) @ R(u, 0, 2) @ R(u - v, 0, 1)
    return np.linalg.norm(lhs - rhs) / np.linalg.norm(lhs)


def commutator_scan(n_sites, delta_values, u=0.5, v=0.2):
    """Relative commutator of tau(w(u)) with weights sharing Gamma and (a, b) of w(v) but given Delta."""
    gamma = closed_form_invariants()[1]
    tau = transfer(weights(u), n_sites)
    a, b = weights(v)[:2]
    return np.array([rel_comm(tau, transfer(weights_on_curve(D, gamma, a, b), n_sites)) for D in delta_values])


def main():
    delta, gamma = closed_form_invariants()
    print(f'k = {K_MOD}, eta = {ETA}: Delta = {delta:.12f}, Gamma = {gamma:.12f}')
    checks, controls = {}, {}

    inv = np.array([invariants(weights(u)) for u in SAMPLES])
    print('weights (a, b, c, d) at u =', SAMPLES)
    for u in SAMPLES:
        print('   ', np.round(weights(u), 10))
    checks['Delta and Gamma are the same at every u and match the closed forms'] = (
        np.allclose(inv[:, 0], delta, atol=1e-13) and np.allclose(inv[:, 1], gamma, atol=1e-13))

    ybe = max(ybe_residual(u, v) for u in SAMPLES for v in SAMPLES if u != v)
    print(f'Yang–Baxter residual, relative: {ybe:.1e}')
    checks['Yang–Baxter equation holds (1e-13)'] = ybe < 1e-13

    solved = weights_on_curve(delta, gamma, 1.3, 0.4)
    print('solved weights on the same curve:', np.round(solved.real, 10), 'invariants', np.round(invariants(solved), 12))
    worst = 0.0
    for N in (4, 5, 6):
        taus = [transfer(weights(u), N) for u in SAMPLES] + [transfer(solved, N)]
        worst = max(worst, max(rel_comm(A, B) for i, A in enumerate(taus) for B in taus[i + 1:]))
    print(f'largest relative commutator among tau(0.2), tau(0.5), tau(0.8) and the solved weights, N = 4, 5, 6: {worst:.1e}')
    checks['transfer matrices on one curve commute (1e-13)'] = worst < 1e-13

    off = weights_on_curve(1.05 * delta, gamma, *weights(0.2)[:2])
    off_comm = max(rel_comm(transfer(weights(0.5), N), transfer(off, N)) for N in (4, 5, 6))
    print(f'Delta moved by 5 percent: invariants {np.round(invariants(off), 6)}, relative commutator {off_comm:.1e}')
    controls['weights with Delta moved by 5 percent do not commute'] = off_comm > 1e-4

    dim_on, s_on = intertwiner_dimension(weights(0.5), weights(0.2))
    dim_off, s_off = intertwiner_dimension(weights(0.5), off)
    X = r_matrix(weights(0.3))
    A, B = embed(r_matrix(weights(0.5)), 0, 2, 3), embed(r_matrix(weights(0.2)), 1, 2, 3)
    Xf = embed(X, 0, 1, 3)
    rx = np.linalg.norm(Xf @ A @ B - B @ A @ Xf) / np.linalg.norm(Xf @ A @ B)
    print(f'intertwiner space: dimension {dim_on} on the curve (R(0.3) solves it to {rx:.1e}); '
          f'dimension {dim_off} off it, smallest singular value {s_off[-1] / s_off[0]:.1e}')
    checks['intertwiners on the curve form a line spanned by R(u - v)'] = dim_on == 1 and rx < 1e-13
    controls['no intertwiner when Delta is moved by 5 percent'] = dim_off == 0

    J = np.array([1.0, gamma, delta])
    xyz = max(rel_comm(xyz_hamiltonian(J, N), transfer(weights(u), N)) for N in (4, 5, 6) for u in SAMPLES)
    bad = max(rel_comm(xyz_hamiltonian(J * [1, 1, 1.1], N), transfer(weights(0.5), N)) for N in (4, 5, 6))
    print(f'XYZ with Jx:Jy:Jz = 1:Gamma:Delta, largest relative commutator with tau: {xyz:.1e}; with Jz x 1.1: {bad:.1e}')
    checks['XYZ chain with 1:Gamma:Delta commutes with every tau (1e-13)'] = xyz < 1e-13
    controls['XYZ with Jz scaled by 1.1 does not commute'] = bad > 1e-4

    sn, cn, dn = jac(ETA)
    R0 = r_matrix(weights(0.0))
    R1 = r_matrix(np.array([cn * dn / sn, 1 / sn, 0.0, K_MOD * sn]))   # dR/du at u = 0
    Pm = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], complex)
    h = Pm @ R1
    # P R'(0) = alpha I + Jx sx sx + Jy sy sy + Jz sz sz with Jx = (b'+d')/2, Jy = (b'-d')/2, Jz = (a'-c')/2.
    Jx, Jy, Jz = (R1[1, 1] + R1[0, 3]).real / 2, (R1[1, 1] - R1[0, 3]).real / 2, (R1[0, 0] - R1[1, 2]).real / 2
    worst_log = 0.0
    for N in (4, 5, 6):
        tau0, dtau = transfer(weights(0.0), N), transfer(None, N, derivative_at=(R0, R1))
        log_derivative = np.linalg.solve(tau0, dtau)
        bonds = sum(embed(h, s, (s + 1) % N, N) for s in range(N))
        worst_log = max(worst_log, np.linalg.norm(log_derivative - bonds) / np.linalg.norm(bonds))
        if N == 4:
            shift_error = np.linalg.norm(tau0 @ tau0 @ tau0 @ tau0 - np.eye(16))
    print(f'regular point: R(0) = P to {np.linalg.norm(R0 - Pm):.1e}; tau(0)^4 = I on four sites to {shift_error:.1e}')
    print(f'log derivative minus sum of P R\'(0) on bonds, relative: {worst_log:.1e}')
    print(f'bond couplings Jx, Jy, Jz = {Jx:.10f}, {Jy:.10f}, {Jz:.10f}; Jy/Jx = {Jy / Jx:.12f}, Jz/Jx = {Jz / Jx:.12f}')
    checks['R(0) = P and tau(0) is the cyclic shift'] = np.linalg.norm(R0 - Pm) < 1e-14 and shift_error < 1e-12
    checks['log derivative at u = 0 is the sum of P R\'(0) over bonds (1e-12)'] = worst_log < 1e-12
    checks['bond couplings have ratios 1:Gamma:Delta'] = abs(Jy / Jx - gamma) < 1e-12 and abs(Jz / Jx - delta) < 1e-12

    # Twists: K_a K_b must commute with R_ab. sigma^z does for eight vertices; diag(e^{i phi}, e^{-i phi})
    # does only when d = 0 (six vertices), because K x K multiplies |uu> and |dd> by different phases.
    Kz, Kphi = PAULI['z'], np.diag([np.exp(0.3j), np.exp(-0.3j)])
    six = lambda u: weights(u, k=0.0)
    tw_z = max(rel_comm(transfer(weights(0.5), N, twist=Kz), transfer(weights(0.2), N, twist=Kz)) for N in (4, 5))
    tw_six = max(rel_comm(transfer(six(0.5), N, twist=Kphi), transfer(six(0.2), N, twist=Kphi)) for N in (4, 5))
    tw_bad = max(rel_comm(transfer(weights(0.5), N, twist=Kphi), transfer(weights(0.2), N, twist=Kphi)) for N in (4, 5))
    print(f'twisted families: sigma^z on eight vertices {tw_z:.1e}; diagonal phase 0.3 on six vertices {tw_six:.1e}, '
          f'on eight vertices {tw_bad:.1e}')
    checks['sigma^z-twisted eight-vertex and phase-twisted six-vertex families commute (1e-13)'] = tw_z < 1e-13 and tw_six < 1e-13
    controls['a diagonal phase twist breaks the eight-vertex family'] = tw_bad > 1e-4

    d6, g6 = closed_form_invariants(k=0.0)
    print(f'six-vertex limit k = 0: Delta = {d6:.12f} = cos(eta) = {np.cos(ETA):.12f}, Gamma = {g6}')
    checks['k -> 0 gives the six-vertex values Delta = cos(eta), Gamma = 1'] = abs(d6 - np.cos(ETA)) < 1e-14 and g6 == 1.0

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('Baxter\'s commuting family, its intertwiners and the XYZ chain check out; every control fails.')


if __name__ == '__main__':
    main()
