"""Independent implementation check for the PF-002 mechanism hypotheses study.

Virtual lab - simulated experiment. It imports nothing from the study and shares
no scientific helper. It repeats the frozen scalars itself and reaches each value
another way: a Cartesian Gauss rule in place of polar Simpson, the shoelace formula
in place of time integrals, closed forms in place of breakpoint sums, and exact
vector algebra for the identity. These are the same declared equations, so
agreement checks an implementation. It is not independently established physics,
and it shows nothing about whether a mechanism exists.
"""

from fractions import Fraction
import math

C = 299792458.0
H = 6.62607015e-34
E = 1.602176634e-19
MU_0 = 1.25663706127e-06
WAVELENGTH = 1.55e-06
WAIST = 3.1e-05
SEPARATION = 3.1e-05
STROKE = 1e-06
GAUSS = (-math.sqrt(0.6), 0.0, math.sqrt(0.6))
GAUSS_WEIGHTS = (5.0/9.0, 8.0/9.0, 5.0/9.0)


def _nodes(low, high, panels):
    step = (high-low)/panels
    for i in range(panels):
        middle = low+(i+0.5)*step
        for point, weight in zip(GAUSS, GAUSS_WEIGHTS):
            yield middle+point*step/2, weight*step/2


def field_integrals(panels=160):
    """Cartesian in (n_x, n_y) with n_x <= 0, and a dOmega = dn_x dn_y/n_z Jacobian."""
    k = 2*math.pi/WAVELENGTH
    kw = k*WAIST
    kd = k*SEPARATION
    edge = 12*math.sqrt(2)/kw
    far = kd-k*STROKE
    near = k*STROKE
    across = list(_nodes(-edge, edge, 2*panels))
    m0 = cosine = moment = half = near_ring = far_ring = 0.0
    for nx, wx in _nodes(-edge, 0.0, panels):
        for ny, wy in across:
            r2 = nx*nx+ny*ny
            nz = math.sqrt(1-r2)
            w = wx*wy*nz*math.exp(-kw*kw*r2/2)*(1-ny*ny)
            sine = math.sin(kd*nx)
            m0 += w
            cosine += w*math.cos(kd*nx)
            moment += w*nx*sine
            half += w*sine
            near_ring += w*math.cos(near*nx)
            far_ring += w*math.cos(far*nx)
    overlap = cosine/m0
    p0 = 1/(1+overlap)
    n_hat = abs(moment)/m0
    f_plus = 0.5+abs(half)/(2*m0)
    return {"C": overlap, "P0": p0, "n_hat": n_hat, "F_hat": p0*n_hat/C,
            "f_plus": f_plus, "f_minus": 1-f_plus, "D_f": 2*f_plus-1,
            "near_ratio": near_ring/m0, "far_ratio": far_ring/m0,
            "far_at_zero_ratio": overlap}


def paraxial_overlap():
    """The closed form exp(-d^2/(2*w^2)), near the exact value and not equal to it."""
    return math.exp(-SEPARATION**2/(2*WAIST**2))


def shoelace(points):
    """Loop integral of y dx by the shoelace rule, for vertices (x, y)."""
    total = Fraction(0)
    for (xa, ya), (xb, yb) in zip(points, points[1:]+points[:1]):
        total += (xb-xa)*(ya+yb)/2
    return total


def holonomy_area(orientation):
    """The trapezoid ramps do not overlap, so (nu, s) traces a rectangle."""
    low, high = Fraction(1, 2), Fraction(1)
    forward = [(Fraction(-1), low), (Fraction(1), low), (Fraction(1), high), (Fraction(-1), high)]
    # At orientation +1, nu rises with s low, and falls with s high.
    path = forward if orientation == 1 else list(reversed(forward))
    return 2*shoelace(path)


def rectangle_phase_units():
    """Loop integrals in stroke units on the frozen (R, nu) rectangle."""
    points = [(Fraction(0), Fraction(1)), (Fraction(1), Fraction(1)),
              (Fraction(1), Fraction(-1)), (Fraction(0), Fraction(-1))]
    nu_dr = shoelace(points)
    r_dnu = shoelace([(y, x) for x, y in points])
    return {"nu_dR": nu_dr, "R_dnu": r_dnu, "theta_A_units": nu_dr,
            "readout_units": nu_dr+r_dnu, "theta_h_units": nu_dr+2*r_dnu}


