"""Closed-form tail coefficients for one first-order cascade channel.

Independent analytic path for the mechanistic robustness study. It shares no
code with the study engine or the instruments: it uses the solved recurrences

    th[n] = p**n*th0 + k*h*(1-p**n)
    me[n] = q**n*me0 + (f + k*h)*(1-q**n) + b*(th0-k*h)*p*S(n)

with p = exp(-dt/thermal), q = exp(-dt/response), b = 1-q, and
S(n) = (p**n-q**n)/(p-q). Virtual lab only.
"""

import math


def _s(p, q, n):
    if p == q:
        return n*p**(n-1)
    return (p**n-q**n)/(p-q)


def _trial(th0, me0, f, h, k, p, q, samples, tail):
    b = 1-q
    target = k*h

    def mechanical(n):
        return (q**n*me0 + (f+target)*(1-q**n)
                + b*(th0-target)*p*_s(p, q, n))

    mean = math.fsum(mechanical(n)
                     for n in range(samples-tail+1, samples+1))/tail
    return p**samples*th0+target*(1-p**samples), mechanical(samples), mean


def coefficients(response, thermal, k, step, samples, tail, trials):
    """Return force and heat matrices g[i][j], h[i][j] for tail of trial i."""
    p, q = math.exp(-step/thermal), math.exp(-step/response)
    force = [[0.0]*trials for _ in range(trials)]
    heat = [[0.0]*trials for _ in range(trials)]
    for matrix, unit in ((force, (1.0, 0.0)), (heat, (0.0, 1.0))):
        for j in range(trials):
            th, me = 0.0, 0.0
            for i in range(j, trials):
                f, h = unit if i == j else (0.0, 0.0)
                th, me, mean = _trial(th, me, f, h, k, p, q, samples, tail)
                matrix[i][j] = mean
    return force, heat
