"""Reproduce the three-site clock-pulse comparison with Python and NumPy.

Keep clock-quench-input.json beside this file and run python clock-check.py.
H is built in hundredths of the bare angular frequency. The tensor factors
are matter sites 2, 1, 0 and the two bonds 01, 12, in that order.
"""
import hashlib
import json
from fractions import Fraction
from math import factorial
from pathlib import Path

import numpy as np


def on_axis(op, axis):
    result = np.array([[1]])
    for index in range(5):
        result = np.kron(result, op if index == axis else np.eye(2, dtype=int))
    return result


x = np.array([[0, 1], [1, 0]])
minus_i_y = np.array([[0, -1], [1, 0]])
z = np.diag([1, -1])
identity = np.eye(32, dtype=int)
x0, x1, x2, flip_a, flip_b = [on_axis(x, k) for k in (2, 1, 0, 3, 4)]
z0, z1, z2 = [on_axis(z, k) for k in (2, 1, 0)]
y0_real, y2_real = [on_axis(minus_i_y, k) for k in (2, 0)]
a, b = [on_axis(np.diag([0, 1]), k) for k in (3, 4)]

# omega=1, J0=.01, deltaB=5, lambda=.8, kappa=.1, k0=4.
h100 = 50 * (x0 + x1 + x2)
for zz, flip, occupancy in ((z0 @ z1, flip_a, a), (z1 @ z2, flip_b, b)):
    h100 += zz + 500 * occupancy + 40 * ((identity - zz) @ flip)
for degree, multiplicity in ((a, 1), (a + b, 2), (b, 1)):
    offset = degree - 4 * identity
    h100 += 10 * multiplicity * (offset @ offset)
h_exact = h100.astype(object)  # Python integers for the proof checks.
parity = x0 @ x1 @ x2
assert np.array_equal(h100 @ parity, parity @ h100)

raw = Path(__file__).with_name("clock-quench-input.json").read_bytes()
assert hashlib.sha256(raw).hexdigest() == "435e0c25b371d63993daae8f79bd32bf234cf580511cccb2c6ef7bee6a265738"
archive = json.loads(raw)
times = np.array(archive["times"])
assert (archive["source_site"], archive["target_site"]) == (0, 2)
np.testing.assert_allclose(times, np.arange(61) / 20, atol=5e-16, rtol=0)
energies, vectors = np.linalg.eigh(h100 / 100)
ground = vectors[:, 0]


def remote_states(initial):
    phases = np.exp(-1j * np.outer(times, energies))
    waves = (phases * (vectors.T @ initial)) @ vectors.T
    split = waves.reshape(len(times), 2, 16)  # Target 2 is the first factor.
    return split @ split.conj().swapaxes(1, 2)


def commutator(left, right):
    return left @ right - right @ left


def eigenvalues_below_five():
    # Leading principal minors by fraction-free elimination. Their sign
    # changes count the negative LDL pivots of 100*(H-5I).
    block = h_exact - 500 * identity
    previous, changes = 1, 0
    while block.size:
        pivot = block[0, 0]
        assert pivot != 0
        changes += int(pivot * previous < 0)
        reduced = pivot * block[1:, 1:] - np.outer(block[1:, 0], block[0, 1:])
        assert np.all(reduced % previous == 0)
        block, previous = reduced // previous, pivot
    return changes


# The normalized integer vector is within sin(angle) < 4e-12 of the unique
# ground ray. The residual is <1e-12 and every excited energy is >=5.
assert eigenvalues_below_five() == 1
witness = np.rint(ground * 10**14).astype(np.int64).astype(object)
norm_squared = witness @ witness
mu_numerator, mu_denominator = 4719316311405, 10**12
assert Fraction(mu_numerator, mu_denominator) < Fraction(19, 4)
residual = (mu_denominator // 100) * (h_exact @ witness) - mu_numerator * witness
assert (residual @ residual) * 10**24 < mu_denominator**2 * norm_squared

# At orders 0, 1 and 2 each target observable commutes with every source
# Pauli. A factor of i multiplying an operator leaves this zero test intact.
for target in (x2, y2_real, z2):
    derivative = target.astype(object)
    for order in range(3):
        for source in (x0, y0_real, z0):
            assert not np.any(commutator(source, derivative))
        derivative = commutator(h_exact, derivative)


def leading_coefficient(pulse, norm_factor, target, power):
    # i^4 X = X and i^3 Y = -iY. The physical Heisenberg derivatives
    # therefore use real matrices for both (X,4) and (Y,3).
    derivative = target.astype(object)
    for _ in range(power):
        derivative = commutator(h_exact, derivative)
    numerator = pulse.T @ derivative @ pulse - norm_factor * derivative
    denominator = 2 * norm_factor * 100**power * factorial(power)
    assert np.array_equal(numerator, numerator.T)
    estimate = Fraction(witness @ numerator @ witness, norm_squared * denominator)
    norm_bound = Fraction(np.abs(numerator).sum(axis=1).max(), denominator)
    error = Fraction(8, 10**12) * norm_bound
    assert estimate > error  # Certifies a strictly positive leading term.
    return float(estimate), float(error)


reference = remote_states(ground)
pulses = (("X", x0), ("Y", y0_real), ("Z", z0), ("Ry(pi/2)", identity + y0_real))
endpoints, energy_excess, errors = {}, {}, []
print("source      power     leading coefficient            D(3)")
for name, pulse in pulses:
    is_clock = name == "Ry(pi/2)"
    norm_factor, power, target = (2, 3, y2_real) if is_clock else (1, 4, x2)
    assert np.array_equal(pulse.T @ pulse, norm_factor * identity)
    prepared = pulse @ ground / np.sqrt(norm_factor)
    energy_excess[name] = prepared @ (h100 / 100) @ prepared - energies[0]
    difference = remote_states(prepared) - reference
    distances = np.abs(np.linalg.eigvalsh(difference)).sum(axis=1) / 2
    if not is_clock:
        np.testing.assert_allclose(distances, archive["trace_distances"][name], rtol=0, atol=5e-13)
    endpoints[name] = distances[-1]
    coefficient, error = leading_coefficient(pulse, norm_factor, target, power)
    errors.append(error)
    print(f"{name:9s} {power:5d} {coefficient:23.12f} {distances[-1]:15.12f}")

ratio = endpoints["Ry(pi/2)"] / max(endpoints[name] for name in ("X", "Y", "Z"))
np.testing.assert_allclose(energy_excess["Ry(pi/2)"], energy_excess["Y"] / 2, rtol=0, atol=1e-13)
print(f"endpoint ratio = {ratio:.9f}")
assert max(errors) < 5e-12
print("absolute error on each unrounded leading coefficient < 5e-12")
print("183 archived distances verified within 5e-13. Half-energy identity verified.")
