"""Checks for the core article on multidimensional consistency of quad equations.

1. H1 and Q1 (with delta) are consistent around the cube and have the tetrahedron property;
   a perturbed H1 is not.
2. The third (Backlund) direction maps the H1 vacuum u = a n + b m to a one-soliton
   u + c (1 + r)/(1 - r), r = r0 ((a+c)/(a-c))^n ((b+c)/(b-c))^m, with p = k - a^2,
   q = k - b^2 and spectral parameter lambda = k - c^2; the result solves H1 exactly.
Run with Python 3 and SymPy:  python3 consistency_core.py
"""
import sympy as sp

x, a_, b_, c_, p, q, r = sp.symbols('x a b c p q r')


def solve_corner(Q, unknown):
    sol = sp.solve(sp.Eq(Q, 0), unknown)
    assert len(sol) == 1, sol
    return sol[0]


def cube_check(face, params):
    """Return (consistent, tetrahedron) for a face law face(x, u, v, z, p, q)."""
    X, A, B, C = sp.symbols('X A B C')
    P, Qp, R = params
    z = sp.Symbol('z')
    u12 = solve_corner(face(X, A, B, z, P, Qp), z)
    u13 = solve_corner(face(X, A, C, z, P, R), z)
    u23 = solve_corner(face(X, B, C, z, Qp, R), z)
    za = solve_corner(face(A, u12, u13, z, Qp, R), z)
    zb = solve_corner(face(B, u12, u23, z, P, R), z)
    zc = solve_corner(face(C, u13, u23, z, P, Qp), z)
    consistent = sp.simplify(za - zb) == 0 and sp.simplify(za - zc) == 0
    tetrahedron = sp.simplify(sp.diff(sp.simplify(za), X)) == 0
    return consistent, tetrahedron


H1 = lambda x, u, v, z, p, q: (x - z) * (u - v) - (p - q)
d = sp.Symbol('delta')
Q1 = lambda x, u, v, z, p, q: p * (x - v) * (u - z) - q * (x - u) * (v - z) + d**2 * p * q * (p - q)
eps = sp.Rational(1, 7)
H1_broken = lambda x, u, v, z, p, q: (x - z) * (u - v) - (p - q) + eps * x * z

P, Qp, R = sp.symbols('P Q R')
checks, controls = {}, {}
for name, face in (('H1', H1), ('Q1 with delta', Q1)):
    consistent, tetra = cube_check(face, (P, Qp, R))
    checks[f'{name} is consistent around the cube'] = consistent
    checks[f'{name} has the tetrahedron property'] = tetra
broken_consistent, _ = cube_check(H1_broken, (P, Qp, R))
controls['H1 + xz/7 is not consistent around the cube'] = not broken_consistent

# One soliton from the vacuum through the third direction.
n, m, r0 = sp.symbols('n m r0')
a, b, c = sp.symbols('a b c', positive=True)
k = sp.Symbol('k')
pp, qq, lam = k - a**2, k - b**2, k - c**2
rho1, rho2 = (a + c) / (a - c), (b + c) / (b - c)


def soliton(R):
    """Field minus the vacuum at a site where r = R."""
    return c * (1 + R) / (1 - R)


Rs = sp.Symbol('R')
xs = soliton(Rs)
us = a + soliton(rho1 * Rs)                # site (n+1, m); vacuum offset a
vs = b + soliton(rho2 * Rs)                # site (n, m+1)
zs = a + b + soliton(rho1 * rho2 * Rs)     # site (n+1, m+1)
residual = sp.simplify((xs - zs) * (us - vs) - (pp - qq))
checks['vacuum a n + b m solves H1 when p - q = b^2 - a^2'] = sp.simplify((-(a + b)) * (a - b) - (pp - qq)) == 0
checks['one-soliton field solves H1 identically'] = residual == 0
# The Backlund faces relate old and new fields on each edge.
w0, w1 = xs, a + soliton(rho1 * Rs)
old0, old1 = 0, a
checks['Backlund face in direction 1: (x - w_1)(u - w) = p - lambda'] = sp.simplify((old0 - w1) * (old1 - w0) - (pp - lam)) == 0
w2 = b + soliton(rho2 * Rs)
checks['Backlund face in direction 2: (x - w_2)(v - w) = q - lambda'] = sp.simplify((old0 - w2) * (b - w0) - (qq - lam)) == 0

# A wrong ratio in one direction breaks the solution.
bad = sp.simplify((xs - (a + b + soliton(rho1 * rho2 * Rs * sp.Rational(11, 10)))) * (us - vs) - (pp - qq))
controls['changing the m-ratio by 10 percent breaks H1'] = bad != 0

# Numerical profile for the article: a=2, b=3, c=1, r0=-1. With a, b > c > 0 the ratios exceed one,
# so r0 < 0 keeps r negative and 1 - r away from zero: the soliton is regular on the whole lattice.
vals = {a: 2, b: 3, c: 1}
ratio1, ratio2 = (rho1.subs(vals), rho2.subs(vals))
profile = [sp.nsimplify(soliton(-ratio1**j).subs(vals)) for j in range(-3, 4)]
steps = [sp.nsimplify(2 + soliton(-ratio1**(j + 1)).subs(vals) - soliton(-ratio1**j).subs(vals)) for j in range(-3, 3)]
checks['r0 = -1 profile equals -c tanh(n log 3 / 2) at m = 0'] = all(
    abs(float(profile[j + 3]) + float(sp.tanh(j * sp.log(3) / 2))) < 1e-14 for j in range(-3, 4))
checks['regular: 1 - r never vanishes for r0 < 0 and a, b > c > 0'] = all(
    (1 - (-ratio1**j * ratio2**i)) > 0 for j in range(-20, 21) for i in range(-20, 21))
singular_r0 = sp.nsimplify(1 - ratio1**0 * ratio2**0)  # r0 = +1 hits r = 1 at the origin
controls['r0 = +1 is singular at the origin'] = singular_r0 == 0


def main():
    print('ratios (a+c)/(a-c), (b+c)/(b-c) at a=2, b=3, c=1:', ratio1, ratio2)
    print('soliton part c(1+r)/(1-r) for n = -3..3 at m = 0, r0 = -1:', profile)
    print('field steps u_{n+1} - u_n along m = 0:', steps)
    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('Cube consistency, tetrahedron property and the one-soliton construction verified; controls fail.')


if __name__ == '__main__':
    main()
