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

Virtual lab - simulated experiment tooling. It imports nothing from the study,
its bounds or any channel, detector or reference-gain module. Constants are
written here from the frozen apparatus table. It steps mechanics sample by
sample, computes mirror maps and finite response matrices its own way, and
holds exact rational structure tables, so a shared mistake must be made twice.
"""

from fractions import Fraction
import math

STEP = 0.1
SIGMA = (1, -1, -1, 1, -1, 1, 1, -1)
EXIT = (1, 1, -1, -1, 1, 1, -1, -1)
LATE = (90, 100)
EARLY = (40, 50)
# Response, thermal, thermal N/W: the frozen primary and reference channels.
PRIMARY = (1.0, 10.0, 5e-13)
REFERENCE = (1.5, 12.0, 6e-13)


def constants(name):
    """Reference and catcher-reference channels start r or u."""
    return REFERENCE if name[0] in "ru" else PRIMARY


def replay_state(channel, force, heat):
    """Mechanical state, direct recursion, from cold zero."""
    tau, tau_t, coefficient = channel
    heat_factor = 1.05 if channel is REFERENCE else 1.0
    a = math.exp(-STEP/tau)
    w = 1-math.exp(-STEP/tau_t)
    x = th = 0.0
    out = []
    for f, q in zip(force, heat):
        th = th+w*(q*coefficient*heat_factor-th)
        x = a*x+(1-a)*(f+th)
        out.append(x)
    return out


def step_force(force, tau):
    a = math.exp(-STEP/tau)
    x = 0.0
    out = []
    for f in force:
        x = a*x+(1-a)*f
        out.append(x)
    return out


def causal_response(tau, n, total=1000):
    """Unit force in bin n by stepping. Earlier samples are exactly zero."""
    force = [0.0]*total
    force[n] = 1.0
    return step_force(force, tau)


def window_mean(values, segment, window):
    first = segment*100
    part = values[first+window[0]:first+window[1]]
    return sum(part)/len(part)


def unit_pattern(amplitudes):
    """Dwell amplitudes held on lit segments, zero before."""
    out = [0.0]*200
    for a in amplitudes:
        out += [float(a)]*100
    return out


def lagged(pattern, tau):
    w = 1-math.exp(-STEP/tau)
    u = 0.0
    out = []
    for f in pattern:
        u = u+w*(f-u)
        out.append(u)
    return out


def contrast(state, signs, window):
    return 2/len(signs)*sum(s*window_mean(state, i+2, window)
                            for i, s in enumerate(signs))


# Mirror map, exact.

def _multiply(a, b):
    return [[sum(a[i][k]*b[k][j] for k in range(3)) for j in range(3)]
            for i in range(3)]


def reflection(normal):
    size = sum(x*x for x in normal)
    return [[Fraction(int(i == j))-2*normal[i]*normal[j]/size for j in range(3)]
            for i in range(3)]


def inverter(sine, cosine):
    """Three plane mirrors at lines +a, 0, -a in the (y, z) plane, frame phi = 0."""
    first = reflection((Fraction(0), cosine, -sine))
    second = reflection((Fraction(0), Fraction(1), Fraction(0)))
    third = reflection((Fraction(0), cosine, sine))
    return _multiply(third, _multiply(second, first))


def turned(matrix):
    """The same element turned 90 degrees about z."""
    turn = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
    back = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]]
    return _multiply(turn, _multiply(matrix, back))


# Exact structure tables, representative rationals only.

def rank(rows):
    matrix = [[Fraction(x) for x in row] for row in rows]
    found = 0
    for column in range(len(matrix[0])):
        pivot = next((i for i in range(found, len(matrix)) if matrix[i][column]), None)
        if pivot is None:
            continue
        matrix[found], matrix[pivot] = matrix[pivot], matrix[found]
        for i in range(len(matrix)):
            if i != found and matrix[i][column]:
                ratio = matrix[i][column]/matrix[found][column]
                matrix[i] = [a-ratio*b for a, b in zip(matrix[i], matrix[found])]
        found += 1
    return found


F = Fraction
T, K_, QL, QE, AB, KB, LR, CB = (F(19, 20), F(3, 4), F(9, 10), F(1, 5), F(7, 10),
                                 F(2, 3), F(1, 20), F(21, 20))


def base_rows():
    return [[T, T, T*QL, 0, AB], [0, 0, 0, T, 0], [T*K_, T*K_, T*QE, 0, AB*KB],
            [0, 0, 0, T*K_, 0], [LR, LR, LR*QL, LR, CB]]


def x1_rows(g=F(97, 100), ce=F(1, 50), cs=F(1, 60), qx=F(1, 30), qxe=F(1, 40)):
    return [[0, T, T*QL, 0, AB, 0, 0], [g*T, 0, T*qx, 0, 0, AB, g*T],
            [0, 0, 0, T, 0, 0, 0], [0]*7,
            [g*T*ce, T*K_, T*QE, 0, AB*KB, AB*ce, g*T*ce],
            [g*T*K_, T*cs, T*qxe, 0, AB*cs, AB*KB, g*T*K_],
            [0, 0, 0, T*K_, 0, 0, 0], [0, 0, 0, T*cs, 0, 0, 0],
            [0, LR, LR*QL, LR, CB, 0, 0], [g*LR, 0, LR*qx, 0, 0, CB, g*LR]]


def t1_rows(d=F(1, 2), dl=F(1, 3), db=F(1, 4)):
    rows = [r+[r[0]] for r in base_rows()]
    return rows+[[0, T*d, T*d*QL, 0, AB*db, 0], [0, 0, 0, T*dl, 0, 0],
                 [0, T*d*K_, T*d*QE, 0, AB*db*KB, 0],
                 [0, LR*d, LR*d*QL, LR*dl, CB*db, 0]]


def m1_rows(tc=F(47, 50), lc=F(1, 25), a=F(999, 1000), kc=F(4, 5)):
    """Rows derived from both orientations of the catcher's forward map."""
    names = ("r", "n_s", "n_l")

    def caught(o, name):
        return {"r": -o*a, "n_s": o, "n_l": 1}[name]

    def column(row):
        return [row["r"], 0, 0, 0, 0, row["n_s"], row["n_l"]]
    built = []
    for w in (F(1), kc):
        built.append(column({n: tc*w*(caught(1, n)-caught(-1, n))/2 for n in names}))
        built.append(column({n: tc*w*(caught(1, n)+caught(-1, n))/2 for n in names}))
    built.append(column({n: lc*caught(1, n) for n in names}))
    return [r+[0, 0] for r in base_rows()]+built