def skew_mean_closed(orientation, skew):
    """Mean of s(t)*nu(t - skew). The autocorrelation slope is 4/T inside the dwell."""
    if abs(skew) > Fraction(1, 32):
        raise ValueError("skew is outside the closed form")
    return Fraction(orientation)*Fraction(1, 4)*4*skew


def contrast(eta, f_plus, f_minus):
    return -(f_plus-f_minus)*eta/(2-eta*(f_plus+f_minus))


def absorption_cases():
    """The declared map, written out as a table of inputs and the `a` each gives."""
    return (
        (("C1-E", "open_path", 0.25, None), 0.25),
        (("C1-E", "closed_laboratory", 0.25, None), 1.0),
        (("C1-E", "local_absorber", 0.25, None), 1.0),
        (("C1-E", "ray_absorbed_later", 0.25, None), 1.0),
        (("C1-F", "open_path", 0.25, True), 0.25),
        (("C1-F", "closed_laboratory", 0.25, True), 1.0),
        (("C1-F", "closed_laboratory", 0.25, False), 0.25),
        (("C1-F", "ray_absorbed_later", 0.25, True), 1.0),
        (("C1-F", "ray_absorbed_later", 0.25, False), 0.25))


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 _dot(a, b):
    return sum(x*y for x, y in zip(a, b))


def e_dot_b_identity(k1, k2, e1, e2):
    """Both sides of the cross-term identity, with c = 1, in exact arithmetic."""
    b1, b2 = _cross(k1, e1), _cross(k2, e2)
    left = _dot(e1, b2)+_dot(e2, b1)
    gap = tuple(y-x for x, y in zip(k1, k2))
    return left, _dot(gap, _cross(e2, e1))


def natural_units():
    hbar_c = H*C/(2*math.pi)
    return {"metre": E/hbar_c, "tesla": math.sqrt(hbar_c**3/MU_0)/E**2}


def c2_table():
    """Each quantity written out again, on the frozen crossed-channel power map."""
    units = natural_units()
    k = 2*math.pi/WAVELENGTH
    intensity = 2*0.5/(math.pi*WAIST*WAIST)
    z_0 = MU_0*C
    field = math.sqrt(2*z_0*intensity)/C
    theta = 2/(k*WAIST)
    length = k*WAIST*WAIST/2
    per_ev = theta*field*units["tesla"]*length*units["metre"]/2
    force = lambda g: (g*1e-9*per_ev)**2*1.0/C
    required = math.sqrt(1e-12/force(1.0))
    return {"force_at_cast": force(0.66e-10), "force_at_sapphires": force(5.45e-7),
            "required_g": required, "coupling_decades": math.log10(required/0.66e-10),
            "force_decades": math.log10(1e-12/force(0.66e-10)),
            "parallel_power_force": force(required)/1.0*0.62245}


def c3_scale(n_hat, p0, ell):
    tau = ell/C
    omega = 2*math.pi*C/WAVELENGTH
    hbar = H/(2*math.pi)
    n0 = p0*tau/(hbar*omega)
    return {"N0": n0, "Q": hbar*n0*(omega/C)*n_hat}


def mirror_parities():
    """Sign of the term G*R*(s*dnu/dt - nu*ds/dt) under each operation."""
    signs = {"mirror_x": {"R": -1, "nu": -1, "s": 1, "t": 1},
             "mirror_y": {"R": 1, "nu": 1, "s": 1, "t": 1},
             "time_reversal": {"R": 1, "nu": -1, "s": 1, "t": -1}}
    return {name: s["R"]*s["s"]*s["nu"]*s["t"] for name, s in signs.items()}


def radiative_limit(power, momentum_rate):
    """Proposition R: a reservoir with E >= |p|*c needs |dp/dt|*c <= its power."""
    return abs(momentum_rate)*C <= power


def in_flight_balance(emitted_momentum, converted_fraction):
    """Proposition I: conversion after the boundary moves momentum between
    outgoing reservoirs and leaves the source's recoil where emission set it."""
    light = emitted_momentum*(1-converted_fraction)
    hidden = emitted_momentum*converted_fraction
    return {"source_recoil": -emitted_momentum, "outgoing": light+hidden}
