"""Checks for the Library article "Onsager's solution of the square-lattice Ising model".

Zero-field square-lattice Ising model with reduced couplings K (within a row) and L (between rows), as in
"The zero-field Ising free energy from the row spectrum". Checks:
  1. the largest eigenvalue of the brute-force periodic row transfer matrix equals Kaufman's free-fermion product
     log Lambda_0 = N log sqrt(2 sinh 2L) + (1/2) sum_m gamma(q_m), q_m = 2 pi (m + 1/2)/N, for N = 4..14 and several
     couplings, isotropic and anisotropic, on both sides of the critical line;
  2. (1/N) log Lambda_0 converges to Onsager's integral, which at the isotropic critical point equals
     (1/2) log 2 + 2G/pi with G Catalan's constant;
  3. at criticality N^2 [(1/N) log Lambda_0 - phi] tends to pi c / 6 with c = 1/2;
  4. at criticality the gap between the two leading eigenvalues gives N log(Lambda_0/Lambda_1)/(2 pi) -> 1/8, the
     scaling dimension of the spin field;
  5. Swendsen-Wang Monte Carlo on a 128 x 128 torus reproduces Yang's spontaneous magnetization
     (1 - sinh(2K)^-4)^(1/8) at three temperatures below T_c; above T_c the magnetization falls like 1/L;
  6. Kasteleyn's product formula counts the domino tilings of rectangles exactly, and the entropy per site of
     2n x 2n squares approaches G/pi.
Controls: the mean-field and Bethe approximations place the transition at T = 4 and T = 2/ln 2 and predict
magnetizations far from the Monte Carlo values.
Run with Python 3, NumPy and SciPy:  python3 ising_onsager_check.py   (about one minute)
"""
import warnings
import numpy as np
from scipy.integrate import IntegrationWarning, quad
from scipy.optimize import brentq
from scipy.sparse.csgraph import connected_components
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import LinearOperator, eigsh

CATALAN = 0.915965594177219015054603514932384110774
KC = 0.5 * np.arcsinh(1.0)


# ------------------------------------------------------------------------------------------------- transfer matrices
def row_energy(N):
    """sum_j s_j s_{j+1} on a periodic row for every configuration (bit 1 = spin +1)."""
    states = np.arange(2 ** N)
    s = 2 * ((states[:, None] >> np.arange(N)) & 1) - 1
    return np.sum(s * np.roll(s, -1, axis=1), axis=1)


def leading_eigenvalues(N, K, L, k=2):
    """Largest eigenvalues of T = D^(1/2) W D^(1/2), D = exp(K * row bonds), W = (e^L, e^-L; e^-L, e^L)^(x N)."""
    d = np.exp(0.5 * K * row_energy(N))
    w = np.array([[np.exp(L), np.exp(-L)], [np.exp(-L), np.exp(L)]])

    def matvec(v):
        x = (d * v.ravel()).reshape((2,) * N)
        for axis in range(N):
            x = np.moveaxis(np.tensordot(w, x, axes=([1], [axis])), 0, axis)
        return d * x.ravel()

    op = LinearOperator((2 ** N, 2 ** N), matvec=matvec, dtype=float)
    vals = eigsh(op, k=k, which='LA', tol=1e-13)[0]
    return np.sort(vals)[::-1]


def dual(L):
    return -0.5 * np.log(np.tanh(L))


def gamma(q, K, L):
    """Single-mode exponent: cosh gamma = cosh 2K cosh 2L* - sinh 2K sinh 2L* cos q, gamma >= 0."""
    Ls = dual(L)
    return np.arccosh(np.cosh(2 * K) * np.cosh(2 * Ls) - np.sinh(2 * K) * np.sinh(2 * Ls) * np.cos(q))


def log_lambda0_kaufman(N, K, L):
    q = 2 * np.pi * (np.arange(N) + 0.5) / N
    return N * 0.5 * np.log(2 * np.sinh(2 * L)) + 0.5 * np.sum(gamma(q, K, L))


def onsager_phi(K, L):
    """Reduced log partition density phi = -beta f = (1/2) log(2 sinh 2L) + (1/2pi) int_0^pi gamma dq."""
    with warnings.catch_warnings():
        # At Kc the integrand has a kink at q = 0; quad reports roundoff near 1e-15, below every tolerance used here.
        warnings.simplefilter("ignore", IntegrationWarning)
        val = quad(lambda q: gamma(q, K, L), 0, np.pi, limit=200, epsabs=1e-14, epsrel=1e-14)[0]
    return 0.5 * np.log(2 * np.sinh(2 * L)) + val / (2 * np.pi)


