"""Deterministic verification of the formulas in the note on Fermi.

Requires Python 3 and SciPy. Run: python verify.py
No path simulation is used; these checks supplement the proofs.
"""
import json
from math import exp, pi, sqrt

from scipy.integrate import quad
from scipy.special import erf, erfc, ndtr


def gaussian(t, x):
    return exp(-(x * x) / (2 * t)) / sqrt(2 * pi * t)


def killed(t, x, a):
    return gaussian(t, x) - gaussian(t, 2 * a - x)


def hitting_density(s, a):
    if s <= 0:
        return 0.0
    return a * exp(-a * a / (2 * s)) / sqrt(2 * pi * s**3)


def verify():
    rows = []
    for a in (0.25, 1.0, 2.0):
        for t in (0.2, 1.0, 5.0):
            q = erf(a / sqrt(2 * t))
            h = erfc(a / sqrt(2 * t))
            mass, _ = quad(lambda x: killed(t, x, a), -float("inf"), a)
            absorbed, _ = quad(lambda s: hitting_density(s, a), 0, t)
            x = -0.3
            convolution, _ = quad(
                lambda s: hitting_density(s, a) * gaussian(t - s, x - a),
                0,
                t,
                epsabs=1e-10,
            )
            checks = (
                abs(q + h - 1),
                abs(mass - q),
                abs(absorbed - h),
                abs(gaussian(t, x) - convolution - killed(t, x, a)),
                abs(killed(t, a, a)),
            )
            assert max(checks) < 2e-8, (a, t, checks)
            rows.append({"a": a, "t": t, "Q": q, "H": h, "max_error": max(checks)})

    brownian_value = 2 * ndtr(0.25) - 1
    no_jumps_limit = exp(-1)
    assert no_jumps_limit > brownian_value
    # A finite-n lower bound follows from Kolmogorov and independence.
    n = 10000
    finite_lower_bound = (1 - 1 / n) ** n * (1 - 1 / (n * 0.25**2))
    assert finite_lower_bound > 0.36
    return {
        "checks_passed": True,
        "quadrature_rows": rows,
        "counterexample": {
            "liminf_lower_bound": no_jumps_limit,
            "brownian_prediction": brownian_value,
            "finite_n": n,
            "finite_n_lower_bound": finite_lower_bound,
        },
    }


if __name__ == "__main__":
    print(json.dumps(verify(), ensure_ascii=False, indent=2))
