"""Independent oracle for the PF-002 reference-gain study, version 1.

Virtual lab - simulated experiment tooling. This module imports nothing from
the study or its bounds. It derives bin timing, mechanics and commands itself,
sample by sample, so that a shared mistake cannot agree with itself. Every
quantity here is stated in channel-domain nominal newtons.
"""

import math

DT = 0.1
DWELL_BINS = 100
ORDER = (1, -1, -1, 1, -1, 1, 1, -1)
SWAPS = (1, 1, -1, -1, -1, -1, 1, 1)


def segment_of(n):
    """Zero for D0a, one for D0b, then 1 + dwell. n is a one-based bin."""
    return (n-1)//DWELL_BINS


def late_bins(segment, first=91, last=100):
    return list(range(segment*DWELL_BINS+first, segment*DWELL_BINS+last+1))


def pole(tau):
    return math.exp(-DT/tau)


def previous_same_label(segment, order=ORDER):
    label = order[segment-2]
    for earlier in range(segment-1, 1, -1):
        if order[earlier-2] == label:
            return earlier
    return None


def mean(values):
    return math.fsum(values)/len(values)


def run_r3(case):
    """One channel pair, closed loop, every remainder kept for replay.

    case holds: tau, g, K0, D(c, n), eps(c, n), k(c, segment), phi(c, u),
    h(c, segment), x(c), addend(c, n), order, A, clamp.
    """
    order, A = case["order"], case["A"]
    clamp = case.get("clamp", 1e-10)
    state = {"p": 0.0, "r": 0.0}
    u = {"p": {0: A, 1: 0.0}, "r": {0: A, 1: 0.0}}
    khat, x_hist, y_hist, act = {}, {"p": {}, "r": {}}, {"p": {}, "r": {}}, {}
    a = {c: pole(case["tau"][c]) for c in "pr"}
    saturated = False
    for segment in range(10):
        if segment >= 2:
            for c in "pr":
                if c not in khat:
                    low = mean([y_hist[c][n] for n in late_bins(0)])
                    high = mean([y_hist[c][n] for n in late_bins(1)])
                    khat[c] = (high-low)/A
                previous = previous_same_label(segment, order)
                if previous is None:
                    value = mean([y_hist[c][n] for n in late_bins(1)])/khat[c]
                else:
                    value = u[c][previous]+mean(
                        [y_hist[c][n] for n in late_bins(previous)])/khat[c]
                if abs(value) > clamp:
                    saturated = True
                    value = math.copysign(clamp, value)
                u[c][segment] = value
        forces = {}
        for c in "pr":
            k = case["k"](c, segment)
            full = (1+k)*case["K0"][c]*(u[c][segment]+case["phi"](c, u[c][segment]))
            forces[c] = full
        for c, other in (("p", "r"), ("r", "p")):
            act[c, segment] = (forces[c]+case["h"](c, segment)
                               + case["x"](c)*forces[other])
        for n in range(segment*DWELL_BINS+1, (segment+1)*DWELL_BINS+1):
            for c in "pr":
                state[c] = a[c]*state[c]+(1-a[c])*(
                    case["D"](c, n)-act[c, segment])
                x_hist[c][n] = state[c]
                y_hist[c][n] = ((1+case["g"][c])*(1+case["eps"](c, n))*state[c]
                                + case["addend"](c, n))
    return {"u": u, "khat": khat, "x": x_hist, "y": y_hist, "act": act,
            "saturated": saturated, "a": a}


def filtered_response(values, a):
    """Direct stepping of a force sequence indexed by bin 1..N."""
    out, x = {}, 0.0
    for n in sorted(values):
        x = a*x+(1-a)*values[n]
        out[n] = x
    return out


def unit_mean(a, segment, window_segment, first=91, last=100):
    """bbar: mean response in a window per unit held only in one segment."""
    force = {n: (1.0 if segment_of(n) == segment else 0.0)
             for n in range(1, (window_segment+1)*DWELL_BINS+1)}
    states = filtered_response(force, a)
    return mean([states[n] for n in late_bins(window_segment, first, last)])


def anchor_error(case, run, c):
    """The exact a of protocol section 8.3, term by term, and the direct value."""
    a, g, K0, A = run["a"][c], case["g"][c], case["K0"][c], case["A"]
    D = filtered_response({n: case["D"](c, n) for n in range(1, 201)}, a)
    Db = mean([D[n] for n in late_bins(1)])
    Da = mean([D[n] for n in late_bins(0)])
    b_aa = unit_mean(a, 0, 0)
    b_ba = unit_mean(a, 0, 1)
    b_bb = unit_mean(a, 1, 1)
    k_a = b_aa-b_ba
    h_a, h_b0 = case["h"](c, 0), case["h"](c, 1)
    other = "r" if c == "p" else "p"
    xt_a = case["x"](c)*case["K0"][other]*(A+case["phi"](other, A))
    A_a = K0*(A+case["phi"](c, A))+h_a+xt_a
    X_a = Da-b_aa*A_a
    ebar_a = mean([case["eps"](c, n) for n in late_bins(0)])
    add = mean([case["addend"](c, n) for n in late_bins(1)])-mean(
        [case["addend"](c, n) for n in late_bins(0)])
    terms = {
        "step": k_a-1, "phi": k_a*case["phi"](c, A)/A,
        "memory": k_a*h_a/(K0*A)-b_bb*h_b0/(K0*A),
        "cross": k_a*xt_a/(K0*A), "force": (Db-Da)/(K0*A),
        "gain": -ebar_a*X_a/(K0*A), "addend": add/((1+g)*K0*A)}
    direct = run["khat"][c]/((1+g)*K0)-1
    return math.fsum(terms.values()), direct, terms