def columns_of(rows, *indices):
    return [[row[i] for i in indices] for row in rows]


def identical_columns(rows, a, b):
    return all(row[a] == row[b] for row in rows)


def m1_dependency_holds(rows, a=F(999, 1000)):
    return all(r[0]-r[1]+a*r[5] == 0 for r in rows)


# Finite response columns by direct stepping, in both orientations.

def _channel_pair(force_p, force_r, signs, weight, window):
    """Contrast of one differential pair, at unit gains, stepped directly."""
    p = step_force(force_p, PRIMARY[0])
    r = step_force(force_r, REFERENCE[0])
    return contrast(p, signs, window)-weight*contrast(r, signs, window)


def x1_column(pattern_p, pattern_r, window, signs, weight=1.0):
    return _channel_pair(pattern_p, pattern_r, signs, weight, window)


def finite_x1(leak=0.05, g=0.97):
    """Finite D rows of X1 for recoil, instant and exit-following inputs."""
    product = tuple(s*e for s, e in zip(SIGMA, EXIT))
    recoil = unit_pattern([s*g*e/2 for s, e in zip(SIGMA, EXIT)])
    instant = unit_pattern([s/2 for s in SIGMA])
    rows = {}
    for label, window in (("late", LATE), ("early", EARLY)):
        for name, signs in (("s", SIGMA), ("x", product)):
            rows[f"D^{name}_{label}"] = {
                column: _channel_pair(f, [leak*v for v in f], signs, 1.0, window)
                for column, f in (("r", recoil), ("s_i", instant), ("x", recoil))}
    return rows


def finite_m1(leak=0.05, a_c=0.999):
    """Catcher D and Sigma rows, stepping both orientations separately."""
    recoil = unit_pattern([s/2 for s in SIGMA])
    out = {}
    for label, window in (("late", LATE), ("early", EARLY)):
        by = {}
        for o in (1, -1):
            force = {"r": [-o*a_c*v for v in recoil], "n_s": [o*v for v in recoil],
                     "n_l": list(recoil)}
            by[o] = {name: _channel_pair(f, [leak*v for v in f], SIGMA, 1.0, window)
                     for name, f in force.items()}
        out[f"D^c_{label}"] = {n: (by[1][n]-by[-1][n])/2 for n in by[1]}
        out[f"Sigma^c_{label}"] = {n: (by[1][n]+by[-1][n])/2 for n in by[1]}
    return out


def t1_loads(z, span=0.2):
    return 0.5-z/span, 0.5+z/span


def t1_statistic(z, delta, span=0.2, zhat=0.0, force=1.0):
    """Q_T by the load split alone, unit transfer, no study code."""
    y_1, y_2 = (force*v for v in t1_loads(z, span))
    c_1, c_2 = (span/2+zhat)/delta, (span/2-zhat)/delta
    return c_2*y_2-c_1*y_1


def m1_set_check(a, K, h):
    """Distance of the true additive residual from the recoil prediction."""
    return abs(h+a)-K
