#!/usr/bin/env python3
"""ACT working note, 25 November 2026: a bath in continuous contact, with a causal form factor.
Note: https://anchoredcausality.org/a-bath-in-continuous-contact.html
Checks F1-F13.  numpy and scipy only.  Seed 20261125.  About fifteen seconds.

Model.  H(t) = sum_w w b^dag b + lambda(t) sigma_z B,  B = sum_w g_w (b_w + b_w^dag),  J(w) = sum g_w^2 delta(w - w').
Two alternatives sigma_z = +1, -1; lambda(t) is their separation (the coupling history).  In the interaction
picture the coupling operator at time u is the field quadrature X[p_u], p_u(w) = g_w exp(i w u), and the field
states of the two alternatives at time s are the coherent states +beta(s), -beta(s), beta(s) = -i P(s),
P(s) = int_0^s lambda(u) p_u du.   Phi(s) = 2 |P(s)|^2 = int int lambda lambda K0,  K0(tau) = 2 int J cos(w tau) dw.

Causal model:  J(w) = eta w^3 sinc^4(w a/2): dipole coupling smeared in time by a triangle of half-width a.
               K0 = -G'''' with G(tau) = 2 eta (C * ln|.|)(tau), C the cubic B-spline on [-2a, 2a].
               The commutator of two coupling operators, [X[p_u], X[p_u']] = 2i eta pi C'''(u' - u), vanishes
               for |u - u'| > 2a.
Exponential model:  J(w) = eta w^3 exp(-w),  G(tau) = eta ln(1 + tau^2)   (the usual exponential cutoff).

Kink formula (exact, both models): for a piecewise-linear lambda that starts and ends at zero, with slope jumps
a_m at times t_m,   Phi = - sum_mn a_m a_n G(t_m - t_n).

Exact formula (causal model, coupling non-zero at all later times):
   Phi_gen(s) = (2 pi eta / a^4) int_0^s [ D2_a I^(1/2) lambda (t) ]^2 dt,
I^(1/2) the half-integral, D2_a f(t) = f(t) - 2 f(t-a) + f(t-2a).   J(|w|) = |Gamma(w)|^2 with
Gamma = (sqrt(eta)/a^2) (1 - e^{iwa})^2 (-iw)^(-1/2), an outer function.
"""
import sys
import numpy as np
from math import comb
from scipy.integrate import quad
from scipy.linalg import expm

SEED = 20261125
rng = np.random.default_rng(SEED)
RESULTS = []


def record(label, ok, text):
    RESULTS.append(ok)
    print(f"  [{'PASS' if ok else 'FAIL'}] {label}: {text}")


# ------------------------------------------------------------------ the two models
def L4(x):
    """Fourth antiderivative of ln|x|: x^4 (ln|x| - 25/12) / 24."""
    x = np.asarray(x, float)
    ax = np.abs(x)
    with np.errstate(divide='ignore', invalid='ignore'):
        return np.where(ax > 0, x**4 * (np.log(ax) - 25.0 / 12.0) / 24.0, 0.0)


class Causal:
    def __init__(self, eta=1.0, a=1.0, switch=16.0):
        self.eta, self.a, self.sw, self.name = eta, a, switch * a, 'causal'
        xs, ws = np.polynomial.legendre.leggauss(12)
        u = np.concatenate([(k + 0.5 + 0.5 * xs) * a for k in (-2, -1, 0, 1)])
        w = np.concatenate([0.5 * a * ws] * 4)
        self.mom = [float(np.sum(w * self.C(u) * u**k)) for k in range(0, 14, 2)]

    def C(self, u):
        u = np.asarray(u, float)
        out = np.zeros_like(u)
        for j in range(5):
            out += (-1)**j * comb(4, j) * np.clip(u + (2 - j) * self.a, 0, None)**3
        return out / (6 * self.a**4)

    def J(self, w):
        return self.eta * w**3 * np.sinc(w * self.a / (2 * np.pi))**4

    def G(self, tau):
        tau = np.asarray(tau, float)
        near = np.zeros_like(tau)
        for j in range(5):
            near += (-1)**j * comb(4, j) * L4(tau + (2 - j) * self.a)
        near /= self.a**4
        at = np.maximum(np.abs(tau), 1.0)
        far = np.log(at)
        for k in range(1, 7):
            far -= self.mom[k] / (2 * k * at**(2 * k))
        return 2 * self.eta * np.where(np.abs(tau) <= self.sw, near, far)

    def W(self, tau):
        """Symplectic kernel for kinks: W'''' = S, S(tau) = int J sin(w tau) dw = eta pi C'''(tau).
        W = (eta pi / 2) (C * sign)(tau); it is constant, +-eta pi/2, outside [-2a, 2a]."""
        tau = np.asarray(tau, float)
        out = np.zeros_like(tau)
        for j in range(5):
            out += (-1)**j * comb(4, j) * np.clip(tau + (2 - j) * self.a, 0, None)**4
        return 0.5 * np.pi * self.eta * (2 * out / (24 * self.a**4) - 1.0)


