"""Finite bound evaluations for the PF-002 reference-gain study, version 1.

Virtual lab - simulated experiment tooling. Everything here is pure arithmetic
over declared classes. It never sees a reading, a seed or a generator draw.
Protocol section numbers refer to PF002_REFERENCE_GAIN_V1.md. A guard that
fails returns an unproved result, which is never a pass.
"""

import math

# Each sum below is multiplied by this, section 6.6 of the stationarity protocol.
OUTWARD = 1.00000000001
OUTWARD_INTERVAL = 1e-15
SESSION_BINS = 1000
SEGMENT_BINS = 100
PAIRS = ((2, 3), (4, 5), (6, 7), (8, 9))
# Segment index of the previous same-label dwell, section 8.4. Segments 0 and 1
# are D0a and D0b, and segment i+1 is lit dwell i.
PREVIOUS = {4: 3, 5: 2, 6: 4, 7: 5, 8: 7, 9: 6}
FIRST_OF_LABEL = (2, 3)
LIT = tuple(range(2, 10))
SIGMA_ORDER = (1, -1, -1, 1, -1, 1, 1, -1)


class Unproved(Exception):
    """A required guard failed or a term has no finite bound."""


def segment_bins(segment):
    first = segment*SEGMENT_BINS+1
    return first, first+SEGMENT_BINS-1


def window_bins(segment, window):
    first, _ = segment_bins(segment)
    return tuple(first+q-1 for q in range(window[0], window[1]+1))


def unit_response(a, first, last, k):
    """State at bin k per unit force held over bins first..last, cold start."""
    if k < first:
        return 0.0
    if k <= last:
        return -math.expm1((k-first+1)*math.log(a))
    return a**(k-last)-a**(k-first+1)


def coefficient_tables(a, windows):
    """Per window: max and mean of b_kj over earlier segments, and c_k."""
    tables = {}
    for i, bins in windows.items():
        peak, mean = {}, {}
        for j in range(i+1):
            first, last = segment_bins(j)
            values = [unit_response(a, first, last, k) for k in bins]
            peak[j], mean[j] = max(values), math.fsum(values)/len(values)
        cold = [1-math.fsum(unit_response(a, *segment_bins(j), k)
                            for j in range(i+1)) for k in bins]
        tables[i] = {"peak": peak, "mean": mean, "cold_max": max(map(abs, cold)),
                     "cold_mean": abs(math.fsum(cold)/len(cold))}
    return tables


def anchor_error(ch, params, tables):
    """abar of section 8.3: the sum of the magnitudes of the exact remainders."""
    L, h, x, A = params["L_nl"], params["h_b"], params["x_b"], params["A"]
    Kmin, Kmax = params["Kmin"], params["Kmax"]
    b_aa = tables[0]["mean"][0]
    k_a = b_aa-tables[1]["mean"][0]
    ratio = Kmax/Kmin
    gmin = (1+ch["g_min"])*Kmin
    return ((abs(k_a-1)+k_a*L+k_a*x*ratio*(1+L)+(1+k_a)*h/(Kmin*A)
             + ch["anchor_force_change"]/(Kmin*A)
             + ch["eps_a"]*(ch["Dbar"][0]/(Kmin*A)
                            + b_aa*(1+L+x*ratio*(1+L))+h/(Kmin*A))
             + ch["anchor_addend_change"]/(gmin*A))*OUTWARD), k_a


def _rho(k_b, eps, abar):
    return max((1+k_b)*(1+eps)/(1-abar)-1, 1-(1-k_b)*(1-eps)/(1+abar))


