import numpy as np, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import z5cube as z

def test_characters_unitary():
    X = z.character_table(); assert np.allclose(X @ X.conj().T, np.eye(125))
    f = np.random.default_rng(0).normal(size=125)
    c = z.to_characters(f); assert np.allclose(c, X.conj() @ f)
    assert np.allclose(z.from_characters(c), f)

def test_fcc_spectrum():
    lam = np.sort(np.real(z.symbol(z.fcc_kernel())))
    exact = np.repeat([v[0] for v in z.fcc_spectrum_exact()], [v[3] for v in z.fcc_spectrum_exact()])
    assert np.allclose(lam, exact) and abs(lam[1] - z.GAP_FCC) < 1e-12
    assert np.allclose(np.sort(np.linalg.eigvalsh(z.fcc_laplacian())), lam)
    assert z.is_translation_invariant(z.fcc_laplacian())

def test_e47():
    P = z.P47(); assert np.allclose(P @ P, P) and round(np.trace(P)) == 47
    assert np.abs(z.selector_K() @ P).max() < 1e-8
    w = np.linalg.eigvalsh(z.selector_K() @ z.selector_K())
    assert abs(min(w[w > 1]) - 11664) < 1e-6 and abs(max(w) - 186624) < 1e-6
    assert not z.is_translation_invariant(P)   # E47 is NOT a union of characters

def test_coupled():
    rng = np.random.default_rng(1); F = rng.normal(size=(125, 125))
    PF = z.project_const_E47(F); assert np.allclose(z.project_const_E47(PF), PF)
    assert np.abs(z.apply_D(PF)).max() < 1e-6
    R = F - PF; assert z.rayleigh_D(R) >= z.GAP_D - 1e-9

def test_heat_bound():
    rng = np.random.default_rng(2); F = rng.normal(size=(125, 125))
    ts = np.linspace(0, 3, 13); h = z.heat_residual_curve(F, ts)
    assert abs(h[0] - np.linalg.norm(F - z.project_const_E47(F))) < 1e-8
    assert np.all(h <= np.exp(-ts * z.GAP_D) * h[0] * (1 + 1e-12))

if __name__ == "__main__":
    for n, t in list(globals().items()):
        if n.startswith("test_"): t(); print("PASS", n)
