"""Check the two-direction stiffness law using exact TT polarizations.

Run with Python 3: python3 axis-check.py
All directions are integer representatives of unoriented lines. The nine
entries of each 3-by-3 tensor are stored row by row so dot() is Frobenius.
"""

from fractions import Fraction
from itertools import product


ENTRIES = tuple(product(range(3), repeat=2))
X, Y, Z = (1, 0, 0), (0, 1, 0), (0, 0, 1)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def tt_plane(n):
    """Two orthogonal, unnormalized tensor polarizations perpendicular to n."""
    u = cross(n, X if n[1] or n[2] else Y)
    v = cross(n, u)
    uu, vv = dot(u, u), dot(v, v)
    plus = tuple(vv * u[i] * u[j] - uu * v[i] * v[j] for i, j in ENTRIES)
    shear = tuple(u[i] * v[j] + v[i] * u[j] for i, j in ENTRIES)
    assert dot(plus, shear) == 0 and dot(plus, plus) > 0 and dot(shear, shear) > 0
    return plus, shear


def hidden_tensor(a, b):
    """Six times the traceless symmetric product, allowing unnormalized a,b."""
    s = dot(a, b)
    return tuple(3 * (a[i] * b[j] + b[i] * a[j]) - 2 * (i == j) * s for i, j in ENTRIES)


def projected_norm_squared(q, plane):
    return sum(Fraction(dot(q, p)**2, dot(p, p)) for p in plane)


def cosine_squared(a, b):
    return Fraction(dot(a, b)**2, dot(a, a) * dot(b, b))


def angular_fraction(a, b, n):
    sine_product_squared = (1 - cosine_squared(a, n)) * (1 - cosine_squared(b, n))
    return 3 * sine_product_squared / (3 + cosine_squared(a, b))


def rank(rows):
    """Integer row elimination. Nonzero row scalings preserve rational rank."""
    rows = list(rows)
    count = 0
    for j in range(len(rows[0])):
        pivot = next((i for i in range(count, len(rows)) if rows[i][j]), None)
        if pivot is None:
            continue
        rows[count], rows[pivot] = rows[pivot], rows[count]
        p = rows[count]
        for i in range(count + 1, len(rows)):
            row = rows[i]
            if row[j]:
                rows[i] = tuple(p[j] * x - row[j] * y for x, y in zip(row, p))
        count += 1
    return count


def check(a, b, n):
    first_two = tt_plane(a) + tt_plane(b)
    q = hidden_tensor(a, b)
    assert rank(first_two) == 4 and all(dot(q, p) == 0 for p in first_two)
    plane = tt_plane(n)
    r = projected_norm_squared(q, plane) / dot(q, q)
    assert r == angular_fraction(a, b, n)
    dimension = rank(first_two + plane)
    assert dimension == 4 + int(r > 0)
    return dimension, r


if __name__ == "__main__":
    print("a=(1,0,0), b=(0,1,0)")
    print("third line       span rank   fraction r   sharp cap / epsilon")
    for n in (Z, (1, 0, 10), (1, 1, 0), (10, 0, 1), X):
        dimension, r = check(X, Y, n)
        assert r - cosine_squared(n, Z) == Fraction((n[0] * n[1])**2, dot(n, n)**2)
        cap = str(1 / r) if r else "unbounded"
        print(f"{str(n):16} {dimension:9} {str(r):>12} {cap:>21}")

    a, b, n = (1, 1, 0), (1, 0, 1), (1, -1, -1)
    dimension, r = check(a, b, n)
    print(f"Oblique case a={a}, b={b}, n={n}: rank {dimension}, fraction {r}")

    # Rotate n to Z. Both norm identities have degree at most two in each
    # of the six real components of a,b. Three distinct values per component
    # prove the polynomial identities by repeated univariate interpolation.
    vectors = tuple(product((-1, 0, 1), repeat=3))
    plane = tt_plane(Z)
    for a, b in product(vectors, repeat=2):
        q = hidden_tensor(a, b)
        assert dot(q, q) == 18 * dot(a, a) * dot(b, b) + 6 * dot(a, b)**2
        assert projected_norm_squared(q, plane) == 18 * dot(a[:2], a[:2]) * dot(b[:2], b[:2])
    print(f"Two polynomial identities verified on all {len(vectors)**2} interpolation nodes.")
