"""Exact local intertwiner at an exceptional spectral difference. Requires SymPy."""
from sympy import Matrix, eye, kronecker_product, zeros

I = eye(2)
P = Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])
P12 = kronecker_product(P, I)
P23 = kronecker_product(I, P)
P13 = P23 * P12 * P23


def coefficient_matrix(u, v):
    """Columns of X -> X12 R13(u) R23(v) - R23(v) R13(u) X12."""
    A, B = u * eye(8) + P13, v * eye(8) + P23
    columns = []
    for j in range(16):
        E = zeros(4)
        E[j // 4, j % 4] = 1
        X = kronecker_product(E, I)
        columns.append((X * A * B - B * A * X).reshape(64, 1))
    return Matrix.hstack(*columns)


def main():
    for u, v, expected_rank in [(1, 2, 1), (1, 3, 4)]:
        equations = coefficient_matrix(u, v)
        expected = (u - v) * eye(4) + P
        assert equations.rank() == 15
        assert equations * expected.reshape(16, 1) == zeros(64, 1)
        assert expected.rank() == expected_rank
        print(f"PASS u={u}, v={v}: nullity 1, intertwiner rank {expected.rank()}")
    # At the exceptional difference the identity is invertible but fails the local relation.
    assert coefficient_matrix(1, 2) * eye(4).reshape(16, 1) != zeros(64, 1)
    print("PASS the identity fails the local relation at the exceptional pair")


if __name__ == "__main__":
    main()
