"""Independent checks for the PF-002 stationarity study, version 1.

Virtual lab only. Written separately from the study and bounds modules and
imports neither. It uses exact rationals, Gram-Schmidt, high-precision decimal
trigonometry and direct enumeration, so it does not share their parser,
expected values or algebra. Retained scalars are passed in by the tests. Its
witness replay uses the committed observe and derives its own time indices.
"""

from dataclasses import replace
from decimal import Decimal, getcontext
from fractions import Fraction
from itertools import product
import math
import random

from virtual_instruments import observe

getcontext().prec = 60


def thue_morse_moment(count, power):
    """Exact moment of the sequence about its centre, in half-sample units."""
    total = Fraction(0)
    for index in range(count):
        sign = -1 if bin(index).count("1") % 2 else 1
        total += sign*Fraction(2*index+1-count)**power
    return total


def slow_factor(x):
    return abs(x)+abs(x*x-Fraction(1, 3))


def v1_null_margin(gain_level, weight_level, lower, base, heat, p_level,
                   r_level, allowance=4.0, weight=1.05):
    """Robustness v1 tier-B null margin in pN, from retained scalars."""
    noise = 2*(0.5+(weight+weight_level)*0.7)
    vibration = noise/(10*math.sin(math.pi*1.5*0.1))
    gain = 2*(gain_level*p_level+(weight+weight_level)*gain_level*r_level
              + weight_level*r_level)
    return lower-2*(base+heat+noise+vibration+gain)-allowance


def v1_threshold(lower, base, heat, p_level, r_level):
    low, high = 0.0, 0.01
    for _ in range(80):
        middle = (low+high)/2
        if v1_null_margin(middle, middle, lower, base, heat, p_level,
                          r_level) >= 1:
            low = middle
        else:
            high = middle
    return low


def step_response(samples, tau, step=0.1):
    """Closed form of the discrete first-order step response at each sample."""
    keep = math.exp(-step/tau)
    return [1-keep**n for n in range(1, samples+1)]


def held_means(levels, size, first, last, tau, step=0.1):
    """Window means of a first-order lag under dwell-held force.

    Closed form by superposing level steps, with no state recursion, so it
    checks settling independently of the channels. first and last are 1-based.
    """
    means = []
    for dwell in range(len(levels)):
        total = []
        for sample in range(first, last+1):
            k = dwell*size+sample
            total.append(math.fsum(
                (level-(levels[i-1] if i else 0.0))
                * -math.expm1(-(k-i*size)*step/tau)
                for i, level in enumerate(levels[:dwell+1])))
        means.append(math.fsum(total)/len(total))
    return means