class Expo:
    def __init__(self, eta=1.0):
        self.eta, self.name = eta, 'exponential'

    def J(self, w):
        return self.eta * w**3 * np.exp(-w)

    def G(self, tau):
        return self.eta * np.log1p(np.asarray(tau, float)**2)


def phi_kinks(model, t, a):
    t, a = np.asarray(t, float), np.asarray(a, float)
    return -float(a @ model.G(t[:, None] - t[None, :]) @ a)


# ------------------------------------------------------------------ piecewise-linear paths on a grid of nodes
def kink_matrix(t, dl, dr):
    """Nodes t_0..t_{n-1} carry values v; the path is linear between nodes and is zero at the ghost nodes
    t_0 - dl and t_{n-1} + dr and beyond.  Returns the node times (n+2) and D with kinks = D v."""
    tt = np.concatenate([[t[0] - dl], t, [t[-1] + dr]])
    n = len(t)
    D = np.zeros((n + 2, n))
    step = np.diff(tt)
    for i in range(n):           # value v_i sits at tt[i+1]
        D[i, i] += 1 / step[i]
        D[i + 1, i] += -1 / step[i] - 1 / step[i + 1]
        D[i + 2, i] += 1 / step[i + 1]
    return tt, D


def nodal_gram(model, t, dl, dr):
    tt, D = kink_matrix(t, dl, dr)
    return -D.T @ model.G(tt[:, None] - tt[None, :]) @ D


def future_nodes(s, h, dense, H, ratio=1.08):
    steps = [h] * int(round(dense / h))
    while sum(steps) < H:
        steps.append(steps[-1] * ratio)
    return s + np.cumsum(steps), steps[-1] * ratio


def phi_gen(model, lam, s, h, dense=16.0, H=2e5, rc=1e-13):
    """Least final Phi over all continuations after s (an upper bound for the exact infimum; it decreases to
    it as h -> 0, H -> infinity).  The path up to s is lam on the nodes 0, h, ..., s (lam must be linear between).
    Returns (Phi of the path cut at s over one step, the infimum, largest |continuation|)."""
    tp = np.round(np.arange(0, s + h / 2, h) / h) * h
    tf, dr = future_nodes(s, h, dense, H)
    t = np.concatenate([tp, tf])
    M = nodal_gram(model, t, h, dr)
    n = len(tp)
    v = lam(tp)
    Mpp, Mpf, Mff = M[:n, :n], M[:n, n:], M[n:, n:]
    b = Mpf.T @ v
    ev, V = np.linalg.eigh(0.5 * (Mff + Mff.T))
    keep = ev > rc * ev.max()
    x = -V[:, keep] @ ((V[:, keep].T @ b) / ev[keep])
    return float(v @ Mpp @ v), float(v @ Mpp @ v + b @ x), float(np.abs(x).max())


