#!/usr/bin/env python3
"""
Computation 55 -- Closed-form sigma_2 = D - 2 of the Walsh-tail off-diagonal block
===================================================================================
This completes Lemma 2-prime by exhibiting an explicit pair of vectors

    u_1  :=  |e_0>  -  (1 / D) sum_{a = 0}^{D-1} |e_a>     in [D-1, 1] cap H_1,
    u_2  := - sum_{b = 1}^{D-1} |{0, b}>                   in [D-1, 1] cap H_2,

(both S_{D-1}-fixed under the fermionic-signed S_D representation
rho_F, which is the representation that commutes with D_sub) and
verifying analytically that

    M  :=  matrix of T_pm = P_+ T_tail P_- on span(u_1, u_2)/normed

reduces to a rank-1 (D - 2)/2 . [[-1, +1], [-1, +1]] matrix whose
singular values are (D - 2, 0).

Combined with Comp 52's closed form sigma_1 = 2^(D-1) - D on the
trivial S_D component, this proves
    || P_+ T_tail P_- ||_op  =  2^(D-1) - D     exactly for all D >= 4,
because the exponential gap dominates: for D >= 4, 2^(D-1) - D >> D - 2.

Method
------
Verify the algebraic identities used by the closed form, to machine
precision, for D in {4, 5, 6, 7, 8}:
    (a)  D_sub u_1  =  u_2
    (b)  D_sub u_2  =  D * u_1     (weight-3 leakage cancels exactly)
    (c)  T_tail u_1 = beta * u_1   with beta = - binom(D-1, 2)
    (d)  T_tail u_2 = gamma * u_2  with gamma = (D-2)(5-D)/2
Then check
    (e)  M_analytic  =  (D-2)/2  *  [[-1, +1], [-1, +1]]
matches M_numerical (machine precision), and that the saturating
right singular vector v_star = (-e_1 + e_2)/sqrt(2) gives
    || T_pm v_star ||  =  (D - 2) || v_star ||     exactly.
"""
import math
import numpy as np
import numpy.linalg as la


def popcount(x):
    c = 0
    while x:
        c += x & 1
        x >>= 1
    return c


def build_T_tail_diagonal(D, kD):
    """T_tail = sum_{|S| > kD} chi_S is diagonal in the computational basis."""
    c_by_weight = []
    for w in range(D + 1):
        total = 0
        for j in range(kD + 1, D + 1):
            kraw = 0
            for i in range(0, min(w, j) + 1):
                if j - i <= D - w:
                    kraw += ((-1) ** i) * math.comb(w, i) * math.comb(D - w, j - i)
            total += kraw
        c_by_weight.append(total)
    dim = 1 << D
    return np.array([c_by_weight[popcount(x)] for x in range(dim)], dtype=complex)


def build_D_sub(D):
    """D_sub = sum_a chi_a^Cliff via Jordan-Wigner."""
    n = 1 << D
    M = np.zeros((n, n), dtype=complex)
    for a in range(D):
        for x in range(n):
            xp = x ^ (1 << a)
            sign = 1
            for b in range(a):
                if (x >> b) & 1:
                    sign *= -1
            M[xp, x] += sign
    return M


def spectral_projectors(D_sub_mat, D):
    n = D_sub_mat.shape[0]
    sqrtD = math.sqrt(D)
    Pp = (np.eye(n, dtype=complex) + D_sub_mat / sqrtD) / 2.0
    Pm = (np.eye(n, dtype=complex) - D_sub_mat / sqrtD) / 2.0
    return Pp, Pm


