"""A three-by-three exponential last-passage square with a slow diagonal.

Run with Python 3, NumPy and SciPy. The mean slope is an exact integral.
Seeded sampling checks it by optimizing over the six paths for each array.
"""
from itertools import combinations

import numpy as np
from scipy.integrate import quad


def middle_probability(weight, stretch):
    """Conditional probability that the maximizing path uses the center."""
    z = np.exp(-stretch * weight)
    return 1 - 9*z/8 + z**2/4


def paths():
    for right_steps in combinations(range(4), 2):
        x = y = 0
        coordinates = [(x, y)]
        for step in range(4):
            if step in right_steps:
                x += 1
            else:
                y += 1
            coordinates.append((x, y))
        yield coordinates


def check(stretch, arrays):
    values = []
    diagonal_weights = []
    central = []
    for route in paths():
        diagonal = sum(arrays[:, i, i] for i, j in route if i == j)
        off_diagonal = sum(arrays[:, i, j] for i, j in route if i != j)
        values.append(stretch * diagonal + off_diagonal)
        diagonal_weights.append(diagonal)
        central.append((1, 1) in route)
    best = np.argmax(values, axis=0)
    slopes = np.asarray(diagonal_weights)[best, np.arange(len(arrays))]
    uses_middle = np.asarray(central)[best]
    expected_visit = 1 - 9/(8*(1+stretch)) + 1/(4*(1+2*stretch))
    expected_slope = 3 - 9/(8*(1+stretch)**2) + 1/(4*(1+2*stretch)**2)
    probability = lambda g: middle_probability(g, stretch) * np.exp(-g)
    np.testing.assert_allclose(quad(probability, 0, np.inf)[0], expected_visit)
    np.testing.assert_allclose(2 + quad(lambda g: g*probability(g), 0, np.inf)[0],
                               expected_slope)
    for name, outcomes, target in (("visit", uses_middle, expected_visit),
                                   ("slope", slopes, expected_slope)):
        mean = outcomes.mean()
        error = outcomes.std(ddof=1) / np.sqrt(len(outcomes))
        print(f"a={stretch:g} {name}: exact {target:.9f}, sample {mean:.6f}, SE {error:.6f}")
        assert abs(mean - target) < 5 * error


if __name__ == "__main__":
    arrays = np.random.default_rng(20261122).exponential(size=(200_000, 3, 3))
    for stretch in (1., 1.25, 2.):
        check(stretch, arrays)