def evaluate_r3(channels, params):
    """Causal finite evaluation of section 8.4, once, with no solver.

    channels maps "p" and "r" to class constants. Dwell order is fixed, and
    each step reads only completed dwells, class constants or step 1 values.
    """
    k_b, L, h, x = (params[n] for n in ("k_b", "L_nl", "h_b", "x_b"))
    A, clamp, Kmin, Kmax = (params[n] for n in ("A", "clamp", "Kmin", "Kmax"))
    if k_b+L >= params["guard_k_plus_L"]:
        raise Unproved("k_b plus L_nl guard")
    Vcap = clamp*Kmax
    Acap = (1+k_b)*(1+L)*Vcap*(1+x)+h
    state = {}
    for c, ch in channels.items():
        abar, k_a = anchor_error(ch, params, ch["tables"])
        if not 0 <= abar < params["guard_abar"]:
            raise Unproved(f"abar guard {c}")
        tables = ch["tables"]
        zbar = (tables[1]["mean"][0]*(Kmax*(1+L)*(1+x*Kmax/Kmin)*A+h)
                + tables[1]["mean"][1]*h)
        addend_b = ch["addend"][1]/(1+ch["g_min"])
        state[c] = {
            "abar": abar, "kA": k_a, "zbar": zbar, "r1": (1+k_b)/(1-abar)-1,
            "Vbar": {0: Kmax*A, 1: 0.0}, "Dv": {}, "Dvc": {}, "Xbar": {},
            "Abar": {1: addend_b}, "Vc": {}, "Dvp": {}, "DA": {}, "Cb": {},
            "Cbm": {}}
    for i in LIT:
        for c, ch in channels.items():
            s = state[c]
            if i in FIRST_OF_LABEL:
                base = (ch["Dbar"][1]+s["zbar"]+s["Abar"][1])/(1-s["abar"])
                s["Vc"][i] = base
                s["Dvc"][i, 1], s["Dvc"][i, 0] = base, base+Kmax*A
                if i == FIRST_OF_LABEL[1]:
                    s["Dvc"][i, FIRST_OF_LABEL[0]] = 0.0
            else:
                p = PREVIOUS[i]
                step = ((1+ch["eps_b"])*s["Xbar"][p]+s["Abar"][p])/(1-s["abar"])
                s["Dvp"][i] = step
                s["Vc"][i] = s["Vbar"][p]+step
                for j in range(i):
                    if j == p:
                        s["Dvc"][i, j] = step
                    else:
                        s["Dvc"][i, j] = s["Dv"][max(p, j), min(p, j)]+step
        for c, ch in channels.items():
            s, o = state[c], state["r" if c == "p" else "p"]
            for j in range(i):
                xt = x*((1+k_b)*(1+L)*o["Dvc"][i, j]+2*k_b*(1+L)*o["Vbar"][j])
                s["DA"][i, j] = ((1+k_b)*(1+L)*s["Dvc"][i, j]
                                 + 2*k_b*(1+L)*s["Vbar"][j]+2*h+xt)
            tab = ch["tables"][i]
            s["Cb"][i] = math.fsum(tab["peak"][j]*s["DA"][i, j] for j in range(i))
            s["Cbm"][i] = math.fsum(tab["mean"][j]*s["DA"][i, j] for j in range(i))
        for c, ch in channels.items():
            s, o = state[c], state["r" if c == "p" else "p"]
            tab = ch["tables"][i]
            r1 = s["r1"]
            if i in FIRST_OF_LABEL:
                value = (ch["DD"][i, 1]+r1*ch["Dbar"][1]
                         + (1+r1)*(s["zbar"]+s["Abar"][1])
                         + (1+k_b)*L*s["Vc"][i]+h
                         + x*(1+k_b)*(1+L)*o["Vc"][i]
                         + tab["cold_max"]*Acap+s["Cb"][i])
            else:
                p = PREVIOUS[i]
                rho = _rho(k_b, ch["eps_b"], s["abar"])
                if rho >= params["guard_rho"]:
                    raise Unproved(f"rho guard {c}")
                xt = x*((1+k_b)*(1+L)*o["Dvp"][i]
                        + 2*k_b*(1+L)*o["Vbar"][p])
                value = (rho*s["Xbar"][p]+(1+r1)*s["Abar"][p]
                         + 2*k_b*(1+L)*s["Vbar"][p]+(1+k_b)*L*s["Dvp"][i]
                         + 2*h+xt+ch["DD"][i, p]+tab["cold_max"]*Acap
                         + ch["tables"][p]["cold_mean"]*Acap
                         + s["Cb"][i]+s["Cbm"][p])
            s["Xbar"][i] = value*OUTWARD
        for c, ch in channels.items():
            s, o = state[c], state["r" if c == "p" else "p"]
            tab = ch["tables"][i]
            if tab["cold_max"] >= params["guard_cold"]:
                raise Unproved(f"cold guard {c}")
            floor = (1-k_b)*(1-L)
            refined = ((ch["Dbar"][i]+s["Xbar"][i]+s["Cb"][i])
                       / (1-tab["cold_max"])+h
                       + x*(1+k_b)*(1+L)*o["Vc"][i])/floor
            s["Vbar"][i] = min(s["Vc"][i], refined)
            for j in range(i):
                value = s["Dvc"][i, j]
                if j in LIT:
                    xt = x*((1+k_b)*(1+L)*o["Dvc"][i, j]
                            + 2*k_b*(1+L)*o["Vbar"][j])
                    other = ((ch["DD"][i, j]+s["Xbar"][i]+s["Xbar"][j]
                              + s["Cb"][i]+s["Cb"][j]
                              + (tab["cold_max"]
                                 + ch["tables"][j]["cold_max"])*Acap
                              + 2*k_b*(1+L)*s["Vbar"][j]+2*h+xt)/floor)
                    value = min(value, other)
                s["Dv"][i, j] = value
            s["Abar"][i] = (ch["addend"][i]/(1+ch["g_min"])
                            + ch["Dhat"]*s["Xbar"][i])
    return state


