
from fractions import Fraction
from rc_ladder_exact import (
    Q, make_geometric_ladder, ladder_transfer,
    zin_exact, complex_div
)

def add(a, b):
    return a[0] + b[0], a[1] + b[1]

def direct_recurrence(R, C, omega):
    w = Q(omega)

    # Last stage
    y = (Fraction(0), w * C[-1])
    z = add(
        (R[-1], Fraction(0)),
        complex_div((Fraction(1), Fraction(0)), y)
    )

    # Original stage-by-stage recurrence
    for k in range(len(R)-2, -1, -1):
        y = add(
            (Fraction(0), w * C[k]),
            complex_div((Fraction(1), Fraction(0)), z)
        )
        z = add(
            (R[k], Fraction(0)),
            complex_div((Fraction(1), Fraction(0)), y)
        )

    return z

def verify(n, rho, gamma):
    R, C = make_geometric_ladder(n, 1, 1, rho, gamma)
    num, den = ladder_transfer(R, C)

    frequencies = [
        "1/256", "1/64", "1/16", "1/4",
        "1", "4", "16", "64", "256"
    ]

    for w in frequencies:
        polynomial = zin_exact(num, den, w)
        recursive = direct_recurrence(R, C, w)

        if polynomial != recursive:
            print("FAIL", n, rho, gamma, w)
            print("POLY:", polynomial)
            print("RECUR:", recursive)
            return False

    print("PASS", n, rho, gamma, len(frequencies), "exact comparisons")
    return True

for rho, gamma in [
    ("2", "2"),
    ("3/2", "3/2"),
    ("2", "3/2"),
    ("3/2", "2"),
    ("5/3", "7/4"),
]:
    for n in [1, 2, 4, 8, 16]:
        assert verify(n, rho, gamma)

print("ALL EXACT VERIFICATIONS PASSED")
