"""Finite bound arithmetic for the PF-002 identifiability 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.
Section numbers refer to PF002_IDENTIFIABILITY_V1.md. A guard that fails raises
Unproved, which is never a pass.
"""

import math

# Hand-counted outward factor, as in the reference-gain bounds. Conditional on
# ordinary IEEE arithmetic, and not a formal proof.
OUTWARD = 1.00000000001
SEGMENTS = 10
SEGMENT_BINS = 100
FIRST_LIT = 2
DWELLS = 8
SIGMA_ORDER = (1, -1, -1, 1, -1, 1, 1, -1)
EXIT = (1, 1, -1, -1, 1, 1, -1, -1)
SWAP_SEGMENTS = (4, 6, 8)


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


def edges(nominal, fraction, cells):
    """Cell edges of a box around nominal. This study's own definition, 8.0."""
    low, high = nominal*(1-fraction), nominal*(1+fraction)
    step = (high-low)/cells
    return [(low+step*j, low+step*(j+1)) for j in range(cells)]


def decay(tau, dt):
    return math.exp(-dt/tau)


def kernel(a, k, n):
    """Causal unit response at sample k to a unit force in bin n only, 8.5."""
    if n > k:
        return 0.0
    return (1-a)*a**(k-n)


def window_bins(segment, window):
    """Zero-based sample indices of a window in a segment."""
    first = segment*SEGMENT_BINS
    return range(first+window[0]-1, first+window[1])


def hbar(a, window_samples, n):
    """Mean of the causal kernel over a window, zeros counted before n."""
    samples = list(window_samples)
    return math.fsum(kernel(a, k, n) for k in samples)/len(samples)


def hsup(a, window_samples, n):
    return max(kernel(a, k, n) for k in window_samples)


def kernel_interval(a_low, a_high, m):
    """Enclosure of (1 - a)*a^m on [a_low, a_high]. Both factors are positive."""
    return (1-a_high)*a_low**m, (1-a_low)*a_high**m


def hbar_interval(a_low, a_high, window_samples, n):
    samples = list(window_samples)
    low = high = 0.0
    for k in samples:
        if n <= k:
            lo, hi = kernel_interval(a_low, a_high, k-n)
            low += lo
            high += hi
    return low/len(samples), high/len(samples)


def _held_power(a, k, first, last):
    """Exponents of the state at bin k for a unit force held first..last."""
    if k < first:
        return None
    if k <= last:
        return 0, k-first+1
    return k-last, k-first+1


def held_state(a, k, first, last):
    """State at k, closed form, zero-based inclusive bins, from cold zero."""
    powers = _held_power(a, k, first, last)
    if powers is None:
        return 0.0
    return a**powers[0]-a**powers[1]


def held_state_interval(a_low, a_high, k, first, last):
    """Enclosure of a^p - a^q, each power monotone, with 0 < a < 1."""
    powers = _held_power(a_low, k, first, last)
    if powers is None:
        return 0.0, 0.0
    p, q = powers
    return max(0.0, a_low**p-a_high**q), a_high**p-a_low**q


def nominal_force_table(a, window):
    """Window mean and sup of a unit force held one segment, by segment lag."""
    mean, peak = [], []
    for lag in range(SEGMENTS):
        values = [held_state(a, k, 0, SEGMENT_BINS-1)
                  for k in window_bins(lag, window)]
        mean.append(math.fsum(values)/len(values))
        peak.append(max(map(abs, values)))
    return mean, peak


def force_cells(tau, dt, fraction, cells, window):
    """Per cell, per lag: enclosure of the window mean and the sup, 8.0."""
    table = []
    for low, high in edges(tau, fraction, cells):
        a_low, a_high = decay(low, dt), decay(high, dt)
        row = []
        for lag in range(SEGMENTS):
            lows, highs = [], []
            for k in window_bins(lag, window):
                x, y = held_state_interval(a_low, a_high, k, 0, SEGMENT_BINS-1)
                lows.append(x)
                highs.append(y)
            row.append((math.fsum(lows)/len(lows)/OUTWARD,
                        math.fsum(highs)/len(highs)*OUTWARD, max(highs)*OUTWARD))
        table.append(row)
    return table