def phi_loc(model, kt, kb, s, h, dense=None, back=1e7, ratio=1.1):
    """Lower bound: the signal held by coupling operators older than 2a.  Records are X[h_i], h_i the coupling
    vector smeared with a hat centred at a node t_i <= s - 2a - h (nodes: step h for `dense` time units, then a
    geometric grid back to -back).  Each commutes with every coupling operator at times >= s.
    The value is 4 c^T M^-1 c, c_i = Im<h_i, P(s)>, M_ij = 2 Re<h_i, h_j>."""
    top = s - 2 * model.a - h
    dense = top + 8.0 if dense is None else dense          # step h back to t = -8, where the path has not begun
    steps = [h] * int(round(dense / h))
    while sum(steps) < back:
        steps.append(steps[-1] * ratio)
    t = (top - np.concatenate([[0.0], np.cumsum(steps)]))[::-1]
    tt, D = kink_matrix(t, steps[-1] * ratio, h)
    M = -D.T @ model.G(tt[:, None] - tt[None, :]) @ D
    c = D.T @ (model.W(tt[:, None] - kt[None, :]) @ kb)
    ev, V = np.linalg.eigh(0.5 * (M + M.T))
    keep = ev > 1e-12 * ev.max()
    return 4 * float((V[:, keep].T @ c)**2 @ (1 / ev[keep]))


def phi_exact(kt, kb, s, eta=1.0, a=1.0):
    """Causal model, later coupling never zero: (2 pi eta / a^4) int_0^s [D2_a I^(1/2) lambda]^2 dt, for a
    piecewise-linear lambda with slope jumps kb at times kt.  I^(1/2) of (t - tau)_+ is (4/(3 sqrt(pi))) (t - tau)_+^(3/2)."""
    c = 4 / (3 * np.sqrt(np.pi))
    f = lambda t: c * sum(b * np.clip(t - tau, 0, None)**1.5 for tau, b in zip(kt, kb))
    g = lambda t: f(t) - 2 * f(t - a) + f(t - 2 * a)
    brk = {0.0, float(s)} | {float(tau + k * a) for tau in kt for k in (0, 1, 2) if 0 < tau + k * a < s}
    top = max([b for b in brk if b < s] + [0.0])
    if s > top + 1.0:
        brk |= set(np.geomspace(top + 1.0, s, 200).tolist())
    brk = sorted(brk)
    xs, ws = np.polynomial.legendre.leggauss(40)
    x = 0.5 * (xs + 1)
    tot = 0.0
    for lo, hi in zip(brk[:-1], brk[1:]):
        t = lo + (hi - lo) * x**2                       # t^(3/2) behaviour at the left end of each piece
        tot += np.sum(0.5 * ws * 2 * x * (hi - lo) * g(t)**2)
    return 2 * np.pi * eta / a**4 * float(tot)


def ramp(T1):
    return lambda t: np.clip(np.asarray(t, float) / T1, 0, 1)


# ------------------------------------------------------------------ checks
def check_F1(m):
    worst = 0.0
    for tau in (0.0, 0.3, 1.0, 1.7, 2.5, 7.0, 15.9, 16.1, 40.0):
        f = lambda u: float(m.C(np.array([u]))[0]) * np.log(abs(tau - u))
        pts = sorted({p for p in (-2, -1, 0, 1, 2, tau) if -2 <= p <= 2})
        worst = max(worst, abs(2 * m.eta * quad(f, -2, 2, points=pts, limit=400)[0] - float(m.G(np.array([tau]))[0])))
    tail = abs(float(m.G(np.array([1e4]))[0]) - 2 * m.eta * np.log(1e4))
    ok = worst < 1e-9 and abs(m.mom[0] - 1) < 1e-12 and abs(m.mom[1] - 1 / 3) < 1e-12 and tail < 1e-7
    record('F1', ok, f'closed form of G against direct quadrature of 2 eta int C(u) ln|tau-u| du at nine points: '
                     f'worst {worst:.1e}; C has unit integral and second moment a^2/3; G -> 2 eta ln|tau| ({tail:.0e} at 1e4)')


def check_F2(m):
    t = np.sort(rng.uniform(0, 10, 7))
    a = rng.normal(size=7)
    A = np.vstack([np.ones(7), t])
    a = a - A.T @ np.linalg.lstsq(A.T, a, rcond=None)[0]          # ends at rest and at zero
    w = np.linspace(1e-6, 3000, 3_000_001)
    tot = 0.0
    for i in range(0, len(w) - 1, 200000):
        ww = w[i:i + 200001]
        L = -(np.exp(1j * ww[:, None] * t[None, :]) @ a) / ww**2
        tot += np.trapezoid(2 * m.J(ww) * np.abs(L)**2, ww)
    kf = phi_kinks(m, t, a)
    record('F2', abs(kf - tot) < 1e-7 * abs(kf), f'kink formula against 2 int J |L|^2 dw for a random seven-kink path: '
                                                 f'{kf:.10f} and {tot:.10f}')


