"""Independent finite representations, charge sums and boundary balances (SymPy)."""
from itertools import product
from math import exp

import sympy as sp


def swap_matrix(first, second):
    words = list(product(range(2), repeat=3))
    swap = sp.zeros(len(words))
    for i, word in enumerate(words):
        values = list(word)
        values[first], values[second] = values[second], values[first]
        swap[words.index(tuple(values)), i] = 1
    return swap


def spin_spaces():
    p, q, r = swap_matrix(0, 1), swap_matrix(0, 2), swap_matrix(1, 2)
    f, g, h = sp.symbols("f g h")
    eye = sp.eye(8)
    defect = (f*eye+p)*(h*eye+q)*(g*eye+r)-(g*eye+r)*(h*eye+q)*(f*eye+p)
    assert (defect-(f+g-h)*(p*q-q*p)).applyfunc(sp.expand) == sp.zeros(8)
    j = sp.Matrix([[0, -1], [1, 0]])
    a, b, c, d = sp.symbols("a b c d")
    matrix = sp.Matrix([[a, b], [c, d]])
    assert sp.solve(matrix*j-j*matrix, [c, d]) == {c: -b, d: a}
    print("Additive YB coefficient verified on 8 states; real rotation commutant has dimension 2.")

    def twisted_trace(physical):
        result = {}
        for start in (0, 1):
            auxiliary, word = start, list(physical)
            for site in range(len(word)):
                auxiliary, word[site] = word[site], auxiliary
            if auxiliary == start:
                result[tuple(word)] = 2+auxiliary
        return result

    assert twisted_trace((0, 0, 1)) == {(1, 0, 0): 3}
    for word in product(range(2), repeat=3):
        weight, current = 1, word
        for _ in range(3):
            (current, local), = twisted_trace(current).items()
            weight *= local
        assert current == word and weight == 2**word.count(0)*3**word.count(1)
    print("Partial trace: twisted translations pass all eight words.")


def charges_and_flux():
    r = sp.symbols("r", real=True, nonnegative=True)
    cdf = 2*r/(1+r)
    assert sp.diff(cdf, r).simplify() == 2/(1+r)**2
    assert sp.integrate(r*sp.diff(cdf, r), (r, 0, 1)) == -1+2*sp.log(2)
    # Midpoints of the random phase reproduce the same one-ratio CDF.
    for num in (1, 2, 3):
        ratios = []
        for i in range(1000):
            offset = 2*(i+.5)/1000
            ratios.append(min(offset, 2-offset)/max(offset, 2-offset))
        empirical = sum(t <= num/4 for t in ratios)/len(ratios)
        assert abs(empirical-2*num/(4+num)) < .002
    print("Merged grids: identical folded Poisson marginal and constant successive ratios.")

    limit = (1+exp(-2))/4
    rounding = []
    for n in [32, 256, 2048]:
        scaled = sum((n-r)*exp(-2*r/n) for r in range(n))/n**2
        rounding.append(abs(scaled-limit))
    assert rounding[2] < rounding[1] < rounding[0] and rounding[-1] < .00025
    theta = sp.symbols("theta")
    assert sp.integrate(1, (theta, 0, 2*sp.pi)) == 2*sp.pi
    mass, spring, displacement, speed, traction, drive = 2, 3, 1, 2, -4, 1
    accel = (-traction-spring*displacement+drive)/mass
    flux = -traction*speed
    stored_power = mass*accel*speed + spring*displacement*speed
    assert (accel, flux, stored_power, stored_power-flux) == (1, 8, 10, 2)
    print("Growing range: squared norm / N^2 approaches", limit)
    print("Generator period = 2*pi; endpoint power (incoming, stored, driven) = (8,10,2).")

    for n in (3, 6, 9):
        states = list(product(range(2), repeat=n))
        mixed = [states[0], states[-1]]
        for ensemble, pair in [(states, .25), (mixed, .5)]:
            assert sum(s[0] for s in ensemble)/len(ensemble) == .5
            assert sum(s[0]*s[1] for s in ensemble)/len(ensemble) == pair
    print("Diagonal states: equal one-body data; adjacent occupied probabilities 1/4 and 1/2.")


if __name__ == "__main__":
    spin_spaces()
    charges_and_flux()