def early_states(channels, state, params, early):
    """Early-window state bound, from one dwell's identity at two samples.

    Commands come from late windows only, so the recurrence stays on late
    windows. Then x_k - x_l is the force difference plus remainders in A_i - A_j.
    """
    k_b, L, h, x = (params[n] for n in ("k_b", "L_nl", "h_b", "x_b"))
    Acap = (1+k_b)*(1+L)*params["clamp"]*params["Kmax"]*(1+x)+h
    result = {}
    for c, ch in channels.items():
        s = state[c]
        result[c] = {}
        for i in LIT:
            tab = early[c]["tables"][i]
            late = ch["tables"][i]
            carry = math.fsum(tab["peak"][j]*s["DA"][i, j] for j in range(i))
            result[c][i] = ((s["Xbar"][i]+early[c]["DD"][i]+carry+s["Cb"][i]
                             + (tab["cold_max"]+late["cold_max"])*Acap)*OUTWARD)
    return result


def r3_terms(channels, state, params, early=None):
    """The terms of the section 8.4 table, per channel, then their weighted sum.

    With early given, the carry and gain terms use the early window's state and
    coefficients. The anchor and command terms do not depend on the window.
    """
    k_b, L, h, x = (params[n] for n in ("k_b", "L_nl", "h_b", "x_b"))
    Acap = (1+k_b)*(1+L)*params["clamp"]*params["Kmax"]*(1+x)+h
    n = len(LIT)
    vc = {c: 2/n*math.fsum(state[c]["Dv"][b, a] for a, b in PAIRS)
          for c in channels}
    states = early_states(channels, state, params, early) if early else None
    out = {}
    total = 0.0
    for c, ch in channels.items():
        s, o = state[c], state["r" if c == "p" else "p"]
        other = "r" if c == "p" else "p"
        vbar = 2/n*math.fsum(s["Vbar"][i] for i in LIT)
        terms = {
            "T_a": s["abar"]*vc[c], "T_k": k_b*vbar, "T_kP": k_b*L*vbar,
            "T_P": L*vc[c], "T_h": 2*h,
            "T_xt": x*((1+L)*vc[other]+2/n*math.fsum(
                k_b*(1+L)*o["Vbar"][i] for i in LIT)),
            "T_carry": 2/n*math.fsum(
                ch["tables"][i]["cold_max"]*Acap+s["Cbm"][i] for i in LIT),
            "T_gain": 2/n*math.fsum(ch["eps_b"]*s["Xbar"][i] for i in LIT)}
        if early:
            tables = early[c]["tables"]
            terms["T_carry"] = 2/n*math.fsum(
                tables[i]["cold_max"]*Acap+math.fsum(
                    tables[i]["mean"][j]*s["DA"][i, j] for j in range(i))
                for i in LIT)
            terms["T_gain"] = 2/n*math.fsum(
                ch["eps_b"]*states[c][i] for i in LIT)
        out[c] = terms
        total += ch["W"]*ch["G1"]*math.fsum(terms.values())
    return out, total*OUTWARD, vc


def large_stimulus_states(channels, params, forces):
    """Section 8.5: the clamp may act, so no recurrence or contraction is used."""
    k_b, L, h, x = (params[n] for n in ("k_b", "L_nl", "h_b", "x_b"))
    Vcap = params["clamp"]*params["Kmax"]
    Acap = (1+k_b)*(1+L)*Vcap*(1+x)+h
    result = {}
    for c, ch in channels.items():
        result[c] = {i: (forces[c]+ch["Dbar"][i]
                         + Acap*(1+ch["tables"][i]["cold_max"])) for i in LIT}
    return result, Vcap


