"""Frequency responses for the comparison plot of this page.

    python peaking.py      writes peaking.dat, which comparison.tex reads

All four stages have the same R_D and the same total capacitance C = C1 + C2,
so they share the same DC gain g_m R_D and the same no-peaking pole 1/(R_D C).
Everything is normalized: R_D = 1, C = 1, frequency in units of 1/(R_D C),
inductors in units of R_D^2 C, gain in units of g_m R_D.

General result (shunt-series; Lp = 0 gives series, Ls = 0 gives shunt):

    |Av(s)|      1 + s Lp/R_D
    ------- = ----------------------------------------------------------------------
    g_m R_D   1 + s R_D(C1+C2) + s^2 (Lp C1 + Lp C2 + Ls C2) + s^3 R_D C1 C2 Ls + s^4 C1 C2 Lp Ls

Each peaking network is sized for a maximally flat magnitude: the low-order
coefficients of |D(jw)|^2 - |N(jw)|^2 (w^2, then w^4, then w^6) are set to zero,
as many as the free parameters allow.
    shunt:         Lp = (sqrt(2) - 1) R_D^2 C                       (1 parameter, w^2)
    series:        C1 = C/4,       Ls = (2/3) R_D^2 C                (2 parameters, w^2 and w^4)
    shunt-series:  C1 = (48/119) C, Lp = R_D^2 C / 7, Ls = (289/497) R_D^2 C   (3 parameters, w^2 to w^6)
"""
import numpy as np

designs = {                      # name: (C1, C2, Lp, Ls), normalized
    "none":         (1.0, 0.0, 0.0, 0.0),
    "shunt":        (1.0, 0.0, np.sqrt(2) - 1, 0.0),
    "series":       (1 / 4, 3 / 4, 0.0, 2 / 3),
    "shunt-series": (48 / 119, 71 / 119, 1 / 7, 289 / 497),
}


def gain(w, C1, C2, Lp, Ls):
    s = 1j * w
    num = 1 + s * Lp
    den = (1 + s * (C1 + C2) + s**2 * (Lp * C1 + Lp * C2 + Ls * C2)
           + s**3 * C1 * C2 * Ls + s**4 * C1 * C2 * Lp * Ls)
    return np.abs(num / den)


w = np.logspace(-1, 1, 401)                          # 0.1 to 10 times 1/(R_D C)
cols = [w] + [20 * np.log10(gain(w, *p)) for p in designs.values()]
np.savetxt("peaking.dat", np.column_stack(cols), fmt="%.6g",
           header="w " + " ".join(designs), comments="")

wf = np.logspace(-3, 1, 400001)
for name, p in designs.items():
    g = gain(wf, *p)
    w3 = wf[np.argmax(g < 1 / np.sqrt(2))]
    print(f"{name:13s} -3 dB at {w3:.3f}/(R_D C)   peak {20 * np.log10(g.max()):+.3f} dB")