def cascade_cells(tau_up, tau_ch, dt, fraction, cells, windows, *, up_box=True):
    """Two-stage unit held response by interval unrolling, 64 by 64 cells.

    Stage one is u += w*(input - u), stage two x = a*x + (1 - a)*u. Inputs are
    positive, so all states are too, and each bound uses its own endpoints.
    With up_box False, the first constant is a declared control value.
    Returns {window: [[(low, high) by lag] per cell pair]} and the nominal.
    """
    upper = (edges(tau_up, fraction, cells) if up_box else [(tau_up, tau_up)])
    lower = edges(tau_ch, fraction, cells)
    picks = {}
    total = SEGMENTS*SEGMENT_BINS
    for name, window in windows.items():
        for lag in range(SEGMENTS):
            for k in window_bins(lag, window):
                picks.setdefault(k, []).append((name, lag))
    count = {name: window[1]-window[0]+1 for name, window in windows.items()}
    result = {name: [] for name in windows}
    for up_low, up_high in upper:
        # A larger time constant gives the smaller weight.
        w_low = -math.expm1(-dt/up_high)
        w_high = -math.expm1(-dt/up_low)
        for ch_low, ch_high in lower:
            a_low, a_high = decay(ch_low, dt), decay(ch_high, dt)
            u_lo = u_hi = x_lo = x_hi = 0.0
            sums = {name: [[0.0, 0.0] for _ in range(SEGMENTS)]
                    for name in windows}
            for k in range(total):
                held = 1.0 if k < SEGMENT_BINS else 0.0
                u_lo = (1-w_high)*u_lo+w_low*held
                u_hi = (1-w_low)*u_hi+w_high*held
                x_lo = a_low*x_lo+(1-a_high)*u_lo
                x_hi = a_high*x_hi+(1-a_low)*u_hi
                for name, lag in picks.get(k, ()):
                    sums[name][lag][0] += x_lo
                    sums[name][lag][1] += x_hi
            for name in windows:
                result[name].append(
                    [(lo/count[name]/OUTWARD, hi/count[name]*OUTWARD)
                     for lo, hi in sums[name]])
    return result


def nominal_cascade(tau_up, tau_ch, dt, windows):
    """Point evaluation of the same recursion at nominal constants."""
    w, a = -math.expm1(-dt/tau_up), decay(tau_ch, dt)
    u = x = 0.0
    picks = {}
    for name, window in windows.items():
        for lag in range(SEGMENTS):
            for k in window_bins(lag, window):
                picks.setdefault(k, []).append((name, lag))
    count = {name: window[1]-window[0]+1 for name, window in windows.items()}
    sums = {name: [0.0]*SEGMENTS for name in windows}
    for k in range(SEGMENTS*SEGMENT_BINS):
        u += w*((1.0 if k < SEGMENT_BINS else 0.0)-u)
        x = a*x+(1-a)*u
        for name, lag in picks.get(k, ()):
            sums[name][lag] += x
    return {name: [v/count[name] for v in sums[name]] for name in windows}


def check_gaps(table, limit, floor):
    """Cell gap of 8.0, entry by entry. A failed entry invalidates the row."""
    for row in table:
        for entry in row:
            low, high = entry[0], entry[1]
            mid = (low+high)/2
            if not (math.isfinite(low) and math.isfinite(high)) or low > high:
                raise Unproved("cell enclosure is not an interval")
            if (high-low)/max(abs(mid), floor) > limit:
                raise Unproved("cell gap above its limit")


def lag_coefficients(weights, amplitudes):
    """Signed coefficient of each lag for dwell weights and segment inputs."""
    if len(weights) != DWELLS or len(amplitudes) != SEGMENTS:
        raise ValueError("weights and amplitudes have fixed lengths")
    out = [0.0]*SEGMENTS
    for i, weight in enumerate(weights):
        segment = i+FIRST_LIT
        for j in range(segment+1):
            out[segment-j] += weight*amplitudes[j]
    return out


def sup_change(cells, nominal, coefficients):
    """Sup over cells of |sum c*(T - T_nominal)|, sign kept inside each cell."""
    best = 0.0
    for row in cells:
        low = high = 0.0
        for c, entry, centre in zip(coefficients, row, nominal):
            a, b = c*(entry[0]-centre), c*(entry[1]-centre)
            low += min(a, b)
            high += max(a, b)
        best = max(best, abs(low), abs(high))
    return best*OUTWARD


def sup_response(cells, coefficients, settled):
    """Sup over cells of |sum c*T - settled|, for rho of 8.4."""
    best = 0.0
    for row in cells:
        low = high = -settled
        for c, entry in zip(coefficients, row):
            a, b = c*entry[0], c*entry[1]
            low += min(a, b)
            high += max(a, b)
        best = max(best, abs(low), abs(high))
    return best*OUTWARD


def response_interval(row, coefficients):
    """Enclosure of sum c*T on one cell, with each term's sign kept."""
    low = high = 0.0
    for c, entry in zip(coefficients, row):
        a, b = c*entry[0], c*entry[1]
        low += min(a, b)
        high += max(a, b)
    return low, high


