from pathlib import Path

source = r'''#!/usr/bin/env python3
"""
Exact rational transfer-function engine for the geometric RC ladder.

No floating-point arithmetic is used in the realization, recurrence,
polynomial construction, transfer-function comparison, or sample evaluation.

The ladder is the original series-R / shunt-C topology:
    Z_k(s) = R_k + 1 / (s*C_k + 1/Z_(k+1)(s))
with the final stage terminated by its shunt capacitor.

All inputs are exact rational numbers (integers, "p/q" strings, or [p,q]).
The returned transfer function is reduced over Q[s]. Exact equivalence is
therefore equality of reduced rational functions, not sampled resemblance.

Python 3.10+, standard library only.
"""

from __future__ import annotations

import argparse
import json
from fractions import Fraction


def Q(x) -> Fraction:
    if isinstance(x, Fraction):
        return x
    if isinstance(x, int):
        return Fraction(x, 1)
    if isinstance(x, str):
        return Fraction(x)
    if isinstance(x, (list, tuple)) and len(x) == 2:
        return Fraction(int(x[0]), int(x[1]))
    raise TypeError(f"unsupported exact rational: {x!r}")


def qstr(x: Fraction) -> str:
    return f"{x.numerator}/{x.denominator}"


# Polynomials are low-degree-first tuples of Fraction coefficients.
def trim(p):
    p = list(p)
    while len(p) > 1 and p[-1] == 0:
        p.pop()
    return tuple(p or [Fraction(0)])


def padd(a, b):
    n = max(len(a), len(b))
    return trim([
        (a[i] if i < len(a) else 0) +
        (b[i] if i < len(b) else 0)
        for i in range(n)
    ])


def pneg(a):
    return trim([-x for x in a])


def psub(a, b):
    return padd(a, pneg(b))


def pmul(a, b):
    out = [Fraction(0)] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i + j] += x * y
    return trim(out)


def pscale(a, k):
    return trim([x * k for x in a])


def pdivmod(a, b):
    a = list(trim(a))
    b = trim(b)
    if len(b) == 1 and b[0] == 0:
        raise ZeroDivisionError("polynomial division by zero")
    q = [Fraction(0)] * max(1, len(a) - len(b) + 1)
    while len(a) >= len(b) and not (len(a) == 1 and a[0] == 0):
        d = len(a) - len(b)
        c = a[-1] / b[-1]
        q[d] += c
        for j in range(len(b)):
            a[d + j] -= c * b[j]
        a = list(trim(a))
    return trim(q), trim(a)


def pmonic(a):
    a = trim(a)
    if a[-1] == 0:
        return a
    return pscale(a, 1 / a[-1])


def pgcd(a, b):
    a, b = trim(a), trim(b)
    while not (len(b) == 1 and b[0] == 0):
        _, r = pdivmod(a, b)
        a, b = b, r
    return pmonic(a)


def pexactdiv(a, b):
    q, r = pdivmod(a, b)
    if any(r):
        raise ArithmeticError("non-exact polynomial division")
    return q


def reduce_rational_function(num, den):
    num, den = trim(num), trim(den)
    if len(den) == 1 and den[0] == 0:
        raise ZeroDivisionError("zero transfer denominator")
    g = pgcd(num, den)
    num, den = pexactdiv(num, g), pexactdiv(den, g)
    # Unique scalar normalization: denominator leading coefficient = +1.
    scale = 1 / den[-1]
    num, den = pscale(num, scale), pscale(den, scale)
    return trim(num), trim(den)


def ladder_transfer(R, C):
    """
    Return reduced exact Z_in(s) = numerator(s) / denominator(s).
    R and C are lists of positive Fractions.
    """
    if not R or len(R) != len(C):
        raise ValueError("R and C must be nonempty and equal length")
    if any(x <= 0 for x in R + C):
        raise ValueError("all R and C values must be positive")

    # Last stage: Z_last = R_last + 1/(s*C_last)
    #            = (1 + R_last*C_last*s)/(C_last*s)
    num = (Fraction(1), R[-1] * C[-1])
    den = (Fraction(0), C[-1])

    # Z_k = R_k + N/(s*C_k*N + D)
    for k in range(len(R) - 2, -1, -1):
        sCN = (Fraction(0),) + pscale(num, C[k])
        inner_den = padd(sCN, den)
        new_num = padd(pscale(inner_den, R[k]), num)
        num, den = reduce_rational_function(new_num, inner_den)

    return reduce_rational_function(num, den)


def peval_complex(p, omega: Fraction):
    """
    Evaluate p(s) at s = j*omega using exact Gaussian rationals.

    Horner step:
        (a + j*b) * (j*omega) + c
        = (c - b*omega) + j*(a*omega)

    The previous implementation used
        (a - b*omega, b + a*omega)
    which multiplies by (1 + j*omega), introducing an erroneous +1
    into the real part at every Horner step.
    """
    omega = Q(omega)
    a, b = Fraction(0), Fraction(0)

    for coeff in reversed(p):
        a, b = coeff - b * omega, a * omega

    return a, b


def complex_div(x, y):
    ar, ai = x
    br, bi = y
    den = br * br + bi * bi
    if den == 0:
        raise ZeroDivisionError("complex rational division by zero")
    return (
        (ar * br + ai * bi) / den,
        (ai * br - ar * bi) / den,
    )


def zin_exact(num, den, omega):
    omega = Q(omega)
    n = peval_complex(num, omega)
    d = peval_complex(den, omega)
    return complex_div(n, d)


def magnitude_squared(z):
    return z[0] * z[0] + z[1] * z[1]


def polynomial_json(p):
    return [qstr(x) for x in p]


def transfer_signature(R, C):
    num, den = ladder_transfer(R, C)
    return {
        "numerator_low_to_high": polynomial_json(num),
        "denominator_low_to_high": polynomial_json(den),
    }


def exactly_equivalent(a, b):
    """Exact equality of rational transfer functions over Q(s)."""
    na, da = a
    nb, db = b
    return pmul(na, db) == pmul(nb, da)


def make_geometric_ladder(n, R0, C0, rho, gamma):
    R0, C0, rho, gamma = map(Q, (R0, C0, rho, gamma))
    if n < 1:
        raise ValueError("n must be >= 1")
    if min(R0, C0, rho, gamma) <= 0:
        raise ValueError("R0, C0, rho, and gamma must be positive")

    R, C = [], []
    for k in range(n):
        R.append(R0 * rho ** k)
        C.append(C0 * gamma ** k)
    return R, C


def run_demo():
    specs = [
        ("rho=gamma=2", "2", "2"),
        ("rho=gamma=3/2", "3/2", "3/2"),
        ("rho=2,gamma=3/2", "2", "3/2"),
    ]
    for label, rho, gamma in specs:
        R, C = make_geometric_ladder(8, 1, 1, rho, gamma)
        num, den = ladder_transfer(R, C)
        print(f"\n{label}")
        print("  numerator degree:", len(num) - 1)
        print("  denominator degree:", len(den) - 1)
        print("  numerator:", polynomial_json(num))
        print("  denominator:", polynomial_json(den))
        for w in ("1/16", "1/8", "1/4", "1/2", "1", "2", "4"):
            z = zin_exact(num, den, w)
            print(f"  omega={w:>4}  |Z|^2={qstr(magnitude_squared(z))}")

    # Changing R0 changes the raw transfer function; it is not raw equality.
    R1, C1 = make_geometric_ladder(4, 1, 1, 2, 2)
    R2, C2 = make_geometric_ladder(4, 2, 1, 2, 2)
    f1, f2 = ladder_transfer(R1, C1), ladder_transfer(R2, C2)
    print("\nDifferent R0 exact transfer equivalence:", exactly_equivalent(f1, f2))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--demo", action="store_true")
    ap.add_argument("--n", type=int, default=8)
    ap.add_argument("--rho", default="2")
    ap.add_argument("--gamma", default="2")
    ap.add_argument("--R0", default="1")
    ap.add_argument("--C0", default="1")
    ap.add_argument("--output", default="")
    args = ap.parse_args()

    if args.demo:
        run_demo()
        return

    R, C = make_geometric_ladder(
        args.n, args.R0, args.C0, args.rho, args.gamma
    )
    num, den = ladder_transfer(R, C)
    record = {
        "domain": "analog_rc",
        "law": "geometric-series-R / geometric-shunt-C",
        "parameters": {
            "n": args.n,
            "R0": str(Q(args.R0)),
            "C0": str(Q(args.C0)),
            "rho": str(Q(args.rho)),
            "gamma": str(Q(args.gamma)),
        },
        "transfer_function": transfer_signature(R, C),
        "exact_arithmetic": True,
    }
    out = json.dumps(record, indent=2)
    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(out + "\n")
    else:
        print(out)


if __name__ == "__main__":
    main()
'''

path = Path("/mnt/data/rc_ladder_exact.py")
path.write_text(source, encoding="utf-8")
print(f"Updated file created: {path}")
print(f"Size: {path.stat().st_size:,} bytes")
