"""Exact finite checks of the sparse negative-jump construction."""

from collections import defaultdict
from fractions import Fraction


def mass(atoms):
    return sum(atoms.values())


def return_weights(atoms, horizon):
    """Use unnormalized weights and keep sums that can still reach zero."""
    states = {0: Fraction(1)}
    for step in range(1, horizon + 1):
        next_states = defaultdict(Fraction)
        for value, weight in states.items():
            for jump, jump_weight in atoms.items():
                target = value + jump
                if target >= step - horizon:
                    next_states[target] += weight * jump_weight
        states = next_states
    return states.get(0, Fraction(0))


def normalized_return(atoms, length):
    return return_weights(atoms, length) / mass(atoms) ** length


def verify():
    atoms = {0: Fraction(1), 1: Fraction(1)}
    choices = ((1, 4), (5, 400))
    stages = []
    for stage, (size, horizon) in enumerate(choices, start=1):
        atoms[-size] = Fraction(1, 2 ** stage * size)
        stages.append(atoms.copy())
        assert sum(jump * w for jump, w in atoms.items()) == Fraction(1, 2 ** stage)
        shift = horizon // 2
        ratio = (normalized_return(atoms, horizon - shift)
                 / normalized_return(atoms, horizon))
        assert ratio > stage
    atoms[-401] = Fraction(1, 8 * 401)
    for earlier, (_, horizon) in zip(stages, choices):
        for length in (horizon // 2, horizon):
            assert return_weights(atoms, length) == return_weights(earlier, length)
            scale = mass(earlier) / mass(atoms)
            assert normalized_return(atoms, length) == (
                scale ** length * normalized_return(earlier, length)
            )
    print("Both half-time ratios exceed their thresholds; later atoms preserve the earlier weights.")


if __name__ == "__main__":
    verify()

