# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Small full-batch BFGS optimizer for the CPU examples.

Pass a scalar loss of a flat parameter vector. Centered differences keep the reference
independent of an autodiff library. Use automatic differentiation for large networks.
"""

from math import fsum, isfinite, sqrt


def dot(a, b):
    return fsum(x * y for x, y in zip(a, b, strict=True))


def gradient(loss, x):
    result = []
    for j, value in enumerate(x):
        h = 1e-5 * max(1.0, abs(value))
        plus, minus = x.copy(), x.copy()
        plus[j] += h
        minus[j] -= h
        result.append((loss(plus) - loss(minus)) / (2 * h))
    return result


def minimize(loss, initial, steps=80, tol=1e-7):
    x = list(initial)
    n = len(x)
    inverse = [[float(i == j) for j in range(n)] for i in range(n)]
    value = loss(x)
    g = gradient(loss, x)
    for _ in range(steps):
        if sqrt(dot(g, g)) <= tol:
            break
        direction = [-dot(row, g) for row in inverse]
        slope = dot(direction, g)
        if slope >= 0:
            direction, slope = [-v for v in g], -dot(g, g)
        scale = 1.0
        while scale >= 2**-30:
            trial = [v + scale * d for v, d in zip(x, direction)]
            try:
                candidate = loss(trial)
            except (OverflowError, ValueError, ZeroDivisionError):
                candidate = float("inf")
            if isfinite(candidate) and candidate <= value + 1e-4 * scale * slope:
                break
            scale *= 0.5
        else:
            break
        new_g = gradient(loss, trial)
        s = [b - a for a, b in zip(x, trial)]
        y = [b - a for a, b in zip(g, new_g)]
        curvature = dot(s, y)
        if curvature > 1e-14 * sqrt(dot(s, s) * dot(y, y)):
            hy = [dot(row, y) for row in inverse]
            factor = (curvature + dot(y, hy)) / curvature**2
            inverse = [[inverse[i][j] + factor*s[i]*s[j] - (hy[i]*s[j] + s[i]*hy[j])/curvature
                        for j in range(n)] for i in range(n)]
        x, value, g = trial, candidate, new_g
    return x, value