def check_F3(m):
    h = 0.25
    kap, off = np.array([1., -2., 1.]) / h, np.array([-h, 0., h])
    sym = lambda d: float(kap @ m.W(d + off[:, None] - off[None, :]) @ kap)
    def num(d):
        f = lambda w: float(m.J(w)) * h**2 * np.sinc(w * h / (2 * np.pi))**4 * np.sin(w * d)
        return sum(quad(f, k * 20.0, (k + 1) * 20.0, limit=400)[0] for k in range(40))
    inside = [(d, sym(d), num(d)) for d in (0.4, 1.1, 1.9)]
    outside = [(d, sym(d), num(d)) for d in (2 * m.a + 2 * h + 0.37, 5.0)]
    ok = (all(abs(x - y) < 1e-6 for _, x, y in inside) and all(abs(x) < 1e-12 and abs(y) < 1e-6 for _, x, y in outside)
          and len({np.sign(x) for _, x, _ in inside}) == 2)
    record('F3', ok, 'the commutator of two coupling operators smeared with hats of half-width 0.25, closed form and '
                     'frequency quadrature, signed: ' + '; '.join(f'at {d:g}: {x:+.6f}, {y:+.6f}' for d, x, y in inside)
                     + '.  Beyond 2a + 2h: ' + '; '.join(f'at {d:g}: {x:.0e}, {y:.0e}' for d, x, y in outside))


def check_F4():
    # (a) one mode, one qubit: the Heisenberg operator of sigma_- is sigma_- times D(2 beta), beta = -i P
    N, w0, g = 60, 1.3, 0.21
    b = np.diag(np.sqrt(np.arange(1, N)), 1)
    lam_t = np.array([0.4, 1.0, -0.3, 0.7])
    dt = 0.5
    U = np.eye(2 * N, dtype=complex)
    sz = np.diag([1., -1.])
    P = 0.0
    nsub = 400
    for k, lv in enumerate(lam_t):
        for j in range(nsub):
            u = (k + (j + 0.5) / nsub) * dt
            Xp = g * (b * np.exp(-1j * w0 * u) + b.conj().T * np.exp(1j * w0 * u))
            U = expm(-1j * (dt / nsub) * lv * np.kron(sz, Xp)) @ U
            P += lv * g * np.exp(1j * w0 * u) * dt / nsub
    beta = -1j * P
    sm = np.array([[0., 0.], [1., 0.]])                       # |-><+|
    heis = U.conj().T @ np.kron(sm, np.eye(N)) @ U
    Dop = expm(2 * beta * b.conj().T - 2 * np.conj(beta) * b)
    want = np.kron(sm, Dop)
    idx = np.concatenate([np.arange(12), N + np.arange(12)])
    A, B = heis[np.ix_(idx, idx)], want[np.ix_(idx, idx)]
    ph = np.vdot(B, A) / abs(np.vdot(B, A))
    errA = np.linalg.norm(A - ph * B) / np.linalg.norm(B)
    # (b) the linear algebra behind Theorem 2 in a random finite model (an identity of projections, not a test
    #     of the operator supremum): 2 dist(P, S_f)^2 = signal of the best quadrature that commutes with S_f
    n, k = 7, 4
    pf = rng.normal(size=(k, n)) + 1j * rng.normal(size=(k, n))
    Pv = rng.normal(size=n) + 1j * rng.normal(size=n)
    R = lambda z: np.concatenate([z.real, z.imag], axis=-1)
    Sf = R(pf)
    coef = np.linalg.lstsq(Sf.T, R(Pv), rcond=None)[0]
    dist2 = float(np.sum((R(Pv) - Sf.T @ coef)**2))
    Q = np.linalg.svd(R(1j * pf))[2][k:]
    beta_v = R(-1j * Pv)
    proj2 = float(np.sum((Q @ beta_v)**2))
    comm = max(abs(np.imag(np.vdot(q[:n] + 1j * q[n:], p))) for q in Q for p in pf)
    # (c) the operator supremum in the one case where it is elementary: one mode, later displacements along one
    #     real direction (z = i t), so the future algebra is the functions of x.  sup |<-b| f(x) |b>| over |f| <= 1
    #     is int |psi_-b(x)| |psi_b(x)| dx; Theorem 2 says exp(-2 dist(b, iR)^2) = exp(-2 (Re b)^2).
    bq = 0.63 - 0.41j
    x = np.linspace(-14, 14, 20001)
    psi = lambda z: np.pi**-0.25 * np.exp(-(x - np.sqrt(2) * z.real)**2 / 2 + 1j * np.sqrt(2) * z.imag * x)
    sup_all = float(np.trapezoid(np.abs(psi(-bq)) * np.abs(psi(bq)), x))
    cs = np.linspace(-6, 6, 4801)
    weyl = max(abs(np.trapezoid(np.conj(psi(-bq)) * np.exp(1j * c * x) * psi(bq), x)) for c in cs)
    thm = np.exp(-2 * bq.real**2)
    ok = (errA < 1e-5 and abs(dist2 - proj2) < 1e-10 and comm < 1e-12 and abs(sup_all - thm) < 1e-9
          and abs(weyl - thm) < 1e-5)
    record('F4', ok, f'(a) one mode and one qubit, sixty levels: the Heisenberg operator of sigma_- is sigma_- times '
                     f'D(2 beta), beta = -iP, up to a phase ({errA:.1e}).  (b) the linear algebra of Theorem 2 in a '
                     f'random model of 7 modes: 2 dist^2 = {2 * dist2:.8f}, signal of the commuting quadratures '
                     f'{2 * proj2:.8f}.  (c) one mode, later displacements along one direction: the supremum over all '
                     f'contractions of the future algebra is {sup_all:.9f}, over its displacements {weyl:.9f}, and '
                     f'Theorem 2 gives {thm:.9f}')


