# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Exact unit-noise Beneš transitions and a small DynGMA coefficient fit."""

from math import ceil, cosh, exp, log, pi, sqrt
from statistics import NormalDist

from fit import minimize
from models import pair_loss


def normal_density(end, mean, variance):
    return exp(-(end-mean)**2/(2*variance))/sqrt(2*pi*variance)


def exact_density(start, end, lag):
    return exp(-lag/2)*cosh(end)/cosh(start)*normal_density(end, start, lag)


def sample_pairs(starts, lags, count=32):
    """Deterministic midpoint quantiles of the exact endpoint law at each start and lag."""
    pairs = []
    for start in starts:
        right_weight = 1/(1+exp(-2*start))
        for lag in lags:
            sd = sqrt(lag)
            left = NormalDist(start-lag, sd)
            right = NormalDist(start+lag, sd)
            for j in range(count):
                target = (j+.5)/count
                low, high = start-lag-8*sd, start+lag+8*sd
                for _ in range(45):
                    middle = (low+high)/2
                    mass = (1-right_weight)*left.cdf(middle)+right_weight*right.cdf(middle)
                    if mass < target:
                        low = middle
                    else:
                        high = middle
                pairs.append([start, (low+high)/2, lag])
    return pairs


def mixture_steps(lag):
    return ceil(lag/.30)


def score(pairs, weights):
    return pair_loss(pairs, weights, substeps=2, step_count=mixture_steps)


def fit(pairs):
    return minimize(lambda weights: score(pairs, weights), [.4, log(.7)], steps=35)
