"""Validated enclosures for the PF-002 stationarity study, version 1.

Virtual lab only. Pilot projection weights depend nonlinearly on the estimator's
time constants, so bounds over a continuous range use subdivision and the mean
value theorem, not corner scans. Each weight is a midpoint and a radius from
explicit derivative bounds, plus a composed rounding bound. Everything here is
conditional on assumptions A1 and A2 of protocol section 6.6. A2, the accuracy
of the platform library, is sampled by fixtures and is not proved.
"""

import math

U0 = 2.0**-53
OUTWARD = 1.00000000001


def gap_check(name, kind, bound, point, floor, limit):
    """Enclosure gap rule of protocol section 6.6.

    The point is one jointly admissible realisation, so it is a lower witness
    of the supremum. A point past its bound is a soundness defect, never a pass.
    """
    if kind == "supremum":
        gap = bound-point
    elif kind == "infimum":
        gap = point-bound
    else:
        raise ValueError("unsupported enclosure kind")
    if gap < -8*U0*(abs(bound)+abs(point)):
        raise ValueError(f"soundness defect, point past its bound: {name}")
    return {"name": name, "kind": kind, "bound": bound, "point": point,
            "gap": gap, "floor": floor,
            "passed": gap <= limit*max(abs(bound), floor)}


def rounding_radius(tau, times, omega, tone, perp, factors, size):
    """Composed bound on each computed weight, protocol section 6.6."""
    gain, psi = _tone(tau, omega)
    largest = max(abs(omega*t) for t in times)
    angle = max(abs(omega*t-psi) for t in times)
    e_arg = U0*(3*largest+14*abs(psi)+2*angle)
    e_z = gain*(e_arg+20*U0)
    top = max(abs(z) for z in tone)
    e_perp = [f*(e_z+8*U0*top) for f in factors]
    e_size = (2*math.fsum(abs(p)*e for p, e in zip(perp, e_perp))
              + math.fsum(e*e for e in e_perp)+4*U0*size)
    if size <= e_size:
        raise ValueError("rounding bound does not clear the projection size")
    return [OUTWARD*(e+abs(p)*e_size/size+U0*abs(p))/(size-e_size)
            for p, e in zip(perp, e_perp)]


def _basis(times):
    mean = math.fsum(times)/len(times)
    centred = [t-mean for t in times]
    return centred, math.fsum(c*c for c in centred)


def perpendicular(values, centred, norm):
    """Remove the least-squares fit on constant and sample time."""
    mean = math.fsum(values)/len(values)
    slope = math.fsum(c*v for c, v in zip(centred, values))/norm
    return [v-mean-slope*c for v, c in zip(values, centred)]


def orthogonal_part(vector, times):
    """Part of a vector the weights can see.

    Every weight vector is exactly orthogonal to constant and sample time for
    any tau_hat, so this changes no projection. Enclosing this part avoids
    charging the radius of u against a level that projects to zero exactly.
    """
    centred, norm = _basis(times)
    return perpendicular(vector, centred, norm)


def _tone(tau, omega):
    gain = 1/math.sqrt(1+(omega*tau)**2)
    return gain, math.atan(omega*tau)


def weights_with_radius(tau, times, omega):
    """Computed weights and their composed rounding bound, for one tau."""
    gain, psi = _tone(tau, omega)
    tone = [gain*math.sin(omega*t-psi) for t in times]
    centred, norm = _basis(times)
    perp = perpendicular(tone, centred, norm)
    size = math.fsum(p*p for p in perp)
    radius = rounding_radius(tau, times, omega, tone, perp,
                             projector_factors(times), size)
    return [p/size for p in perp], radius


def point_weights(tau, times, omega):
    """Exact finite-sample weights for one time constant, section 5.4."""
    gain, psi = _tone(tau, omega)
    tone = [gain*math.sin(omega*t-psi) for t in times]
    centred, norm = _basis(times)
    perp = perpendicular(tone, centred, norm)
    size = math.fsum(p*p for p in perp)
    if size <= 0:
        raise ValueError("projection tone vanished")
    return [p/size for p in perp]


def projector_factors(times):
    """Row sum bound of the projector, f_n of protocol section 6.6."""
    centred, norm = _basis(times)
    spread = math.fsum(abs(c) for c in centred)/norm
    return [2+abs(c)*spread for c in centred]


def _cell(tau, half, times, omega, centred, norm, factors):
    gain, psi = _tone(tau, omega)
    top = tau+half
    high = 1/math.sqrt(1+(omega*(tau-half))**2)
    d_gain = omega*omega*top*high**3
    d_psi = omega*high*high
    d2_gain = omega*omega*high**3+3*omega**4*top*top*high**5
    d2_psi = 2*omega**3*top*high**4
    first = d_gain+high*d_psi
    second = d2_gain+2*d_gain*d_psi+high*d2_psi+high*d_psi*d_psi
    tone, rate = [], []
    for t in times:
        s, c = math.sin(omega*t-psi), math.cos(omega*t-psi)
        tone.append(gain*s)
        rate.append(-omega*omega*tau*gain**3*s-gain*omega*gain*gain*c)
    perp = perpendicular(tone, centred, norm)
    perp_rate = perpendicular(rate, centred, norm)
    size = math.fsum(p*p for p in perp)
    low_size = math.fsum(max(0.0, abs(p)-half*first*f)**2
                         for p, f in zip(perp, factors))
    if low_size <= 0:
        raise ValueError("projection norm not bounded away from zero")
    perp_bound = [abs(p)+half*first*f for p, f in zip(perp, factors)]
    rate_bound = [abs(p)+half*second*f for p, f in zip(perp_rate, factors)]
    cross = math.fsum(p*r for p, r in zip(perp_bound, rate_bound))
    mid = [p/size for p in perp]
    rounding = rounding_radius(tau, times, omega, tone, perp, factors, size)
    rad = [OUTWARD*half*(r/low_size+2*p*cross/low_size**2)+e
           for r, p, e in zip(rate_bound, perp_bound, rounding)]
    return mid, rad