def check_F5_F7(m, e):
    T1 = 4.0
    lam = ramp(T1)
    kt, kb = np.array([0., T1]), np.array([1 / T1, -1 / T1])
    radc, rade = phi_kinks(m, kt, kb), phi_kinks(e, kt, kb)
    s_list = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 12.0, 20.0, 40.0]
    hs = [0.5, 0.25, 0.125]
    tc = np.array([[phi_gen(m, lam, s, h)[1] for h in hs] for s in s_list])
    exact = np.array([phi_exact(kt, kb, s) for s in s_list])
    far = phi_exact(kt, kb, 1e6)
    gap = tc[:, 2] - exact
    ok5 = bool(np.all(gap > -1e-9) and np.all(gap < 2e-2) and np.all(np.diff(tc, axis=1) < 1e-9)
               and abs(exact[0] - 1 / 18) < 1e-9 and abs(far - radc) < 1e-7)
    print('      causal model, ramp 0 -> 1 over [0, 4] then held; eta = 1, a = 1.  Radiated part %.6f' % radc)
    print('        s     exact      grid h=0.5   h=0.25    h=0.125    fraction of radiated part')
    for s, row, x in zip(s_list, tc, exact):
        print(f'      {s:5.1f}  {x:.5f}    {row[0]:.5f}    {row[1]:.5f}   {row[2]:.5f}    {x / radc:.4f}')
    record('F5', ok5, f'causal model: the exact formula gives 1/18 at s = 1 ({exact[0]:.9f}) and the radiated part in '
                      f'the limit ({far:.8f} at s = 1e6 against {radc:.8f} from the kink formula).  The minimisation '
                      f'on a grid, which does not use the formula, lies above it at every s and h, comes down as h '
                      f'is refined, and at h = 0.125 is within {gap.max():.4f}')
    # F6: the floor from records
    lo = np.array([phi_loc(m, np.array([0., T1, 1e4, 1e4 + 1]), np.array([1 / T1, -1 / T1, -1., 1.]), s, 0.125)
                   for s in s_list])
    lo40 = phi_loc(m, np.array([0., T1, 1e4, 1e4 + 1]), np.array([1 / T1, -1 / T1, -1., 1.]), 4.0, 0.125, dense=40.0, back=40.0)
    ok6 = bool(np.all(lo <= exact + 1e-9) and np.all(lo[1:] > 0.95 * exact[1:]) and lo40 < 0.9 * lo[3])
    print('      floor from coupling operators older than 2a (h = 0.125, references back to -1e7): '
          + ', '.join(f'{s:g}: {v:.4f}' for s, v in zip(s_list, lo)))
    record('F6', ok6, f'coupling operators older than 2a commute with everything later and hold nearly all of it: '
                      f'{lo[3]:.4f} of {exact[3]:.4f} at s = 4, {lo[-1]:.5f} of {exact[-1]:.5f} at s = 40, never above '
                      f'the exact value.  The far past matters as a noise reference: with records back to -40 only, '
                      f'the floor at s = 4 is {lo40:.4f}')
    # F7: the exponential model
    s7 = (1.0, 2.0, 3.0, 4.0)
    te = np.array([[phi_gen(e, lam, s, h)[1] for h in hs] for s in s7])
    de1, de2 = te[:, 0] - te[:, 1], te[:, 1] - te[:, 2]
    dc1, dc2 = tc[:4, 0] - tc[:4, 1], tc[:4, 1] - tc[:4, 2]
    ok7 = bool(np.all(de2 > 0.9 * de1) and np.all(dc2 < 0.75 * dc1))
    print('      exponential model, same path.  Radiated part %.6f' % rade)
    print('        s     h=0.5     h=0.25    h=0.125')
    for s, row in zip(s7, te):
        print(f'      {s:5.1f}  {row[0]:.5f}   {row[1]:.5f}   {row[2]:.5f}')
    record('F7', ok7, f'exponential model: the grid values have not converged at h = 0.125.  The second halving of h '
                      f'lowers them by {np.min(de2 / de1):.2f} to {np.max(de2 / de1):.2f} times what the first did; in the '
                      f'causal model the factor is {np.min(dc2 / dc1):.2f} to {np.max(dc2 / dc1):.2f}.  By Theorem 4(a) the '
                      f'limit in the exponential model is zero; the grid cannot be refined further in double precision')
    return radc, exact


