"""Checks for the core article on factorized scattering in 1+1 dimensions.

Scalar amplitudes are tested for unitarity, crossing and their physical-strip poles; the
Lee-Yang self-fusion and the sine-Gordon breather masses test the bootstrap; the O(N)
vector amplitude is tested against the Yang-Baxter equation, which fails when its
crossing-fixed scale is changed. Run with Python 3, NumPy and mpmath:
    python3 factorized_scattering.py
"""
import itertools
import mpmath as mp
import numpy as np

mp.mp.dps = 40
I = mp.mpc(0, 1)
rng = np.random.default_rng(20261125)
SAMPLES = [mp.mpc(*map(float, rng.uniform(-2, 2, 2))) for _ in range(6)]


def block(alpha):
    """Elementary CDD block (sinh t + i sin a)/(sinh t - i sin a)."""
    return lambda t: (mp.sinh(t) + I * mp.sin(alpha)) / (mp.sinh(t) - I * mp.sin(alpha))


def close(a, b, tol=mp.mpf('1e-30')):
    return abs(a - b) < tol


AMPLITUDES = {
    'Ising (free Majorana)': lambda t: mp.mpf(-1),
    'scaling Lee-Yang': block(mp.pi / 3),
    'sinh-Gordon, b = 0.3': lambda t: 1 / block(mp.pi * mp.mpf('0.3'))(t),
    'sine-Gordon first breather, xi = 2/5': block(2 * mp.pi / 5),
}

checks = {}
for name, S in AMPLITUDES.items():
    checks[f'{name}: unitarity S(t)S(-t) = 1'] = all(close(S(t) * S(-t), 1) for t in SAMPLES)
    checks[f'{name}: crossing S(i pi - t) = S(t)'] = all(close(S(I * mp.pi - t), S(t)) for t in SAMPLES)
    checks[f'{name}: phase on the real axis'] = all(close(abs(S(mp.mpf(x))), 1) for x in (-1.3, 0.2, 2.7))

# Physical-strip poles: Lee-Yang has poles at i pi/3 and 2 i pi/3; sinh-Gordon has none.
LY = AMPLITUDES['scaling Lee-Yang']
res_direct = mp.limit(lambda e: e * LY(2 * I * mp.pi / 3 + e), 0)
checks['Lee-Yang direct pole residue = -2 sqrt(3) i (wrong sign, non-unitary)'] = close(res_direct, -2 * mp.sqrt(3) * I, mp.mpf('1e-15'))
res_cross = mp.limit(lambda e: e * LY(I * mp.pi / 3 + e), 0)
checks['Lee-Yang crossed pole residue = +2 sqrt(3) i'] = close(res_cross, 2 * mp.sqrt(3) * I, mp.mpf('1e-15'))
shG = AMPLITUDES['sinh-Gordon, b = 0.3']
grid = [mp.mpc(x, y) for x in np.linspace(-4, 4, 81) for y in np.linspace(0.01, float(mp.pi) - 0.01, 61)]
checks['sinh-Gordon has no pole in the open physical strip'] = max(abs(shG(t)) for t in grid) < 50

# Bootstrap: Lee-Yang is a bound state of itself at fusing angle 2 pi/3.
checks['Lee-Yang self-fusion: m^2 = 2m^2(1 + cos 2pi/3)'] = close(2 * (1 + mp.cos(2 * mp.pi / 3)), 1)
checks['Lee-Yang bootstrap S(t) = S(t + i pi/3) S(t - i pi/3)'] = all(
    close(LY(t), LY(t + I * mp.pi / 3) * LY(t - I * mp.pi / 3)) for t in SAMPLES)

# Sine-Gordon breathers: the pole at i pi xi of S_11 gives m_2 = 2 m_1 cos(pi xi / 2) = m_2 of the tower.
xi = mp.mpf(2) / 5
m1, m2 = 2 * mp.sin(mp.pi * xi / 2), 2 * mp.sin(mp.pi * xi)
checks['breather fusion mass m_2 = 2 m_1 cos(pi xi/2) matches 2M sin(pi xi)'] = close(
    mp.sqrt(2 * m1**2 * (1 + mp.cos(mp.pi * xi))), m2)

# CDD factors preserve both scalar equations.
cdd = lambda t: LY(t) * block(mp.pi / 5)(t)
checks['CDD factor preserves unitarity and crossing'] = all(
    close(cdd(t) * cdd(-t), 1) and close(cdd(I * mp.pi - t), cdd(t)) for t in SAMPLES)

# The bootstrap is stronger: the dressed Lee-Yang amplitude violates self-fusion.
def bootstrap_residual(S, t):
    return abs(S(t) - S(t + I * mp.pi / 3) * S(t - I * mp.pi / 3))
DRESSED_RESIDUAL = bootstrap_residual(cdd, mp.mpf('0.4'))
LY2 = lambda t: LY(t)**2
checks['Lee-Yang squared satisfies the self-fusion equation'] = all(bootstrap_residual(LY2, t) < mp.mpf('1e-30') for t in SAMPLES)
checks['but its pole at 2 i pi/3 is double, not a simple bound-state pole'] = (
    abs(mp.limit(lambda e: e**2 * LY2(2 * I * mp.pi / 3 + e), 0) - (-2 * mp.sqrt(3) * I)**2) < mp.mpf('1e-12'))
