"""Local curvature, Kerr twist and the boundary data of two static Weyl rods.

Run with Python 3, SymPy and SciPy. All lengths in the rod examples use M=1.
"""
import math

import sympy as sp
from scipy.integrate import quad


def kerr():
    # Rational mass/spin pair with sigma=4/5. Check the polynomial identity
    # throughout the prolate chart, independently of the equatorial restriction.
    x, y = sp.symbols("x y", real=True)
    spin, sigma = sp.Rational(3, 5), sp.Rational(4, 5)
    radius = 1 + sigma*x
    potential = 1 - 2/(radius + sp.I*spin*y)
    norm = 1 - 2*radius/(radius**2 + spin**2*y**2)
    gradient = [(x, x*x-1), (y, 1-y*y)]
    residual = sum(norm*sp.diff(weight*sp.diff(potential, v), v)
                   - weight*sp.diff(potential, v)**2 for v, weight in gradient)
    assert sp.cancel(residual) == 0
    twist = 2*spin*y/(radius**2 + spin**2*y*y)
    equatorial = sp.diff(twist, y).subs({x:sp.Rational(5, 2), y:0})/2
    assert equatorial == sp.Rational(1, 15)
    print("Kerr equatorial twist gradient:", equatorial)


def middle_axis(separation, tolerance=1e-12):
    if separation <= 2:
        raise ValueError("The two unit-mass horizon intervals must be disjoint.")
    a, b = separation/2 - 1, separation/2 + 1

    def radial_integrand(rho):
        # Rationalize b/R_b - a/R_a to avoid cancellation near the axis.
        ra, rb = math.hypot(rho, a), math.hypot(rho, b)
        difference = (b*b-a*a)*rho*rho/(ra*rb*(b*ra+a*rb))
        return difference**2/rho

    integral, error = quad(radial_integrand, 0, math.inf,
                           epsrel=tolerance, epsabs=tolerance)
    return -integral, error


def heavenly_transport():
    p, q, r, s, eps = sp.symbols("p q r s epsilon")
    coords = (p, q, r, s)
    metric = sp.zeros(4)
    metric[0, 2] = metric[2, 0] = metric[1, 3] = metric[3, 1] = 1
    metric[0, 3] = metric[3, 0] = 4*eps*p*s
    inverse = metric.inv()
    connection = {}
    for i in range(4):
        for j in range(4):
            for k in range(4):
                value = sum(inverse[i, l]*(sp.diff(metric[k,l], coords[j])
                            + sp.diff(metric[j,l], coords[k])
                            - sp.diff(metric[j,k], coords[l])) for l in range(4))/2
                if value != 0:
                    connection[i,j,k] = value
    assert connection == {(1,0,0):4*eps*s, (2,3,3):4*eps*p}
    # Use constant-connection transports on each straight edge.
    width, height = sp.symbols("P S")
    corners = [(0,0), (width,0), (width,height), (0,height), (0,0)]
    transport = sp.eye(4)
    for (p0, s0), (p1, s1) in zip(corners, corners[1:]):
        generator = sp.zeros(4)
        for (i,j,k), value in connection.items():
            step = (p1-p0,0,0,s1-s0)
            generator[i,k] -= value.subs({p:p0, s:s0})*step[j]
        assert generator**2 == sp.zeros(4)
        transport = (sp.eye(4)+generator)*transport
    expected = sp.eye(4)
    expected[1,0], expected[2,3] = 4*eps*width*height, -4*eps*width*height
    assert transport == expected
    print("Heavenly transport on a unit rectangle:", transport.subs({width:1,height:1,eps:sp.Rational(1,4)}))


if __name__ == "__main__":
    kerr()
    for separation in (2.5, 3, 4, 6, 10):
        value, error = middle_axis(separation)
        coarser, _ = middle_axis(separation, 1e-8)
        exact = math.log1p(-4/separation**2)
        assert abs(value-exact) < 3e-13 and abs(coarser-value) < 1e-9
        print("D/M, middle k, estimated quadrature error:", separation, value, error)
    heavenly_transport()