def check_F8(m):
    T1 = 4.0
    kt, kb = np.array([0., T1]), np.array([1 / T1, -1 / T1])
    rad = phi_kinks(m, kt, kb)
    gaps = np.array([4.0, 8.0, 16.0, 32.0, 64.0, 256.0, 1024.0])
    rec = np.array([rad - phi_exact(kt, kb, T1 + g) for g in gaps])
    ratio = rec * 4 * gaps**2
    c = 4 / (3 * np.sqrt(np.pi))
    f = lambda t: c * (kb[0] * t**1.5 + kb[1] * (t - T1)**1.5)
    haz = lambda t: 2 * np.pi * (f(t) - 2 * f(t - 1) + f(t - 2))**2
    hz = haz(4000.0) * 2 * 4000.0**3
    ok = bool(np.all(np.diff(ratio) > 0) and abs(ratio[-1] - 1) < 0.01 and abs(hz - 1) < 0.01)
    print('      causal model: what a later coupling can still take back, a time g after the ramp ends (exact):')
    print('        g      remainder      divided by eta/(4 g^2)')
    for g, x, r in zip(gaps, rec, ratio):
        print(f'      {g:5.0f}   {x:.4e}     {r:.4f}')
    record('F8', ok, f'the remainder a time g after the motion tends to eta/(4 g^2): the ratio is {ratio[4]:.3f} at '
                     f'g = 64 and {ratio[-1]:.4f} at g = 1024; the rate at t = 4000 is {hz:.4f} times eta/(2 t^3)')
    return gaps, rec