def ratio_change(early_cells, late_cells, coefficients, early_nominal, late_nominal, guard):
    """k_Q and dk_Q of 9.4. No endpoint or monotone claim is made."""
    late = math.fsum(c*v for c, v in zip(coefficients, late_nominal))
    early = math.fsum(c*v for c, v in zip(coefficients, early_nominal))
    if not late > 0:
        raise Unproved("late response is not positive")
    k = early/late
    change = 0.0
    for row_e, row_l in zip(early_cells, late_cells):
        e_low, e_high = response_interval(row_e, coefficients)
        l_low, l_high = response_interval(row_l, coefficients)
        if not l_low > guard*late:
            raise Unproved("late response below its guard")
        corners = (e_low/l_low, e_low/l_high, e_high/l_low, e_high/l_high)
        change = max(change, max(abs(c-k) for c in corners))
    return k, change*OUTWARD


def held_map(cells, weights, amplitudes):
    """Sum over dwells of |weight| times the largest window mean, per cell sup."""
    best = 0.0
    for row in cells:
        total = 0.0
        for i, weight in enumerate(weights):
            segment = i+FIRST_LIT
            total += abs(weight)*math.fsum(
                row[segment-j][1]*abs(amplitudes[j]) for j in range(segment+1))
        best = max(best, total)
    return best*OUTWARD


def bins_map(tau, dt, fraction, cells, weights, window, bins):
    """Map of force bounds in single bins, by the causal kernel, 8.5.

    bins maps a zero-based bin to its force bound. Every later window it
    reaches is counted, and windows before it contribute exactly zero.
    """
    best = 0.0
    for low, high in edges(tau, fraction, cells):
        a_low, a_high = decay(low, dt), decay(high, dt)
        total = 0.0
        for i, weight in enumerate(weights):
            samples = window_bins(i+FIRST_LIT, window)
            for n, value in bins.items():
                total += abs(weight)*value*hbar_interval(a_low, a_high, samples, n)[1]
        best = max(best, total)
    return best*OUTWARD


def swap_bins(value, count):
    """First count bins after each swap, section 8.5."""
    return {segment*SEGMENT_BINS+q: value for segment in SWAP_SEGMENTS
            for q in range(count)}


def exit_sums(sigma=SIGMA_ORDER, exit_pattern=EXIT):
    product = [s*e for s, e in zip(sigma, exit_pattern)]
    return {"sum_e": sum(exit_pattern), "sum_sigma_e": sum(product),
            "sum_i_sigma_e": sum((i+1)*x for i, x in enumerate(product)),
            "sum_i_e": sum((i+1)*x for i, x in enumerate(exit_pattern))}


def separation_margin(distance, error, half):
    """m_W of section 10.1: distance, less the error without its set term."""
    return distance-error-half


def x1_margins(g_min, signal_level, lower, E_z, Ehat_R, Ehat_I, half):
    return {"m_R": separation_margin(g_min*signal_level-E_z, Ehat_R, half),
            "m_I": separation_margin(g_min*lower-E_z, Ehat_I, half)}


def t1_margins(a_goal, E_lev, Ehat_R, Ehat_I, half):
    """T1's impostor world has s = 0, so it carries no recoil null."""
    return {"m_R": separation_margin(a_goal-E_lev, Ehat_R, half),
            "m_I": separation_margin(a_goal-E_lev, Ehat_I, half)}


def m1_sets(a_goal, K):
    """Predicted sets of section 10.2. Truth in the impostor world is h + a."""
    if K < 0 or a_goal <= 0:
        raise Unproved("set parameters")
    return {"recoil": (-K, K), "impostor_magnitude_at_least": a_goal-K}


def m1_margins(a_goal, K, Ehat_R, Ehat_I, half):
    """Both worlds lose 2*K: h runs against a, and the prediction widens."""
    distance = a_goal-2*K
    return {"m_R": separation_margin(distance, Ehat_R, half),
            "m_I": separation_margin(distance, Ehat_I, half),
            "separable": distance > half}


def a_star_m1(required, K, Ehat_R, Ehat_I, half):
    return required+2*K+max(Ehat_R, Ehat_I)+half


def a_star_state(star, transfer_low, force_max):
    """Section 10.3: a value at fixed B says nothing outside its domain."""
    if star/transfer_low <= force_max:
        return "in_domain"
    return "unproved_outside_declared_domain"


def a_star_b1(required, lower, upper, E_S, half):
    """Worst pairing: true recoil at the lower edge, and C - B clearing upper."""
    return required+(upper-lower)+E_S+half