def held_contrast(order, force, size, first, last, tau, step=0.1):
    """Label contrast a channel reports for a force held per dwell, unit gain."""
    means = held_means([sigma*force for sigma in order], size, first, last, tau,
                       step)
    return math.fsum(s*m for s, m in zip(order, means))/(len(order)//2)


def convolved(values, tau, step=0.1):
    """First-order response by explicit impulse-response convolution."""
    keep = math.exp(-step/tau)
    powers = [keep**n for n in range(len(values))]
    return [(1-keep)*math.fsum(values[j]*powers[k-j] for j in range(k+1))
            for k in range(len(values))]


def lag_row(order, size, first, last, amplitude, lag, tau_p, tau_r, *,
            late=None, step=0.1):
    """D, U_p and U_r of section 6.8, with no shared recursion or scale.

    late is the window that fixes the scale, when it is not this window.
    """
    held = [order[k//size]*amplitude for k in range(len(order)*size)]
    lagged = convolved(held, lag, step)
    match = late or (first, last)

    def window(states, dwell):
        return states[dwell*size+first-1:dwell*size+last]

    def contrast(states):
        return math.fsum(s*math.fsum(window(states, i))
                         for i, s in enumerate(order))

    def matched(states):
        return math.fsum(s*math.fsum(states[i*size+match[0]-1:i*size+match[1]])
                         for i, s in enumerate(order))

    scale = matched(convolved(held, tau_p, step))/matched(
        convolved(lagged, tau_p, step))
    force = [scale*x for x in lagged]
    primary, reference = convolved(force, tau_p, step), convolved(force, tau_r, step)
    half = len(order)//2
    count = last-first+1
    return {
        "d": abs(contrast(reference)-contrast(primary))/(half*count),
        "u_p": math.fsum(abs(x) for i in range(len(order))
                         for x in window(primary, i))/(half*count),
        "u_r": math.fsum(abs(x) for i in range(len(order))
                         for x in window(reference, i))/(half*count)}


def sample_blocks(order, size, first, last, offset, hold=10):
    """(dwell sign, sample, block, block centre) of every window sample."""
    rows = []
    for dwell, sigma in enumerate(order):
        for k in range(dwell*size+first-1, dwell*size+last):
            block = (k+hold-offset)//hold
            low = max(0, offset+hold*(block-1))
            high = min(800, offset+hold*block)
            rows.append((sigma, k, block, (low+high)/20))
    return rows


def drift_supremum(order, size, first, last, states, *, means=False, hold=10):
    """Largest |sum c_k*e_k| over slow paths and offsets, by corner enumeration.

    With means set, each dwell uses its mean state times its mean path, the
    form revision 11 withdrew, kept here to measure the difference.
    """
    half = len(order)//2
    count = last-first+1
    best = 0.0
    for offset in range(hold):
        rows = sample_blocks(order, size, first, last, offset, hold)
        for a, b in product((-1, 1), repeat=2):
            terms = []
            for sigma, k, _, centre in rows:
                x = 2*centre/80-1
                state = states[k]
                if means:
                    dwell = k//size
                    state = math.fsum(states[dwell*size+first-1:dwell*size+last]
                                      )/count
                terms.append(sigma*(a*x+b*(x*x-1/3))*state/(half*count))
            best = max(best, abs(math.fsum(terms)))
    return best


def block_coefficients(order, size, first, last, states, offset, hold=10):
    """Coefficient of each hold block from sample states, contiguous from 0."""
    half = len(order)//2
    count = last-first+1
    rows = sample_blocks(order, size, first, last, offset, hold)
    series = [0.0]*(max(row[2] for row in rows)+1)
    for sigma, k, block, _ in rows:
        series[block] += sigma*states[k]/(half*count)
    return series


def rate_maximiser(coefficients, steps):
    """Best lattice path by traceback; the levels are a slew-limited witness."""
    size = steps+1
    value = [0.0]*size
    links = []
    for c in reversed(coefficients):
        step, link = [], []
        for j in range(size):
            choices = range(max(0, j-1), min(size, j+2))
            top = max(choices, key=lambda m: value[m])
            step.append(c*(-1+2*j/steps)+value[top])
            link.append(top)
        value = step
        links.append(link)
    j = max(range(size), key=lambda m: value[m])
    best = value[j]
    levels = []
    for link in reversed(links):
        levels.append(-1+2*j/steps)
        j = link[j]
    return best, levels


def rate_bruteforce(coefficients, slew_steps=5):
    """Direct enumeration of slew paths on the lattice, for short sequences."""
    levels = range(-slew_steps, slew_steps+1)
    best = -math.inf
    for path in product(levels, repeat=len(coefficients)):
        if all(abs(a-b) <= 1 for a, b in zip(path, path[1:])):
            value = sum(c*p/slew_steps for c, p in zip(coefficients, path))
            best = max(best, value)
    return best


def gram_schmidt_weights(tau, times, omega):
    """Same defining conditions as the study, by a different construction."""
    n = len(times)
    one = [1/math.sqrt(n)]*n
    mean = math.fsum(times)/n
    ramp = [t-mean for t in times]
    size = math.sqrt(math.fsum(r*r for r in ramp))
    ramp = [r/size for r in ramp]
    response = 1/complex(1, omega*tau)
    tone = [(response*complex(math.cos(omega*t), math.sin(omega*t))).imag
            for t in times]
    for basis in (one, ramp):
        dot = math.fsum(a*b for a, b in zip(tone, basis))
        tone = [t-dot*b for t, b in zip(tone, basis)]
    norm = math.fsum(t*t for t in tone)
    return [t/norm for t in tone]


def _sine(x):
    """Decimal sine by Taylor series, for |x| below a few radians."""
    term, total, n = x, x, 1
    while abs(term) > Decimal(10)**-55:
        term = -term*x*x/((2*n)*(2*n+1))
        total += term
        n += 1
    return total


def _cosine(x):
    term, total, n = Decimal(1), Decimal(1), 1
    while abs(term) > Decimal(10)**-55:
        term = -term*x*x/((2*n-1)*(2*n))
        total += term
        n += 1
    return total


def _arctangent(y):
    """Decimal arctangent by Newton iteration on sine minus y times cosine."""
    x = Decimal(math.atan(float(y)))
    for _ in range(8):
        s, c = _sine(x), _cosine(x)
        x -= (s-y*c)/(c+y*s)
    return x


def precise_weights(tau, times, omega):
    """Weights at 60 digits, from the defining conditions of section 5.4.

    Inputs are the exact binary64 values the study uses.
    """
    tau, omega = Decimal(tau), Decimal(omega)
    grid = [Decimal(t) for t in times]
    gain = 1/(1+(omega*tau)**2).sqrt()
    psi = _arctangent(omega*tau)
    tone = [gain*_sine(omega*t-psi) for t in grid]
    count = Decimal(len(grid))
    mean = sum(grid)/count
    centred = [t-mean for t in grid]
    norm = sum(c*c for c in centred)
    tone_mean = sum(tone)/count
    slope = sum(c*z for c, z in zip(centred, tone))/norm
    perp = [z-tone_mean-slope*c for z, c in zip(tone, centred)]
    size = sum(p*p for p in perp)
    return [p/size for p in perp]


def precise_atan_error(x):
    """Library arctangent against 60 digits, in units in the last place."""
    value = math.atan(x)
    return abs(Decimal(value)-_arctangent(Decimal(x)))/Decimal(math.ulp(value))


def own_window(dwell, first, last, size, step):
    """Reading indices and times of a window, derived here only.

    Sample q of a dwell, counted from 1, is session reading dwell*size + q. A
    reading k, counted from 1, sits at time k*step, the channel bin endpoint.
    """
    readings = [dwell*size+q for q in range(first, last+1)]
    return [k-1 for k in readings], [k*step for k in readings]


def replay_q(witness, *, primary, reference, omega, step, samples, size, dwells,
             first, last, reported_times, amplitude=1e-9):
    """Replay one retained joint tuple through the committed observe.

    Refuses if the caller's window times disagree with those derived here, so
    an off-by-one window cannot be reproduced by sharing it.
    """
    _, times = own_window(0, first, last, size, step)
    if len(times) != len(reported_times) or any(
            abs(x-y) > 1e-12 for x, y in zip(times, reported_times)):
        raise ValueError("window times disagree with the oracle's derivation")

    def readings(balance, gains, shifts):
        quiet = replace(balance, noise_bound_newtons=0.0, offset_newtons=0.0,
                        drift_newtons_per_second=0.0, vibration_newtons=0.0,
                        calibration_fraction=0.0, thermal_newtons_per_watt=0.0)
        drive = []
        for k in range(samples):
            index = k//size
            drive.append(gains[index]*amplitude*math.sin(
                omega*((k+1)*step+shifts[index])))
        return observe(quiet, drive, [0.0]*samples, step, 0)["readings_newtons"]

    def project(tau, xi, series, dwell):
        weights = gram_schmidt_weights(tau*(1+xi), times, omega)
        indices, _ = own_window(dwell, first, last, size, step)
        return math.fsum(u*series[k] for u, k in zip(weights, indices))

    a, k, tau = witness["a"], witness["k"], witness["tau"]
    dwell = witness["dwell"]
    flat = [1.0]*dwells
    zero = [0.0]*dwells
    tau_p, tau_r = primary.response_seconds, reference.response_seconds
    xi_p, xi_r = witness["xi_p"], witness["xi_r"]
    y_p = readings(primary, [1+x for x in a], tau)
    y_r = readings(reference, [(1+x)*(1+y) for x, y in zip(a, k)], tau)
    base_p = readings(primary, flat, zero)
    base_r = readings(reference, flat, zero)
    actual = project(tau_p, xi_p, y_p, dwell)/project(tau_r, xi_r, y_r, dwell)
    steady = (project(tau_p, xi_p, base_p, dwells-1)
              / project(tau_r, xi_r, base_r, dwells-1))
    return actual/steady-1


def precise_sine(x):
    return float(_sine(Decimal(x)))


def precise_cosine(x):
    return float(_cosine(Decimal(x)))


def rectified_mean(amplitude, gain_step, cut, samples=20):
    """Hand value: mean of pilot times a gain step at sample cut of a cycle."""
    tone = [amplitude*math.sin(2*math.pi*(n+1)/samples) for n in range(samples)]
    gain = [gain_step if n >= cut else 0.0 for n in range(samples)]
    return math.fsum(g*t for g, t in zip(gain, tone))/samples


def exponential_projection(weights, times, tau):
    return math.fsum(u*math.exp(-t/tau) for u, t in zip(weights, times))


def dirichlet_kernel(samples, frequency, step):
    return abs(math.sin(math.pi*frequency*samples*step)
               / (samples*math.sin(math.pi*frequency*step)))


def session_ratio_error(thetas, ratios):
    """Exact phi of protocol section 6.3 for given thetas and true ratios."""
    mean = math.fsum(ratios)/len(ratios)
    return math.fsum(r*t for r, t in zip(ratios, thetas))/(len(ratios)*mean)


def exact_rank(rows):
    matrix = [[Fraction(x) for x in row] for row in rows]
    rank = 0
    for column in range(len(matrix[0])):
        pivot = next((r for r in range(rank, len(matrix))
                      if matrix[r][column] != 0), None)
        if pivot is None:
            continue
        matrix[rank], matrix[pivot] = matrix[pivot], matrix[rank]
        for r in range(rank+1, len(matrix)):
            factor = matrix[r][column]/matrix[rank][column]
            matrix[r] = [x-factor*y for x, y in zip(matrix[r], matrix[rank])]
        rank += 1
    return rank


def exact_duplicate_columns(rows, first, second):
    return ([row[first] for row in rows] == [row[second] for row in rows])


def gram_determinant(rows):
    """Exact det(J^T*J), which is the product of squared singular values."""
    matrix = [[Fraction(x) for x in row] for row in rows]
    columns = list(zip(*matrix))
    n = len(columns)
    gram = [[sum(x*y for x, y in zip(columns[i], columns[j]))
             for j in range(n)] for i in range(n)]
    determinant = Fraction(1)
    for column in range(n):
        pivot = next((r for r in range(column, n) if gram[r][column] != 0), None)
        if pivot is None:
            return Fraction(0)
        if pivot != column:
            gram[column], gram[pivot] = gram[pivot], gram[column]
            determinant = -determinant
        determinant *= gram[column][column]
        for r in range(column+1, n):
            factor = gram[r][column]/gram[column][column]
            gram[r] = [x-factor*y for x, y in zip(gram[r], gram[column])]
    return determinant


def injection_forces(signal, common, pilot, kappa, coupling, leak):
    """Exact forces after the transform, with rationals."""
    x = (kappa-leak)*pilot/(coupling-leak)
    y = pilot-x
    return signal+y+common+x, leak*(signal+y)+coupling*(common+x)


def pointwise_null(contrast_w, truth_w, predicted_w, allowance):
    """Interval separation by cases, not the study's closed form."""
    half = abs(contrast_w-truth_w)+allowance
    low, high = contrast_w-half, contrast_w+half
    if high < predicted_w[0]:
        return predicted_w[0]-high
    if low > predicted_w[1]:
        return low-predicted_w[1]
    return -min(high-predicted_w[0], predicted_w[1]-low)


def pointwise_signal(contrast_w, truth_w, allowance):
    half = abs(contrast_w-truth_w)+allowance
    low, high = contrast_w-half, contrast_w+half
    return low if truth_w >= 0 else -high


def uniform_formula(lowers, errors, allowance):
    return min(lowers)-2*max(errors)-allowance


def admissible(draws, limits, noise_path=None):
    """Separate validator: every parameter inside its declared class.

    Returns sorted violation names, so an empty list is admissible. Limits are
    given by the caller, not read from study structures, and blocks are derived
    here. Gain is read at the first sample of a held segment, so a path that
    varies inside a segment would be misrepresented and is refused.
    """
    samples, size = limits["samples"], limits["dwell_samples"]
    hold = limits["hold_samples"]
    series = ("e_p", "e_r", "psi", "xi")
    per_dwell = ("a", "k", "tau", "blind", "common", "phases", "feeds")
    scalars = ("gp", "gr", "w", "leak", "vibration", "xi_p", "xi_r", "kappa",
               "offset")
    missing = [key for key in series+per_dwell+scalars+("order",)
               if key not in draws]
    if missing:
        return sorted("missing_"+key for key in missing)
    bad = set()
    dwells = samples//size

    def within(name, value, bound):
        if not math.isfinite(value) or abs(value) > bound*(1+1e-12):
            bad.add(name)

    within("gp", draws["gp"]-limits["gp_centre"], limits["calibration"])
    within("gr", draws["gr"]-limits["gr_centre"], limits["calibration"])
    within("w", draws["w"]-limits["weight_centre"], limits["weight"])
    within("xi_p", draws["xi_p"], limits["xi"])
    within("xi_r", draws["xi_r"], limits["xi"])
    within("leak", draws["leak"]-limits["leak_centre"], limits["leak"])
    if not draws["leak"] >= 0:
        bad.add("leak")
    low_band, high_band = limits["vibration_band"]
    if not low_band <= draws["vibration"] <= high_band:
        bad.add("vibration")
    if not limits["kappa"][0] <= draws["kappa"] <= limits["kappa"][1]:
        bad.add("kappa")
    if tuple(draws["order"]) not in [tuple(o) for o in limits["orders"]]:
        bad.add("order")
    offset = draws["offset"]
    if type(offset) is not int or not 0 <= offset < hold:
        bad.add("offset")
        offset = 0
    for name in series:
        if len(draws[name]) != samples:
            bad.add(name+"_length")
    for name in per_dwell:
        if len(draws[name]) != dwells:
            bad.add(name+"_length")
    if bad & {name+"_length" for name in series+per_dwell}:
        return sorted(bad)
    for name, bound in (("a", limits["a"]), ("k", limits["k"]),
                        ("tau", limits["tau"]), ("blind", limits["blind"]),
                        ("common", limits["common"])):
        for value in draws[name]:
            within(name, value, bound)
    for phase in draws["phases"]:
        within("phase", abs(phase)-math.pi/2, limits["phase_jitter"])
    for feed in draws["feeds"]:
        within("feed", feed-1, limits["feed_variation"])
    for value in draws["psi"]:
        within("psi", value, limits["phase_jitter"])
    for value in draws["xi"]:
        within("feed_walk", value, limits["feed_variation"])
    # Each element is tested, because a maximum can step over a non-finite one.
    for name, label, bound in (("e_p", "max_e_p", limits["amplitude_p"]),
                               ("e_r", "max_e_r", limits["amplitude_r"])):
        for value in draws[name]:
            if not math.isfinite(value):
                bad.add(name+"_nonfinite")
            elif abs(value) > bound*(1+1e-12):
                bad.add(label)
    if bad & {"e_p_nonfinite", "e_r_nonfinite"}:
        return sorted(bad)
    for name, global_slew, dwell_slew in (
            ("e_p", limits["slew_p"], limits["dwell_slew_p"]),
            ("e_r", limits["slew_r"], limits["dwell_slew_r"])):
        path = draws[name]
        for k in range(samples-1):
            step = abs(path[k+1]-path[k])
            same_dwell = k//size == (k+1)//size
            same_block = ((k+hold-offset)//hold == (k+1+hold-offset)//hold)
            if same_dwell and same_block and step != 0.0:
                bad.add(name+"_hold")
            if same_dwell and step > dwell_slew*(1+1e-12):
                bad.add(name+"_slew")
            if global_slew is not None and step > global_slew*(1+1e-12):
                bad.add(name+"_slew")
    if noise_path is not None:
        for name, values, bound in (("noise_p", noise_path[0], limits["noise_p"]),
                                    ("noise_r", noise_path[1], limits["noise_r"])):
            if len(values) != samples or any(
                    not math.isfinite(x) or abs(x) > bound*(1+1e-12)
                    for x in values):
                bad.add(name)
    return sorted(bad)


def interior_samples(seed, count, ranges):
    """Reproducible random interior points of a continuous box."""
    rng = random.Random(seed)
    for _ in range(count):
        yield tuple(rng.uniform(low, high) for low, high in ranges)
