"""Z5^3 (125-site) lattice, FCC Laplacian, E47 projector and gap -- importable helpers.

Conventions follow nicholaskouns-create/E47-Kartekeya
  website/interfaces/fcc-e47-spatial-lift/{index.html,fcc_e47_validation.py} @ e9be2dee:
  * sites = itertools.product(range(5), repeat=3), flat index pi(x,y,z) = 25x + 5y + z
  * spatial H_s = l2(Z5^3), FCC Laplacian with S = {e1,e2,e3,e1-e2,e1-e3,e2-e3}, Delta = S u -S (12 nbrs)
      lambda(w) = 2 sum_{s in S} [1 - cos(2 pi w.s/5)],  gap gamma = (15 - 3 sqrt5)/2 (mult 8)
  * internal H_i = V2 (x) V2 (x) V2, same site index with m_j = k_j - 2, C = (J1+J2+J3)^2,
      K = (C-6I)(C-30I), B = K^2, E47 = ker B = 5V2 + 2V5, P47 = 1_{0}(B)
  * D = L (x) I + I (x) B on C^15625, ker D = <u0> (x) E47, ||exp(-tD) - P0||_2 = exp(-t gamma)
  * discrete internal contraction Gamma = I - K^2/99144, ||Gamma^n - P47||_2 = (15/17)^n
"""
from itertools import product
import numpy as np

N = 5
SITES = np.array(list(product(range(N), repeat=3)))           # (125,3), lexicographic = 25x+5y+z
S_DIRS = np.array([[1,0,0],[0,1,0],[0,0,1],[1,-1,0],[1,0,-1],[0,1,-1]])
GAMMA_EXACT = (15 - 3*np.sqrt(5)) / 2                          # 4.145898033750315
LAMBDA_MAX = (25 + 3*np.sqrt(5)) / 2
RHO_DISCRETE = 15/17
EPS_DISCRETE = 1/99144


def site_index(x, y, z):
    return 25*np.asarray(x) + 5*np.asarray(y) + np.asarray(z)


def fcc_laplacian():
    """Dense 125x125 FCC graph Laplacian on Z5^3 (degree 12)."""
    L = 12*np.eye(125)
    for c, s in enumerate(SITES):
        for d in S_DIRS:
            for sg in (-1, 1):
                L[site_index(*((s + sg*d) % N)), c] -= 1
    return L


def fcc_eigenvalues():
    """lambda(w) for w in SITES order (Z5^3 characters chi_w(x)=exp(2 pi i w.x/5)/sqrt125)."""
    ws = SITES @ S_DIRS.T
    return 2*np.sum(1 - np.cos(2*np.pi*ws/N), axis=1)


def character_transform(f):
    """Unitary Z5^3 Fourier coefficients <chi_w, f> for f in SITES order; returns (125,) complex in SITES order."""
    return np.fft.fftn(np.asarray(f).reshape(5, 5, 5), norm="ortho").reshape(125)


def spin2_ops():
    m = np.arange(2, -3, -1).astype(float)                    # |2>,|1>,...,|-2>
    jz = np.diag(m)
    jp = np.zeros((5, 5))
    for i in range(1, 5):
        jp[i-1, i] = np.sqrt(6 - m[i]*(m[i]+1))
    jx = (jp + jp.T)/2
    jy = (jp - jp.T)/(2j)
    return jx, jy, jz


def casimir_internal():
    """Total Casimir C on V2^{(x)3} in the orthonormal basis indexed like SITES with m_j = k_j - 2.

    Basis vector for site (k1,k2,k3) is |m1=k1-2> (x) |m2=k2-2> (x) |m3=k3-2>.
    """
    jx, jy, jz = spin2_ops()
    # reorder single-spin basis so that index k corresponds to m = k-2
    perm = [4, 3, 2, 1, 0]
    ops = []
    for j in (jx, jy, jz):
        j = j[np.ix_(perm, perm)]
        I = np.eye(5)
        ops.append(np.kron(np.kron(j, I), I) + np.kron(np.kron(I, j), I) + np.kron(np.kron(I, I), j))
    C = sum(o @ o for o in ops)
    assert np.allclose(C.imag, 0, atol=1e-12)
    return C.real


def internal_operators():
    """Return dict with C, K, B=K^2, P47 (orthogonal projector onto ker K), Gamma = I - K^2/99144."""
    C = casimir_internal()
    I = np.eye(125)
    K = (C - 6*I) @ (C - 30*I)
    B = K @ K
    evals, U = np.linalg.eigh(C)
    c = np.rint(evals).astype(int)
    assert np.allclose(evals, c, atol=1e-9)
    ker = (c == 6) | (c == 30)
    Q = U[:, ker]
    P47 = Q @ Q.T
    return dict(C=C, K=K, B=B, P47=P47, Q=Q, Gamma=I - B*EPS_DISCRETE,
                casimir_eigs=c, casimir_vecs=U, b_eigs=((c-6)*(c-30))**2.0)


def residual_curve(psi, lam_s, Us, beta_i, Ui, ts):
    """Spectral-formula residual ||exp(-tD) psi - P0 psi|| for psi a (125,125) matrix (rows spatial, cols internal)."""
    coef = Us.T @ psi @ Ui
    rate = lam_s[:, None] + beta_i[None, :]
    mask = rate > 1e-9
    w2 = np.abs(coef[mask])**2
    r = rate[mask]
    return np.array([np.sqrt(np.sum(w2*np.exp(-2*t*r))) for t in ts])


def cubic_laplacian():
    """Periodic nearest-neighbour (degree-6) Laplacian on Z5^3: L = 6I - sum_a (S_a + S_a^T)."""
    L = 6*np.eye(125)
    for c, s in enumerate(SITES):
        for d in np.eye(3, dtype=int):
            for sg in (-1, 1):
                L[site_index(*((s + sg*d) % N)), c] -= 1
    return L


def compressed_gap(L, Q):
    """lambda_min(Q^T L Q): the spatial Laplacian compressed onto E47 under the identification
    site index == internal basis index (the 'B = Q^T L Q' construction in the
    e47-invariant-transport-gradient note). Different object from the gap of D."""
    return float(np.linalg.eigvalsh(Q.T @ L @ Q)[0])
