"""Check the three-state chiral Potts star–triangle relation for fixed boundaries.

Run with Python 3 and mpmath 1.3.0:
    python3 -m pip install mpmath==1.3.0
    python3 chiral_potts_star_triangle.py

All rapidities, weights and absolute errors are dimensionless. Inputs and root
choices reproduce the Integrable.org model page /models/integrable-chiral-potts-model/.
The program checks all six tables after one spin cycle and all 27 external
spin triples, then reverses the triangle's barred pr bond. The correctly
oriented error decreases with precision. The reversed error stays near 0.133626.
"""

from itertools import product

import mpmath as mp


def rapidity(mu, k, k_prime, n):
    """Choose the positive real roots of both rapidity-curve equations."""
    x = mp.root((1 - k_prime / mu**n) / k, n)
    y = mp.root((1 - k_prime * mu**n) / k, n)
    return x, y, mu


def bond_tables(p, q, omega, n):
    xp, yp, mup = p
    xq, yq, muq = q
    plain = [mp.mpf(1)]
    barred = [mp.mpf(1)]
    for j in range(1, n + 1):
        phase = omega**j
        plain.append(plain[-1] * (mup / muq) * (yq - phase*xp) / (yp - phase*xq))
        barred.append(barred[-1] * mup*muq * (omega*xp - phase*xq) / (yq - phase*yp))
    cycle_error = max(abs(plain[n] - 1), abs(barred[n] - 1))
    return plain[:n], barred[:n], cycle_error


def check(digits):
    n = 3
    with mp.workdps(digits):
        k, k_prime = mp.mpf(4) / 5, mp.mpf(3) / 5
        omega = (-1 + mp.j * mp.sqrt(3)) / 2
        p, q, r = [rapidity(mp.mpf(mu), k, k_prime, n) for mu in ("0.92", "1", "1.12")]
        w_pq, bar_pq, cycle_pq = bond_tables(p, q, omega, n)
        w_pr, bar_pr, cycle_pr = bond_tables(p, r, omega, n)
        w_qr, bar_qr, cycle_qr = bond_tables(q, r, omega, n)

        def star(a, b, c):
            return sum(
                bar_qr[(b - d) % n] * w_pr[(a - d) % n]
                * bar_pq[(d - c) % n]
                for d in range(n)
            )

        def triangle(a, b, c, reverse=False):
            middle = (c - b) if reverse else (b - c)
            return w_pq[(a - b) % n] * bar_pr[middle % n] * w_qr[(a - c) % n]

        # Both all-equal triangles have weight one, fixing the same scalar.
        scalar = star(0, 0, 0)
        error = reversed_error = mp.mpf(0)
        for a, b, c in product(range(n), repeat=3):
            left = star(a, b, c)
            error = max(error, abs(left - scalar * triangle(a, b, c)))
            reversed_error = max(reversed_error, abs(left - scalar * triangle(a, b, c, reverse=True)))
        cycle_error = max(cycle_pq, cycle_pr, cycle_qr)

        print(f"{digits} decimal digits")
        for label, value in [
            ("R", scalar), ("D(0,1,2)", triangle(0, 1, 2)), ("S(0,1,2)", star(0, 1, 2)),
            ("maximum cycle error", cycle_error), ("maximum star–triangle error", error),
            ("maximum error with the triangle's pr barred bond reversed", reversed_error),
        ]:
            print(f"  {label} = {mp.nstr(value, 12)}")

        tolerance = mp.power(10, 4 - digits)
        if cycle_error > tolerance or error > tolerance or reversed_error < mp.mpf("0.01"):
            raise ArithmeticError("The cyclic weights, star–triangle identity or orientation control failed.")

        # A ring of three barred bonds with a fixed twist of the closing spin.
        # Reversing every bond preserves the untwisted trace and exchanges the twists.
        spectrum = [sum(bar_pq[j] * omega**(-mode*j) for j in range(n))
                    for mode in range(n)]
        for twist in (0, 1, -1):
            fourier = sum(value**3 * omega**(-mode*twist)
                          for mode, value in enumerate(spectrum))
            direct = sum(bar_pq[(a-b) % n] * bar_pq[(b-c) % n] * bar_pq[(c-a-twist) % n]
                         for a, b, c in product(range(n), repeat=3))
            assert abs(fourier - direct) < tolerance
            print(f"  Three barred bonds, twist {twist:+d}: {mp.nstr(direct, 12)}")


if __name__ == "__main__":
    for precision in (48, 96):
        check(precision)
