"""Finite polymer and growth observations. Python 3.9+, NumPy and SciPy."""
from collections import Counter
from fractions import Fraction
from itertools import product
from math import exp, pi, sin, sqrt

import numpy as np
from scipy.integrate import quad, trapezoid
from scipy.special import roots_hermitenorm


def equal_moments():
    # tau=pi^2, X=pi*U for U standard normal, so the sine perturbation is sin(2U).
    nodes, weights = roots_hermitenorm(768)
    for eta in (-.5, 0, .5):
        def observable(u):
            return exp(-exp(pi*u))*(1+eta*sin(2*u))
        density = lambda u: exp(-u*u/2)/sqrt(2*pi)
        value = quad(lambda u: density(u)*observable(u), -12,12,
                     epsabs=3e-14,epsrel=3e-14)[0]
        hermite = np.dot(weights, [observable(u) for u in nodes])/sqrt(2*pi)
        assert abs(value-hermite) < 5e-13
        print("Lognormal perturbation, eta and Laplace at 1:", eta, value)


def quenched_split():
    # Under the arcsine law P=sin(U)^2 for U uniform on [0,pi/2].
    overlap = quad(lambda u: 2/pi*(sin(u)**4+(1-sin(u)**2)**2), 0, pi/2)[0]
    assert abs(overlap-.75) < 1e-14
    rng = np.random.Generator(np.random.PCG64(20261122))
    g1,g2 = rng.gamma(.5,1.,size=(2,100_000))
    p = g2/(g1+g2)
    shared = ((rng.random(len(p)) < p) == (rng.random(len(p)) < p)).mean()
    print("Same route in a common environment: exact and simulated", overlap, shared)


def common_brownian_shift():
    rng = np.random.Generator(np.random.PCG64(20261122))
    x = np.linspace(0,1,513)
    b = np.column_stack((np.zeros(2), np.cumsum(rng.normal(size=(2,512))/sqrt(512),axis=1)))
    shift = x/3+x*(1-x)
    def mass_and_density(paths):
        weight = np.exp(paths[0]+paths[1,-1]-paths[1])
        mass = trapezoid(weight,x)
        return mass, weight/mass
    mass, density = mass_and_density(b)
    new_mass, new_density = mass_and_density(b+shift)
    np.testing.assert_allclose(new_density, density, atol=2e-14, rtol=0)
    np.testing.assert_allclose(np.log(new_mass/mass), 1/3, atol=1e-14)
    print("Common shift: log mass change, max path density change",
          np.log(new_mass/mass), np.max(abs(new_density-density)))


def early_heights(weights, side):
    grid = [[0]*(side+1) for _ in range(side+1)]
    for i in range(1,side+1):
        for j in range(1,side+1):
            grid[i][j] = weights[(i-1)*side+j-1]+max(grid[i-1][j],grid[i][j-1])
    return [grid[i][i] for i in range(1,side+1)]


def geometric_history():
    # With nonnegative weights and last height <=1, all weights in the box are 0 or 1.
    for history in (0,1):
        marginal = joint = Fraction(0)
        counts = Counter()
        for side in (2,3):
            for weights in product((0,1), repeat=side**2):
                h = early_heights(weights,side)
                if h[:2] != [history,1]:
                    continue
                probability = Fraction(1,2)**(len(weights)+sum(weights))
                if side == 2:
                    marginal += probability
                elif h[-1] == 1:
                    joint += probability
                    counts[sum(weights)] += 1
        expected = (Fraction(23,448), Fraction(1,32))[history]
        assert joint/marginal == expected
        print("H1, P(H1,H2=1), P(H1,H2=H3=1), conditional, counts",
              history,marginal,joint,joint/marginal,dict(sorted(counts.items())))


if __name__ == "__main__":
    equal_moments()
    quenched_split()
    common_brownian_shift()
    geometric_history()