# ---------------------------------------------------------------------------------------------------------- Monte Carlo
def swendsen_wang(L, K, sweeps, rng, burn=200):
    spins = np.ones((L, L), dtype=np.int8)
    idx = np.arange(L * L).reshape(L, L)
    p = 1 - np.exp(-2 * K)
    mags = []
    for sweep in range(sweeps + burn):
        right = (spins == np.roll(spins, -1, axis=1)) & (rng.random((L, L)) < p)
        down = (spins == np.roll(spins, -1, axis=0)) & (rng.random((L, L)) < p)
        rows = np.concatenate([idx[right], idx[down]])
        cols = np.concatenate([np.roll(idx, -1, axis=1)[right], np.roll(idx, -1, axis=0)[down]])
        graph = coo_matrix((np.ones(len(rows), dtype=np.int8), (rows, cols)), shape=(L * L, L * L))
        n, labels = connected_components(graph, directed=False)
        flip = rng.random(n) < 0.5
        spins = np.where(flip[labels].reshape(L, L), -spins, spins).astype(np.int8)
        if sweep >= burn:
            mags.append(abs(spins.mean()))
    mags = np.array(mags)
    blocks = mags[: len(mags) // 20 * 20].reshape(20, -1).mean(axis=1)
    return mags.mean(), blocks.std(ddof=1) / np.sqrt(20)


def yang_m(K):
    return (1 - np.sinh(2 * K) ** -4) ** 0.125 if K > KC else 0.0


def mean_field_m(T, z=4):
    if T >= z:
        return 0.0
    return brentq(lambda m: m - np.tanh(z * m / T), 1e-9, 1.0)


def bethe_m(T, z=4):
    """Bethe-Peierls magnetization on a lattice of coordination z (Baxter's book, section 4.6)."""
    K = 1 / T
    Kc_b = 0.5 * np.log(z / (z - 2))
    if K <= Kc_b:
        return 0.0
    # effective field h on a site's neighbors solves h = (z-1) atanh(tanh K tanh h)
    f = lambda h: h - (z - 1) * np.arctanh(np.tanh(K) * np.tanh(h))
    h = brentq(f, 1e-9, 50.0)
    H = z * np.arctanh(np.tanh(K) * np.tanh(h))
    return np.tanh(H)


# ---------------------------------------------------------------------------------------------------------- dimers
def tilings_transfer(m, n):
    """Count domino tilings of an m x n rectangle by a row-by-row transfer over occupancy masks."""
    def fill(col, mask_in, mask_out, out):
        if col == m:
            out[mask_out] = out.get(mask_out, 0) + 1
            return
        if mask_in >> col & 1:
            fill(col + 1, mask_in, mask_out, out)
            return
        fill(col + 1, mask_in, mask_out | (1 << col), out)            # vertical domino sticks up
        if col + 1 < m and not (mask_in >> (col + 1) & 1):
            fill(col + 2, mask_in, mask_out, out)                       # horizontal domino
    counts = {0: 1}
    for _ in range(n):
        new = {}
        for mask, c in counts.items():
            out = {}
            fill(0, mask, 0, out)
            for k, v in out.items():
                new[k] = new.get(k, 0) + c * v
        counts = new
    return counts.get(0, 0)


def tilings_kasteleyn_log(m, n):
    """log of Kasteleyn's product prod_j prod_k (4 cos^2(pi j/(m+1)) + 4 cos^2(pi k/(n+1))), j <= m/2, k <= n/2."""
    j = np.arange(1, (m + 1) // 2 + 1)[:, None]
    k = np.arange(1, (n + 1) // 2 + 1)[None, :]
    return float(np.sum(np.log(4 * np.cos(np.pi * j / (m + 1)) ** 2 + 4 * np.cos(np.pi * k / (n + 1)) ** 2)))


def tilings_kasteleyn(m, n):
    return np.exp(tilings_kasteleyn_log(m, n))


def main():
    checks, controls = {}, {}
    # 1. Brute-force transfer matrix against Kaufman's product.
    worst = 0.0
    for N in (4, 6, 8, 10, 12, 14):
        for K, L in ((0.3, 0.3), (KC, KC), (0.6, 0.6), (0.25, 0.5), (0.7, 0.35)):
            lam = leading_eigenvalues(N, K, L, k=1)[0]
            worst = max(worst, abs(np.log(lam) - log_lambda0_kaufman(N, K, L)) / N)
    print(f'largest |log Lambda_0 (brute force) - Kaufman| / N over N = 4..14 and five couplings: {worst:.1e}')
    checks['brute-force leading eigenvalue equals Kaufman\'s product (1e-12 per site)'] = worst < 1e-12

    # 2. Onsager's integral and its critical value.
    phi_c = onsager_phi(KC, KC)
    exact_c = 0.5 * np.log(2) + 2 * CATALAN / np.pi
    print(f'phi(Kc) = {phi_c:.15f}; (1/2) log 2 + 2G/pi = {exact_c:.15f}')
    checks['Onsager integral at Kc equals (1/2) log 2 + 2G/pi (1e-12)'] = abs(phi_c - exact_c) < 1e-12
    off = [(abs(log_lambda0_kaufman(N, 0.6, 0.6) / N - onsager_phi(0.6, 0.6))) for N in (8, 16, 32)]
    print('off-critical (K = L = 0.6) |phi_N - phi|:', ' '.join(f'{e:.1e}' for e in off))
    checks['away from Kc the finite-width density converges exponentially (each doubling of N squares the error or better)'] = (
        off[2] < 1e-9 and off[1] < off[0] ** 1.5 and off[2] < off[1] ** 1.5)

    # 3. Central charge from the critical finite-size correction.
    print(' N      N^2 (phi_N - phi) * 6/pi   (c)')
    cs = []
    for N in (16, 32, 64, 128, 256):
        c = N ** 2 * (log_lambda0_kaufman(N, KC, KC) / N - phi_c) * 6 / np.pi
        cs.append(c)
        print(f'{N:4d}   {c:.10f}')
    checks['central charge from the critical correction is 1/2 (1e-5 at N = 256, error falling like 1/N^2)'] = (
        abs(cs[-1] - 0.5) < 1e-5 and all(0.2 < (cs[i + 1] - 0.5) / (cs[i] - 0.5) < 0.3 for i in range(len(cs) - 1)))

    # 4. Spin scaling dimension from the critical transfer gap.
    print(' N      N log(Lambda_0/Lambda_1) / 2pi   (x_sigma)')
    xs = []
    for N in (6, 8, 10, 12, 14, 16):
        lam = leading_eigenvalues(N, KC, KC, k=2)
        xs.append(N * np.log(lam[0] / lam[1]) / (2 * np.pi))
        print(f'{N:4d}   {xs[-1]:.8f}')
    checks['critical gap gives the spin dimension 1/8 (within 1e-3 at N = 16, approaching monotonically)'] = (
        abs(xs[-1] - 0.125) < 1e-3 and all(abs(xs[i + 1] - 0.125) < abs(xs[i] - 0.125) for i in range(len(xs) - 1)))

    # 5. Monte Carlo magnetization against Yang's formula.
    rng = np.random.default_rng(20261125)
    Tc = 1 / KC
    print(f'T_c = {Tc:.6f}')
    print(' T      MC <|m|> (L = 128)       Yang          mean field    Bethe')
    mc = {}
    for T in (2.0, 2.1, 2.2, 2.5):
        m, err = swendsen_wang(128, 1 / T, 1500, rng)
        mc[T] = (m, err)
        print(f'{T:.1f}    {m:.4f} +- {err:.4f}       {yang_m(1 / T):.4f}        {mean_field_m(T):.4f}        {bethe_m(T):.4f}')
    checks['Monte Carlo matches Yang\'s magnetization below Tc (within 4 standard errors and 0.006)'] = all(
        abs(mc[T][0] - yang_m(1 / T)) < max(4 * mc[T][1], 0.006) for T in (2.0, 2.1, 2.2))
    m64, err64 = swendsen_wang(64, 1 / 2.5, 1500, rng)
    print(f'2.5    {m64:.4f} +- {err64:.4f} (L = 64): above Tc <|m|> ~ sqrt(chi)/L, ratio 64 -> 128 = {m64 / mc[2.5][0]:.3f}')
    checks['above Tc the magnetization falls like 1/L (ratio between L = 64 and 128 within 0.25 of 2)'] = (
        abs(m64 / mc[2.5][0] - 2) < 0.25)
    controls['mean-field theory predicts T_c = 4 and a magnetization off by more than 0.1 at T = 2.2'] = (
        abs(mean_field_m(2.2) - mc[2.2][0]) > 0.1)
    controls['the Bethe approximation predicts T_c = 2/ln 2 and a nonzero magnetization at T = 2.5'] = (
        abs(2 / np.log(2) - 2.885) < 1e-3 and bethe_m(2.5) > 0.3 and mc[2.5][0] < 0.1)

    # 6. Dimers.
    pairs = ((2, 2), (2, 3), (4, 4), (6, 6), (8, 8), (4, 7), (6, 9), (10, 10))
    exact = all(tilings_transfer(m, n) == round(tilings_kasteleyn(m, n)) for m, n in pairs)
    print('domino tilings:', ', '.join(f'{m}x{n}: {tilings_transfer(m, n)}' for m, n in pairs))
    checks['Kasteleyn\'s product equals the transfer count for eight rectangles, 8 x 8 giving 12988816'] = (
        exact and tilings_transfer(8, 8) == 12988816)
    ents = [tilings_kasteleyn_log(2 * k, 2 * k) / (2 * k) ** 2 for k in (8, 32, 128)]
    print('entropy per site of 2n x 2n squares:', ' '.join(f'{e:.6f}' for e in ents), f'-> G/pi = {CATALAN / np.pi:.6f}')
    checks['domino entropy per site approaches G/pi (within 1e-2 at 256 x 256, monotonically)'] = (
        abs(ents[-1] - CATALAN / np.pi) < 1e-2 and abs(ents[2] - CATALAN / np.pi) < abs(ents[1] - CATALAN / np.pi))

    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)


if __name__ == '__main__':
    main()