_cell_cache = {}


def weight_cells(tau, knowledge, count, times, omega):
    """Midpoint and radius of the weights on each cell of the tau_hat range."""
    key = (tau, knowledge, count, tuple(times), omega)
    if key in _cell_cache:
        return _cell_cache[key]
    centred, norm = _basis(times)
    factors = projector_factors(times)
    half = OUTWARD*tau*knowledge/count
    cells = []
    for index in range(count):
        centre = tau*(1-knowledge+(2*index+1)*knowledge/count)
        cells.append(_cell(centre, half, times, omega, centred, norm, factors))
    _cell_cache[key] = cells
    return cells


def _sum(mid, rad, vector):
    total = math.fsum(m*v for m, v in zip(mid, vector))
    slack = math.fsum(r*abs(v) for r, v in zip(rad, vector))
    size = math.fsum(abs(m*v) for m, v in zip(mid, vector))
    return total, OUTWARD*slack+2*U0*size+U0*abs(total)


def linear_range(cells, vector):
    """Validated range of sum(u*vector), and the range at cell midpoints."""
    low, high = math.inf, -math.inf
    point_low, point_high = math.inf, -math.inf
    for mid, rad in cells:
        total, slack = _sum(mid, rad, vector)
        low, high = min(low, total-slack), max(high, total+slack)
        point_low = min(point_low, total)
        point_high = max(point_high, total)
    return low, high, point_low, point_high


def sup_abs(cells, vector):
    """Validated supremum of abs(sum(u*vector)), and its best point value."""
    low, high, point_low, point_high = linear_range(cells, vector)
    return max(abs(low), abs(high)), max(abs(point_low), abs(point_high))


def ratio_sup_abs(cells, numerator, denominator):
    """Supremum of abs(sum(u*numerator)/sum(u*denominator)) on each cell."""
    bound, point = 0.0, 0.0
    for mid, rad in cells:
        top, top_slack = _sum(mid, rad, numerator)
        bottom, bottom_slack = _sum(mid, rad, denominator)
        if bottom-bottom_slack <= 0:
            raise ValueError("projection denominator not positive")
        bound = max(bound, (abs(top)+top_slack)/(bottom-bottom_slack))
        point = max(point, abs(top)/bottom)
    return bound, point


def ratio_range(cells, numerator, denominator):
    """Signed validated range of sum(u*numerator)/sum(u*denominator)."""
    low, high = math.inf, -math.inf
    for mid, rad in cells:
        top, top_slack = _sum(mid, rad, numerator)
        bottom, bottom_slack = _sum(mid, rad, denominator)
        if bottom-bottom_slack <= 0:
            raise ValueError("projection denominator not positive")
        for value in ((top-top_slack)/(bottom-bottom_slack),
                      (top-top_slack)/(bottom+bottom_slack),
                      (top+top_slack)/(bottom-bottom_slack),
                      (top+top_slack)/(bottom+bottom_slack)):
            low, high = min(low, value), max(high, value)
    return low, high


def noise_gain(cells, denominator):
    """Supremum of sum(|u|)/sum(u*denominator): correlated within one cell."""
    bound, point = 0.0, 0.0
    for mid, rad in cells:
        bottom, slack = _sum(mid, rad, denominator)
        if bottom-slack <= 0:
            raise ValueError("projection denominator not positive")
        size = math.fsum(abs(m) for m in mid)
        bound = max(bound, (size+math.fsum(rad))/(bottom-slack))
        point = max(point, size/bottom)
    return bound*OUTWARD, point


def kernel(cells, times, band, frequency_cells):
    """Validated magnitude of sum(u*exp(2 pi i f t)) over band and cells."""
    centre = math.fsum(times)/len(times)
    offsets = [2*math.pi*(t-centre) for t in times]
    half = (band[1]-band[0])/(2*frequency_cells)
    bound, point = 0.0, 0.0
    for mid, rad in cells:
        size = math.fsum(rad)+10*U0*math.fsum(abs(m) for m in mid)
        drift = math.fsum((abs(m)+r)*abs(o)
                          for m, r, o in zip(mid, rad, offsets))
        for index in range(frequency_cells):
            f = band[0]+(2*index+1)*half
            real = math.fsum(m*math.cos(f*o) for m, o in zip(mid, offsets))
            imag = math.fsum(m*math.sin(f*o) for m, o in zip(mid, offsets))
            value = math.hypot(real, imag)
            point = max(point, value)
            slack = size+half*drift
            bound = max(bound, math.hypot(abs(real)+slack, abs(imag)+slack))
    return bound*OUTWARD, point


def mean_kernel(samples, frequency, step):
    """Mean of a unit sinusoid over equal samples, any phase, band edge bound."""
    return 1/(samples*math.sin(math.pi*frequency*step))


def vertex_paths(blocks, step):
    """Block values of a path whose adjacent change is at most step."""
    paths = [(0.0,)]
    for _ in range(blocks-1):
        paths = [p+(p[-1]+delta,) for p in paths
                 for delta in (-step, 0.0, step)]
    return paths