def check_F9(m, e):
    def szego_expo(Om):
        f = lambda w: (3 * np.log(w) - w) / (1 + w * w)
        return quad(f, 0, 1, limit=200)[0] + quad(f, 1, Om, limit=2000)[0]
    def szego_causal(Om):
        xs, ws = np.polynomial.legendre.leggauss(40)
        tot = 0.0
        for k in range(int(Om / (2 * np.pi))):
            w = 2 * np.pi * (k + 0.5 + 0.5 * xs)
            tot += np.sum(np.pi * ws * np.log(m.J(w)) / (1 + w * w))
        return tot
    e2, e4, e6 = szego_expo(1e2), szego_expo(1e4), szego_expo(1e6)
    c2, c4 = szego_causal(1e2 * 2 * np.pi), szego_causal(1e4 * 2 * np.pi)
    w = rng.uniform(0.01, 60, 9)
    Gam = (1 - np.exp(1j * w))**2 / np.sqrt(-1j * w)
    fac = float(np.max(np.abs(np.abs(Gam)**2 - m.J(w))))
    ok = (e4 - e2) < -4.0 and abs((e6 - e4) + np.log(100.0)) < 0.01 and abs(c4 - c2) < 0.1 and fac < 1e-12
    record('F9', ok, f'the integral of ln J / (1 + w^2): exponential model {e2:.2f} up to w = 1e2, {e4:.2f} up to 1e4, '
                     f'{e6:.2f} up to 1e6 (it falls by ln 10 per decade, without limit); causal model {c2:.3f} up to '
                     f'w = 2 pi 1e2 and {c4:.3f} up to 2 pi 1e4 (it converges).  |Gamma|^2 = J at nine random '
                     f'frequencies ({fac:.0e})')


def check_F10(m):
    # slow set-up, hold, slow removal.  The later coupling ends at 100: continuations live on (s, 100].
    Tr, Th = 40.0, 20.0
    Tend = 2 * Tr + Th
    lam = lambda t: np.clip(np.minimum(np.asarray(t, float) / Tr, (Tend - np.asarray(t, float)) / Tr), 0, 1)
    kt = np.array([0., Tr, Tr + Th, Tend])
    kb = np.array([1 / Tr, -1 / Tr, -1 / Tr, 1 / Tr])
    final = phi_kinks(m, kt, kb)
    h, eps = 0.5, 1e-3
    rows = []
    for s in (10.0, 40.0, 50.0, 60.0, 90.0):
        tp = np.round(np.arange(0, s + h / 2, h) / h) * h
        tf = np.round(np.arange(s + h, Tend - h / 2, h) / h) * h
        t = np.concatenate([tp, tf])
        M = nodal_gram(m, t, h, h)
        n = len(tp)
        v = lam(tp)
        b = M[:n, n:].T @ v
        ev, V = np.linalg.eigh(0.5 * (M[n:, n:] + M[n:, n:].T))
        x = -V @ ((V.T @ b) / ev)
        # bare loss at s: the path cut at s over a time eps
        past = kt < s
        slope = float(np.sum(kb[past]))
        val = float(lam(np.array([s]))[0])
        bt = np.concatenate([kt[past], [s, s + eps]])
        ba = np.concatenate([kb[past], [-slope - val / eps, val / eps]])
        rows.append((s, phi_kinks(m, bt, ba), float(v @ M[:n, :n] @ v + b @ x), phi_exact(kt, kb, s)))
    on = phi_exact(kt, kb, Tend)
    gen = np.array([r[2] for r in rows] + [final])
    ok = bool(np.all(np.diff(gen) > -1e-9) and all(r[2] >= r[3] - 1e-9 for r in rows) and on < final
              and abs(phi_exact(kt, kb, 1e7) - final) < 2e-6 and rows[2][1] > 100 * final)
    print('      slow set-up over 40, hold 20, slow removal over 40 (causal model); final loss %.5f' % final)
    print('        s      bare loss at s    later coupling ends at 100    later coupling never zero (exact)')
    for s, bb, gg, xx in rows:
        print(f'      {s:5.0f}   {bb:9.4f}          {gg:.5f}                       {xx:.5f}')
    print(f'        100   {final:9.4f}          {final:.5f}                       {on:.5f}')
    record('F10', ok, f'a superposition set up and removed slowly: the bare loss is {rows[2][1]:.2f} while held and '
                      f'{final:.4f} at the end.  With the later coupling ending at 100 the infimum rises to the final '
                      f'loss {final:.5f}; if the coupling stayed on at all later times, at any strength, it would be {on:.5f} at s = 100, '
                      f'reaching {final:.5f} only in the limit.  The support of the later coupling is the one thing '
                      f'about the future that enters')
    return rows, final, on