# The dressing adds poles at i pi/5 (residue -7.59i) and 4 i pi/5 (+7.59i, a lighter bound state)
# and changes the Lee-Yang direct residue to -18.1i.
dressed_res = {k: mp.limit(lambda e, k=k: e * cdd(I * k + e), 0) for k in (mp.pi / 5, 4 * mp.pi / 5, 2 * mp.pi / 3)}
checks['dressed residues: i pi/5 -> -7.59i, 4 i pi/5 -> +7.59i, 2 i pi/3 -> -18.1i'] = (
    abs(dressed_res[mp.pi / 5] + 7.5924j) < 1e-4 and abs(dressed_res[4 * mp.pi / 5] - 7.5924j) < 1e-4
    and abs(dressed_res[2 * mp.pi / 3] + 18.1j) < 1e-3)
checks['the positive dressed pole would be a particle of mass 2m cos(2 pi/5)'] = close(
    mp.sqrt(2 * (1 + mp.cos(4 * mp.pi / 5))), 2 * mp.cos(2 * mp.pi / 5))
# Sinh-Gordon is the first-breather amplitude continued to delta = -pi b: its strip poles become zeros.
checks['sinh-Gordon amplitude equals the breather block at delta = -pi b'] = all(
    close(AMPLITUDES['sinh-Gordon, b = 0.3'](t), block(-mp.pi * mp.mpf('0.3'))(t)) for t in SAMPLES)


# O(N) vector amplitude: S = I - (i lam/t) P + (i lam/(t - i pi)) K on V (x) V, V = C^N.
def onv(N, lam):
    d = N
    Id = np.eye(d * d, dtype=complex)
    P = np.zeros((d * d, d * d), dtype=complex)
    K = np.zeros((d * d, d * d), dtype=complex)
    for a, b in itertools.product(range(d), repeat=2):
        P[b * d + a, a * d + b] = 1
        if a == b:
            for c in range(d):
                K[c * d + c, a * d + a] = 1
    return lambda t: Id - (1j * lam / t) * P + (1j * lam / (t - 1j * np.pi)) * K


def embed(M, i, j, N):
    """Act with a two-site operator M on slots (i, j) of (C^N)^{(x)3}."""
    out = np.zeros((N**3, N**3), dtype=complex)
    for idx in itertools.product(range(N), repeat=3):
        for jdx in itertools.product(range(N), repeat=3):
            if any(idx[k] != jdx[k] for k in range(3) if k not in (i, j)):
                continue
            out[np.ravel_multi_index(idx, (N,) * 3), np.ravel_multi_index(jdx, (N,) * 3)] = M[idx[i] * N + idx[j], jdx[i] * N + jdx[j]]
    return out


def ybe_residual(N, lam, u=0.37 + 0.21j, v=-0.52 + 0.44j):
    S = onv(N, lam)
    lhs = embed(S(u), 0, 1, N) @ embed(S(u + v), 0, 2, N) @ embed(S(v), 1, 2, N)
    rhs = embed(S(v), 1, 2, N) @ embed(S(u + v), 0, 2, N) @ embed(S(u), 0, 1, N)
    return np.linalg.norm(lhs - rhs) / np.linalg.norm(lhs)


for N in (3, 4, 5):
    checks[f'O({N}) amplitude with lambda = 2 pi/(N-2) obeys Yang-Baxter'] = ybe_residual(N, 2 * np.pi / (N - 2)) < 1e-12

controls = {
    'Lee-Yang dressed by the pi/5 block violates self-fusion': DRESSED_RESIDUAL > mp.mpf('1e-3'),
    'O(3) amplitude with lambda scaled by 1.1 violates Yang-Baxter': ybe_residual(3, 1.1 * 2 * np.pi) > 1e-3,
    'exp(i t/2) is unitary and a real-axis phase but violates crossing': (
        all(close(mp.exp(I * t / 2) * mp.exp(-I * t / 2), 1) for t in SAMPLES)
        and not any(close(mp.exp(I * (I * mp.pi - t) / 2), mp.exp(I * t / 2)) for t in SAMPLES)),
}


def main():
    print('dressed Lee-Yang bootstrap residual at t = 0.4:', mp.nstr(DRESSED_RESIDUAL, 8))
    print('dressed Lee-Yang S(0.4):', mp.nstr(cdd(mp.mpf('0.4')), 8))
    print('product S(0.4 + i pi/3) S(0.4 - i pi/3):', mp.nstr(cdd(mp.mpf('0.4') + I * mp.pi / 3) * cdd(mp.mpf('0.4') - I * mp.pi / 3), 8))
    print('O(3) Yang-Baxter relative residual at the crossing value and at 1.1 times it:',
          f'{ybe_residual(3, 2 * np.pi):.2e}', f'{ybe_residual(3, 1.1 * 2 * np.pi):.2e}')
    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('All scattering identities hold; every altered input fails.')


if __name__ == '__main__':
    main()