def _ab(case, run, c, i):
    a = run["a"][c]
    total = 0.0
    for j in range(i+1):
        total += unit_mean(a, j, i)*run["act"][c, j]
    return total


def whole_error(case, run, c, i):
    """Fhat - (1+g)<D>, directly and from the named terms of section 8.3."""
    a_c, g, K0 = run["a"][c], case["g"][c], case["K0"][c]
    D = filtered_response({n: case["D"](c, n) for n in sorted(run["x"][c])}, a_c)
    bins = late_bins(i)
    meanD = mean([D[n] for n in bins])
    M = mean([run["y"][c][n] for n in bins])
    Fhat = run["khat"][c]*run["u"][c][i]+M
    direct = Fhat-(1+g)*meanD
    anchor, _, _ = anchor_error(case, run, c)
    v = K0*run["u"][c][i]
    P = K0*case["phi"](c, run["u"][c][i])
    k = case["k"](c, i)
    other = "r" if c == "p" else "p"
    other_full = (1+case["k"](other, i))*case["K0"][other]*(
        run["u"][other][i]+case["phi"](other, run["u"][other][i]))
    xt = case["x"](c)*other_full
    Ab = _ab(case, run, c, i)
    A_i = run["act"][c, i]
    bracket = (anchor*v-k*v-(1+k)*P-case["h"](c, i)-xt+(A_i-Ab))
    X = mean([run["x"][c][n] for n in bins])
    ebar = mean([case["eps"](c, n) for n in bins])
    Z = (1+g)*mean([(case["eps"](c, n)-ebar)*run["x"][c][n] for n in bins])
    O = mean([case["addend"](c, n) for n in bins])
    named = (1+g)*bracket+(1+g)*ebar*X+Z+O
    return direct, named


def r1_product(theta_s, theta_i, level):
    """Direct product against the two pieces of section 8.2."""
    direct = ((1+theta_s)*(1+theta_i)-1)*level
    pieces = theta_s*level, (1+theta_s)*theta_i*level
    return direct, pieces


def gain_on_mimic(gain, eps, m0, f=(0.0,)*8, order=ORDER):
    """GR_m for an ideal settled state: sample-free contrast of gain on state."""
    n = len(order)
    return 2/n*math.fsum(
        order[i]*gain*eps[i]*order[i]*m0*(1+f[i]) for i in range(n))


def label_held_mu(a, m0, f, order=ORDER):
    """mu by direct stepping of a label-held mimic, for L_mu to bound below."""
    force = {}
    for n in range(1, 1001):
        segment = segment_of(n)
        force[n] = 0.0 if segment < 2 else order[segment-2]*m0*(1+f[segment-2])
    states = filtered_response(force, a)
    n_dwells = len(order)
    return 2/n_dwells*math.fsum(
        order[i]*mean([states[k] for k in late_bins(i+2)])
        for i in range(n_dwells))


def held_block_x(n, offset):
    """x at the hold block midpoint for one-based bin n, derived independently.

    Hold edges fall at readings offset + 10*m. Bins before the first edge form
    a clipped first block, and every block is clipped to the 100 s session.
    """
    k = n-1
    start = offset+10*((k-offset)//10)
    low = max(0, start)*DT
    high = min(1000, start+10)*DT
    return 2*((low+high)/2)/100.0-1


def slow_contrast(states, a, b, offset, first, last, order=ORDER):
    """Contrast of e*x by direct sum, with e held at its block midpoint value."""
    total = 0.0
    n_dwells = len(order)
    for i in range(n_dwells):
        bins = late_bins(i+2, first, last)
        values = []
        for n in bins:
            x = held_block_x(n, offset)
            values.append((a*x+b*(x*x-1/3))*states[n])
        total += order[i]*mean(values)
    return 2/n_dwells*total


def reference_drive_excess(c, C, b, f):
    """Actual drive at both extremes, less the two separate first-order parts."""
    return c*(1+b)*C*(1+f)-(c*C+b*c*C+f*c*C)


def best_rate_path(coefficients, level, step_size):
    """Largest sum(c*e) under amplitude and slew, with its path, by traceback."""
    count = int(round(2*level/step_size))
    grid = [-level+m*step_size for m in range(count+1)]
    score = [0.0]*len(grid)
    back = []
    for c in coefficients:
        new, pointers = [], []
        for m in range(len(grid)):
            j = max(range(max(0, m-1), min(len(grid), m+2)), key=score.__getitem__)
            new.append(score[j]+c*grid[m])
            pointers.append(j)
        score = new
        back.append(pointers)
    m = max(range(len(grid)), key=score.__getitem__)
    value = score[m]
    path = [grid[m]]
    for pointers in reversed(back[1:]):
        m = pointers[m]
        path.append(grid[m])
    return value, path[::-1]


def tone_state(tau, omega, amplitude, k, tau_i, phi, h):
    """Reference tone state alone, stepped from cold, for dwell values given."""
    a = pole(tau)
    x, out = 0.0, {}
    for n in range(1, 1001):
        segment = segment_of(n)
        i = segment-2
        shift = tau_i[i] if i >= 0 else 0.0
        gain = 1+(k[i] if i >= 0 else 0.0)
        memory = h[i] if i >= 0 else 0.0
        u = amplitude*math.sin(omega*(n*DT+shift))
        x = a*x+(1-a)*(gain*(u+phi(u))+memory)
        out[n] = x
    return out


def window_means(states, first, last):
    return [mean([states[n] for n in late_bins(i+2, first, last)]) for i in range(8)]


def thue_morse_moments(order=ORDER):
    return [math.fsum(s*(i**d) for i, s in enumerate(order)) for d in range(3)]