def check_F11(m):
    v = 0.25
    kt, kb = np.array([0.]), np.array([v])
    ss = np.array([64.0, 256.0, 1024.0, 4096.0])
    val = np.array([phi_exact(kt, kb, s) for s in ss])
    coef = np.diff(val) / np.log(4.0) / (m.eta * v * v)
    grid = phi_gen(m, lambda t: v * np.clip(np.asarray(t, float), 0, None), 32.0, 0.25, dense=12.0, H=4e6, rc=1e-12)[1]
    ex32 = phi_exact(kt, kb, 32.0)
    ok = bool(abs(coef[-1] - 2) < 0.01 and 0 <= grid - ex32 < 5e-3)
    record('F11', ok, 'kick and coast at velocity v = 0.25 (exact): ' + ', '.join(f'{x:.4f}' for x in val)
           + f' at s = 64, 256, 1024, 4096; the coefficient of ln s is {coef[0]:.3f}, {coef[1]:.3f}, {coef[2]:.3f} '
             f'times eta v^2.  The grid minimisation at s = 32 gives {grid:.4f} against {ex32:.4f} exact')


def check_F12(m):
    # the quadratures beyond reach: one pair that does not commute, one pair that does
    h = 0.25
    kap, off = np.array([1., -2., 1.]) / h, np.array([-h, 0., h])
    sym = lambda d: float(kap @ m.W(d + off[:, None] - off[None, :]) @ kap)
    near, farv = sym(0.25), sym(3.0)
    ok = abs(near) > 0.1 and abs(farv) < 1e-12
    record('F12', ok, f'the quadratures beyond reach are not a commuting family: two coupling operators older than 2a, '
                      f'0.25 apart, have Im<h_i, h_j> = {near:+.4f}; 3 apart, {farv:.0e}')


def check_F13(m):
    # the later coupling confined to (s, T): the least final loss depends on T, not only on whether a coupling lies ahead
    lam, s = ramp(4.0), 4.0
    ever = phi_exact([0.0, 4.0], [0.25, -0.25], s)

    def confined(T, h, rc=1e-13):
        tp = np.round(np.arange(0, s + h / 2, h) / h) * h
        tf = s + h * np.arange(1, int(round((T - s) / h)))
        M = nodal_gram(m, np.concatenate([tp, tf]), h, h)
        n = len(tp)
        v = lam(tp)
        b = M[:n, n:].T @ v
        ev, V = np.linalg.eigh(0.5 * (M[n:, n:] + M[n:, n:].T))
        keep = ev > rc * ev.max()
        return float(v @ M[:n, :n] @ v - b @ V[:, keep] @ ((V[:, keep].T @ b) / ev[keep]))

    Ts, hs = (8.0, 20.0, 68.0), (0.5, 0.25, 0.125)
    tab = np.array([[confined(T, h) for h in hs] for T in Ts])
    print('\n  F13  ramp 0 -> 1 over [0, 4]; s = 4; later coupling confined to (4, T); least final loss on a grid')
    print('         T      h = 0.5     h = 0.25    h = 0.125')
    for T, row in zip(Ts, tab):
        print(f'      {T:4.0f}   ' + '   '.join(f'{x:9.4f}' for x in row))
    print(f'      for ever (exact, Theorem 5)            {ever:9.4f}')
    ok = (np.all(np.diff(tab, axis=1) < 0) and np.all(np.diff(tab, axis=0) < 0) and np.all(tab > ever)
          and tab[0, -1] > 2.5 * ever and tab[-1, -1] < 1.2 * ever)
    record('F13', ok, f'if the coupling ends at T the least final loss is larger and depends on T: at most '
                      f'{tab[0, -1]:.2f}, {tab[1, -1]:.2f}, {tab[2, -1]:.2f} for T = 8, 20, 68 (grid values, upper '
                      f'bounds, falling with T and with h), against {ever:.4f} when the coupling never ends')


def main():
    print('A bath in continuous contact, with a causal form factor: checks\n')
    m, e = Causal(1.0, 1.0), Expo(1.0)
    check_F1(m)
    check_F2(m)
    check_F3(m)
    check_F4()
    check_F5_F7(m, e)
    check_F8(m)
    check_F9(m, e)
    check_F10(m)
    check_F11(m)
    check_F12(m)
    check_F13(m)
    print(f'\n{sum(RESULTS)} of {len(RESULTS)} checks pass.')
    return 0 if all(RESULTS) else 1


if __name__ == '__main__':
    sys.exit(main())