def main():
    print("=" * 90)
    print("  Computation 55  --  Closed-form sigma_2 = D - 2 of the Walsh-tail block")
    print("=" * 90)
    print()
    print("  Explicit S_{D-1}-fixed input vectors:")
    print("    u_1 = |e_0> - (1/D) sum_a |e_a>          in [D-1, 1] cap H_1")
    print("    u_2 = -sum_{b > 0} |{0, b}>              in [D-1, 1] cap H_2")
    print()
    print("  Verify algebraic identities, then verify || M_analytic - M_numerical ||")
    print("  and the closed-form sigma_max = D - 2.")
    print()

    kD = 2
    print(f"  {'D':>3}  {'D_sub u1=u2':>15}  {'D_sub u2=D u1':>15}  "
          f"{'T u1=beta u1':>14}  {'T u2=gamma u2':>15}  "
          f"{'||M_a - M_n||':>14}  {'sigma_max':>12}  {'target':>8}")
    for D in range(4, 9):
        n = 1 << D
        D_mat = build_D_sub(D)
        T_tail_diag = build_T_tail_diagonal(D, kD)
        T_tail = np.diag(T_tail_diag)
        Pp, Pm = spectral_projectors(D_mat, D)
        T_pm = Pp @ T_tail @ Pm

        # Build u_1, u_2
        u1 = np.zeros(n, dtype=complex)
        for a in range(D):
            u1[1 << a] = -1.0 / D
        u1[1] += 1.0
        u2 = np.zeros(n, dtype=complex)
        for b in range(1, D):
            u2[(1 << 0) | (1 << b)] = -1.0

        # Identities (a)-(d):
        err_a = la.norm(D_mat @ u1 - u2)
        err_b = la.norm(D_mat @ u2 - D * u1)
        beta = -math.comb(D - 1, 2)
        gamma = (D - 2) * (5 - D) / 2
        err_c = la.norm(T_tail @ u1 - beta * u1)
        err_d = la.norm(T_tail @ u2 - gamma * u2)

        # Normalize:
        e1 = u1 / la.norm(u1)
        e2 = u2 / la.norm(u2)

        # Numerical M:
        basis = np.stack([e1, e2], axis=1)
        M_num = basis.conj().T @ T_pm @ basis

        # Analytical M:
        M_ana = (D - 2) / 2.0 * np.array([[-1.0, 1.0], [-1.0, 1.0]], dtype=complex)
        err_M = la.norm(M_num - M_ana)

        # Saturating right singular vector:
        v_star = (e2 - e1) / math.sqrt(2)
        sigma_max = la.norm(T_pm @ v_star) / la.norm(v_star)

        print(f"  {D:>3}  {err_a:>15.2e}  {err_b:>15.2e}  "
              f"{err_c:>14.2e}  {err_d:>15.2e}  "
              f"{err_M:>14.2e}  {sigma_max:>12.6f}  {D-2:>8}")

    print()
    print("=" * 90)
    print("  Findings")
    print("=" * 90)
    print()
    print("  (a) D_sub u_1 = u_2 and D_sub u_2 = D u_1 are exact identities (no")
    print("      weight-3 leakage in D_sub u_2 because each triple {0, b, c}")
    print("      receives contributions +|{0,b,c}> and -|{0,b,c}> from the (b, c)")
    print("      and (c, b) JW orderings that cancel).")
    print()
    print("  (b) T_tail u_1 = beta u_1 (weight-1) and T_tail u_2 = gamma u_2")
    print("      (weight-2) follow from T_tail being diagonal in the computational")
    print("      basis with eigenvalues depending only on Hamming weight.")
    print()
    print("  (c) The 2-x-2 multiplicity-space matrix")
    print()
    print("           M = (D-2)/2  .  [[-1, +1], [-1, +1]]")
    print()
    print("      is RANK 1, with sigma values (D - 2, 0).  Combined with the")
    print("      closed form sigma_1 = 2^(D-1) - D on the trivial S_D-component")
    print("      (Comp 52) and the vanishing of all higher 2-row irreps under")
    print("      the fermionic rho_F (Comp 54), the operator norm of the")
    print("      Walsh-tail off-diagonal block is")
    print()
    print("           ||  P_+ T_tail P_-  ||_op  =  2^(D-1) - D     exactly,")
    print()
    print("      for every D >= 4 at k_D = 2.")


if __name__ == "__main__":
    main()