def r3_large_stimulus(channels, params, forces):
    k_b, L, h, x = (params[n] for n in ("k_b", "L_nl", "h_b", "x_b"))
    states, Vcap = large_stimulus_states(channels, params, forces)
    Acap = (1+k_b)*(1+L)*Vcap*(1+x)+h
    n = len(LIT)
    total = 0.0
    for c, ch in channels.items():
        abar, _ = anchor_error(ch, params, ch["tables"])
        vc = 2/n*len(PAIRS)*2*Vcap
        carry = 2/n*math.fsum(
            ch["tables"][i]["cold_max"]*Acap
            + math.fsum(ch["tables"][i]["mean"][j]*2*Acap for j in range(i))
            for i in LIT)
        gain = 2/n*math.fsum(ch["eps_b"]*states[c][i] for i in LIT)
        total += ch["W"]*ch["G1"]*(abar*vc+2*k_b*(1+L)*Vcap+L*vc+2*h
                                   + x*(1+L)*vc+carry+gain)
    return total*OUTWARD


def r1_mix(W, G_r, G_p, bracket, steps, level, tone_peak, x_b):
    """E_mix of section 8.2: in-window gain on the level and the tone's swing."""
    return (2*W*G_r*(1+bracket)*steps[1]*(level+tone_peak)
            + 2*G_p*steps[0]*x_b*tone_peak)*OUTWARD


def tone_weights(a, omega, step, window):
    """S_ij, C_ij and B_ij of section 8.2, by direct sum of the sample weights."""
    table = {}
    count = window[1]-window[0]+1
    for i in LIT:
        bins = window_bins(i, window)
        for j in LIT:
            if j > i:
                continue
            first, last = segment_bins(j)
            s = c = b = 0.0
            for k in bins:
                for n in range(first, min(last, k)+1):
                    weight = (1-a)*a**(k-n)/count
                    time = n*step
                    s += weight*math.sin(omega*time)
                    c += weight*math.cos(omega*time)
                    b += weight
            table[i, j] = (s, c, b)
    return table


def tone_deviation(table, Kmax, A, k_b, L, delta, h):
    """Td_i of section 8.2. No shared period or decay is assumed here."""
    result = {}
    cosine, sine = 1-math.cos(delta), math.sin(delta)
    for i in LIT:
        total = 0.0
        for j in LIT:
            if j > i:
                continue
            s, c, b = table[i, j]
            total += (Kmax*A*((1+k_b)*(abs(s)*cosine+abs(c)*sine)+k_b*abs(s)
                              + L*b*(k_b+(1+k_b)*delta))+2*h*b)
        result[i] = total*OUTWARD
    return result


def theta_interval(blocks, lower, k_b, q):
    """Exact interval of section 8.2 for one dwell, or a refusal."""
    if lower <= 0 or blocks/lower > 0.25:
        raise Unproved("projection denominator guard")
    x = blocks/lower
    return 1/((1-k_b)*(1-q)*(1-x))-1


def r1_terms(settings):
    """Terms of the section 8.2 table, with the anchor and dwell cross-product."""
    s = settings
    n = len(LIT)
    W, G1 = s["W"], s["G1_r"]
    e_p = 2/n*math.fsum(s["G1_p"]*s["eps_p"]*s["Xbar_p"][i] for i in LIT)
    e_thd = 2/n*math.fsum(W*G1*(1+s["theta_s"])*s["theta"][i]*s["Xbar_r"][i]
                          for i in LIT)
    e_ths = W*G1*s["theta_s"]*s["XC_r"]
    e_mod = 2/n*math.fsum(W*s["bracket"][i]*s["offset_path"][i] for i in LIT)
    return {"E_p": e_p*OUTWARD, "E_thd": e_thd*OUTWARD, "E_ths": e_ths*OUTWARD,
            "E_mod": e_mod*OUTWARD}


