#!/usr/bin/env python3
"""Six independent checks for the Foundations readings on Poisson geometry.

Run python3 poisson_geometry_controls.py. Python 3.8+ standard library.
The torus samples illustrate finite returns; density is proved in the reading.
"""

import math
from fractions import Fraction


def area_check():
    def integrate_strip(left, right, panels=512):
        width = (right - left) / panels
        total = 0.0
        for i in range(panels):
            x = left + i * width
            total += 1 / x + 4 / (x + width / 2) + 1 / (x + width)
        return 2 * width * total / 6

    before = integrate_strip(1, 3)
    after = integrate_strip(2, 6)
    assert abs(before - 2 * math.log(3)) < 2e-12
    assert abs(before - after) < 1e-14
    print(f"Area: ordinary 4 -> 8, canonical {before:.10f} -> {after:.10f}")


def oscillator_check():
    detuning = 0.5
    for t in [0, 0.4, math.pi, 4 * math.pi]:
        # Each (q,p) pair solves its own Hamilton equations with the given start.
        q1, p1 = math.cos(t), -math.sin(t)
        theta = (1 + detuning) * t
        q2, p2 = math.sin(theta), math.cos(theta)
        c = q1 * q2 + p1 * p2
        ell = q1 * p2 - q2 * p1
        assert abs(c - math.sin(detuning * t)) < 1e-14
        assert abs(ell - math.cos(detuning * t)) < 1e-14
    print("Detuned oscillators: (C,L) is (0,1) initially and (1,0) at t=pi")


def moving_frame_check():
    # In the laboratory, a free particle has q(t)=q0+p*t/m.
    mass, momentum, q0 = 2, 6, Fraction(1, 2)
    t = Fraction(3, 2)
    step = Fraction(1, 4096)

    def moving_position(time):
        return q0 + momentum * time / mass - time**2 / 2

    velocity = (moving_position(t + step) - moving_position(t - step)) / (2 * step)
    acceleration = (moving_position(t + step) - 2 * moving_position(t)
                    + moving_position(t - step)) / step**2
    assert velocity == Fraction(momentum, mass) - t
    assert acceleration == -1
    print(f"Accelerating origin: Q'={velocity} and Q''={acceleration} at t=3/2")


def winding_check():
    rational = {(Fraction(n, 2) % 1) for n in range(13)}
    assert rational == {Fraction(0), Fraction(1, 2)}
    # Squaring n*sqrt(2)=m+1/2 would give 8*n*n=(2*m+1)**2:
    # the right-hand side is odd. Independently compare the sampled heights.
    heights = [(n * math.sqrt(2)) % 1 for n in range(13)]
    assert len(set(heights)) == 13
    assert all(abs(y - 0.5) > 1e-8 for y in heights)
    print("Torus section: 2 rational heights and 13 distinct irrational heights in 13 samples")


def multiply(left, right):
    return [[sum(a * b for a, b in zip(row, column)) for column in zip(*right)]
            for row in left]


def heisenberg_check():
    # In upper triangular matrices e_q=E12, e_p=E23, e_c=E13.
    a, b, c = 2, -3, 5
    group = [[1, a, c], [0, 1, b], [0, 0, 1]]
    inverse = [[1, -a, a * b - c], [0, 1, -b], [0, 0, 1]]
    q, p = 7, -4
    components = []
    for i, j in [(0, 1), (1, 2), (0, 2)]:
        basis = [[0] * 3 for _ in range(3)]
        basis[i][j] = 1
        adjoint = multiply(multiply(inverse, basis), group)
        components.append(p * adjoint[0][1] - q * adjoint[1][2] + adjoint[0][2])
    assert components == [p + b, -q - a, 1]
    print(f"Heisenberg action: coadjoint matrix calculation gives {tuple(components)}")


def field_check():
    def residuals(n):
        dx = 2 * math.pi / n
        u = [math.exp(math.cos(i * dx)) for i in range(n)]

        def apply(function):
            product = [value * function(value) for value in u]
            return [value * (product[(i + 1) % n] - product[i - 1]) / (2 * dx)
                    for i, value in enumerate(u)]

        casimir_error = max(abs(value) for value in apply(lambda v: 1 / v))
        velocity = apply(lambda v: math.log(v) / v)
        flow_error = max(abs(v + u[i] * math.sin(i * dx)) for i, v in enumerate(velocity))
        return casimir_error, flow_error

    rows = [residuals(n) for n in [64, 128, 256]]
    assert max(casimir for casimir, _ in rows) < 3e-14
    errors = [error for _, error in rows]
    assert all(3.9 < coarse / fine < 4.1 for coarse, fine in zip(errors, errors[1:]))
    print("Field transport: max velocity errors at 64, 128, 256 points:",
          ", ".join(f"{error:.6g}" for error in errors))


if __name__ == "__main__":
    for check in [area_check, oscillator_check, moving_frame_check, winding_check,
                  heisenberg_check, field_check]:
        check()