def detection_bound(settings):
    """A_unflag of section 7.3, or None when its guards fail."""
    s = settings
    if s["L_mu"] < s["guard_L_mu"]:
        return {"status": "unproved", "reason": "L_mu guard"}
    psi_min = 1-(1+s["dk"])*s["coupling_ratio_max"]*s["b_w_max"]
    lam_m = (2*s["G_r_max"]*s["eps_r"]
             + s["kbar"]*s["G_w_max"]*s["b_w_max"]
             * (2*s["eps_w"]+4*(s["beta_w"]+s["beta_r"])))
    psi_eff = psi_min-lam_m*(1+s["f"])/(2*s["L_mu"]*s["G_r_min"])
    if psi_eff <= s["guard_psi"]:
        return {"status": "unproved", "reason": "psi_eff guard", "psi_eff": psi_eff,
                "lam_m": lam_m}
    return {"status": "bounded", "psi_eff": psi_eff, "psi_min": psi_min,
            "lam_m": lam_m,
            "A_unflag": 2*s["Nbar"]/(s["G_r_min"]*psi_eff)*OUTWARD}


def l_mu(a, f, windows):
    """Explicit finite response lower bound of section 7.3, at R's response."""
    values = []
    tables = coefficient_tables(a, windows)
    for i in LIT:
        own = tables[i]["mean"][i]
        earlier = math.fsum(tables[i]["mean"][j] for j in LIT if j < i)
        values.append((1-f)*own-(1+f)*earlier)
    return math.fsum(values)/len(values)


def rate_bound(coefficients, level, step):
    """Largest sum(c_k*e_k), |e_k| <= level, |e_k - e_(k-1)| <= step, exact."""
    count = int(math.floor(2*level/step+1e-9))
    grid = [-level+m*step for m in range(count+1)]
    best = [0.0]*len(grid)
    for c in coefficients:
        moved = []
        for m in range(len(grid)):
            around = best[max(0, m-1):m+2]
            moved.append(max(around)+c*grid[m])
        best = moved
    return max(best)


def _times(p, q):
    values = [a*b for a in p for b in q]
    return min(values), max(values)


def _widen(value):
    margin = max(abs(value[0]), abs(value[1]), 1e-300)*OUTWARD_INTERVAL
    return value[0]-margin, value[1]+margin


def ratio_direction(sigma, early, late, low, high, cells, step):
    """Sign of d(C_early/C_late)/dtau on every cell, or None if not strict.

    Outward interval forward sensitivity of the first-order recursion, in the
    form x - d, which keeps a and d from being counted as independent.
    """
    directions = set()
    for c in range(cells):
        t0, t1 = low+(high-low)*c/cells, low+(high-low)*(c+1)/cells
        a = (math.exp(-step/t0), math.exp(-step/t1))
        da = (step/t1**2*a[0], step/t0**2*a[1])
        x = y = (0.0, 0.0)
        totals = {"e": [0.0, 0.0, 0.0, 0.0], "l": [0.0, 0.0, 0.0, 0.0]}
        for k in range(SESSION_BINS):
            drive = 0.0 if k < 200 else float(sigma[k//100-2])
            z = (x[0]-drive, x[1]-drive)
            part = _times(a, z)
            x = _widen((drive+part[0], drive+part[1]))
            one, two = _times(a, y), _times(da, z)
            y = _widen((one[0]+two[0], one[1]+two[1]))
            if k >= 200:
                q = k%100+1
                sign = sigma[k//100-2]
                state = x if sign > 0 else (-x[1], -x[0])
                slope = y if sign > 0 else (-y[1], -y[0])
                for name, window in (("e", early), ("l", late)):
                    if window[0] <= q <= window[1]:
                        total = totals[name]
                        total[0] += state[0]
                        total[1] += state[1]
                        total[2] += slope[0]
                        total[3] += slope[1]
        scale_e, scale_l = early[1]-early[0]+1, late[1]-late[0]+1
        e = [v/scale_e for v in totals["e"]]
        l = [v/scale_l for v in totals["l"]]
        if l[0] <= 0:
            return None
        left = _times(e[2:], l[:2])
        right = _times(e[:2], l[2:])
        number = _widen((left[0]-right[1], left[1]-right[0]))
        if number[0] > 0:
            directions.add(1)
        elif number[1] < 0:
            directions.add(-1)
        else:
            return None
    return directions.pop() if len(directions) == 1 else None


def r2_narrow_label(s_p, s_r, x_p, x_r, residual, z, chi, W):
    """E_label,N of section 8.1, from the frozen pattern's direct sums."""
    return (2*z*(s_p*x_p+W*s_r*x_r)+(s_p+s_r)*abs(residual)
            + chi*(s_p+s_r)*(x_p+W*x_r))*OUTWARD


def r2_narrow_mimic(s_p, s_r, nominal, f, z, chi):
    return (1+f)*nominal*(z*s_r+chi*(s_p+s_r)/2)*OUTWARD
