main
John Lauer ECAS vs MLCC: a study of moving the buck to polymer capacitors, with its section card 531f515
#!/usr/bin/env python3
"""ECAS exploration: every capacitor variant through the same ngspice tests.

For each variant (which caps sit on VIN and on VOUT):
  loop      averaged PCM loop gain (the board's own sim/loop.py model, calibrated to TPS54202 eq 14),
            Cff swept, crossover + phase margin at 9/12/16 V, 0.5 and 1 A
  switching cycle-by-cycle transient (the board's own sim/transient.py modulator) at 12 V:
            output ripple, 1 A -> 0.5 A -> 1 A step, VIN-pin ripple, RMS current in every input cap
  hotplug   the board plugged into a live 16 V rail through 0.5 and 1 uH of wiring: peak VIN
  zin       input-filter output impedance peak vs the converter's |Zin| (Middlebrook)

Capacitors are R-L-C branches with C at the real DC bias (tools/parts.py).
Run: python3 variants.py [variant ...]  -> ../results/<variant>.json
"""
import json, math, os, subprocess, sys
import numpy as np
from parts import lib

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "..", "results")
WORK = os.path.join(HERE, "..", "work")
os.makedirs(OUT, exist_ok=True); os.makedirs(WORK, exist_ok=True)
LIB = lib()
calcs = json.load(open(os.path.join(HERE, "..", "..", "design", "calcs.json")))
VREF, VOUT, FSW, L, DCR = 0.596, 5.0, 500e3, 15e-6, 0.118
RTOP, RBOT = calcs["feedback"]["Rtop"], calcs["feedback"]["Rbot"]
# the board's calibrated internal-compensation equivalent (sim/loop.json)
M = json.load(open(os.path.join(HERE, "..", "..", "sim", "loop.json")))["model"]
RI, GM, RC, CC, CP = M["Ri"], M["gm"], M["Rc"], M["Cc"], M["Cp"]
RO = 1000 / GM

# a bank entry is a part key, or a tuple (part key, damping resistor key) for an R in series with a bulk cap
VARIANTS = {
    "A_as_built": {
        "label": "As built: 47 uF alu can + 2 x 10 uF 1206 in, 3 x 22 uF 0805 out",
        "vin": ["alu47", "x7r10_1206", "x7r10_1206", "c100n"],
        "vout": ["x5r22_0805"] * 3, "cff": 68},
    "B_ecas_swap": {
        "label": "ECAS swap: 33 uF ECAS + 1 x 10 uF 1206 in, 150 uF ECAS out",
        "vin": ["ecas33_25", "x7r10_1206", "c100n"],
        "vout": ["ecas150_10"]},
    "B2_ecas_plus_ceramic": {
        "label": "ECAS + one ceramic each side: 33 uF ECAS + 10 uF 1206 in, 150 uF ECAS + 22 uF 0805 out",
        "vin": ["ecas33_25", "x7r10_1206", "c100n"],
        "vout": ["ecas150_10", "x5r22_0805"]},
    "C_ecas_input_damped": {
        "label": "ECAS where it earns it: 33 uF ECAS + 0.22 ohm in place of the can, 2 x 10 uF 1206 in, 3 x 22 uF 0805 out",
        "vin": [("ecas33_25", "r_damp"), "x7r10_1206", "x7r10_1206", "c100n"],
        "vout": ["x5r22_0805"] * 3, "cff": 68},
    "C2_ecas_input_bare": {
        "label": "ECAS for the can, no damping resistor: 33 uF ECAS + 2 x 10 uF 1206 in, 3 x 22 uF 0805 out",
        "vin": ["ecas33_25", "x7r10_1206", "x7r10_1206", "c100n"],
        "vout": ["x5r22_0805"] * 3, "cff": 68},
    "F_smallest": {
        "label": "Smallest set: 33 uF ECAS + 0.22 ohm for the can, 2 x 22 uF/25 V 0805 in, 2 x 47 uF 0805 out",
        "vin": [("ecas33_25", "r_damp"), "x5r22_25_0805", "x5r22_25_0805", "c100n"],
        "vout": ["x5r47_0805"] * 2, "cff": 68},
    "A2_as_built_cff47": {
        "label": "As built with Cff 47 pF (the fix the measured derating calls for)",
        "vin": ["alu47", "x7r10_1206", "x7r10_1206", "c100n"],
        "vout": ["x5r22_0805"] * 3, "cff": 47},
    "F2_recommended": {
        "label": "Recommended: 33 uF ECAS + 0.22 ohm for the can, 2 x 22 uF/25 V 0805 in, 2 x 47 uF 0805 out, Cff 47 pF",
        "vin": [("ecas33_25", "r_damp"), "x5r22_25_0805", "x5r22_25_0805", "c100n"],
        "vout": ["x5r47_0805"] * 2, "cff": 47},
    "D_dense_mlcc": {
        "label": "Denser MLCC only: can + 2 x 22 uF/25 V 0805 in, 2 x 47 uF 0805 out",
        "vin": ["alu47", "x5r22_25_0805", "x5r22_25_0805", "c100n"],
        "vout": ["x5r47_0805"] * 2},
    "E_poscap_out": {
        "label": "Polymer tantalum out: as-built input, 100 uF POSCAP + 22 uF 0805 out",
        "vin": ["alu47", "x7r10_1206", "x7r10_1206", "c100n"],
        "vout": ["poscap100", "x5r22_0805"]},
}
CFFS = [0, 22, 33, 47, 68, 100, 150, 220]


def models(bank, bias):
    """[(C, ESR, ESL, extraR, key)] for a bank at a DC bias."""
    out = []
    for e in bank:
        key, rkey = (e if isinstance(e, tuple) else (e, None))
        m = LIB[key]["model"](bias)
        extra = LIB[rkey]["model"](bias)["R"] if rkey else 0.0
        out.append((m["C"], m["ESR"], m["ESL"], extra, key))
    return out


def branches(node, bank, prefix, sense=False):
    s = []
    for i, (c, esr, esl, extra, key) in enumerate(bank):
        n1 = f"{prefix}{i}a"
        if sense:
            s.append(f"V{prefix}{i} {node} {prefix}{i}s 0")
            node_i = f"{prefix}{i}s"
        else:
            node_i = node
        s.append(f"R{prefix}{i} {node_i} {n1} {esr + extra}")
        s.append(f"L{prefix}{i} {n1} {prefix}{i}b {esl}")
        s.append(f"Rp{prefix}{i} {n1} {prefix}{i}b 2")   # eddy/proximity loss across the ESL: damps the nH rings like real parts
        s.append(f"C{prefix}{i} {prefix}{i}b 0 {c}")
    return "\n".join(s)


def total_c(bank):
    return sum(b[0] for b in bank)


def run(cir, name):
    p = os.path.join(WORK, name + ".cir")
    open(p, "w").write(cir)
    r = subprocess.run(["ngspice", "-b", p], capture_output=True, text=True)
    if r.returncode:
        raise RuntimeError(r.stdout[-2000:] + r.stderr[-2000:])


# ---------------------------------------------------------------- loop gain
def loop(v, vin, rload, cff, tag):
    bank = models(v["vout"], VOUT)
    D = VOUT / vin
    Sn = (vin - VOUT) / L * RI
    Se = 0.5 * VOUT / L * RI
    mc = 1 + Se / Sn
    Qp = 1 / (math.pi * (mc * (1 - D) - 0.5))
    wn = math.pi * FSW
    Cs = 1e-9; Ls = 1 / (wn ** 2 * Cs); Rs = math.sqrt(Ls / Cs) / Qp
    f_ac = os.path.join(WORK, f"_ac_{tag}.txt")
    cir = f"""* loop {tag}
Vx vout vfbtop DC 0 AC 1
Rtop vfbtop fb {RTOP}
{f'Cff vfbtop fb {cff}p' if cff else ''}
Rbot fb 0 {RBOT}
Gea vc 0 fb 0 {GM}
Rea vc 0 {RO}
Rc vc cz {RC}
Cc cz 0 {CC}
Cp vc 0 {CP}
Ebuf vcb 0 vc 0 1
Rs vcb s1 {Rs}
Ls s1 s2 {Ls}
Cs s2 0 {Cs}
Gpwr 0 vout s2 0 {1/RI}
{branches('vout', bank, 'co')}
Rload vout 0 {rload}
.ac dec 100 100 1meg
.control
run
wrdata {f_ac} vdb(vout) vdb(vfbtop) vp(vout) vp(vfbtop)
.endc
.end
"""
    run(cir, f"loop_{tag}")
    d = np.loadtxt(f_ac)
    f = d[:, 0]
    H = 10 ** ((d[:, 1] - d[:, 3]) / 20) * np.exp(1j * (d[:, 5] - d[:, 7]))
    T = -H
    mag = 20 * np.log10(np.abs(T)); ph = np.degrees(np.angle(T))
    i = np.where(np.diff(np.sign(mag)) < 0)[0]
    if not len(i):
        return None, None, (f, mag, ph)
    k = i[0]
    fc = f[k] + (f[k + 1] - f[k]) * (0 - mag[k]) / (mag[k + 1] - mag[k])
    phc = ph[k]
    pm = 180 + phc if phc < 0 else 180 - phc
    # gain margin: |T| where phase crosses -180 above fc
    return fc, pm, (f, mag, ph)


def loop_sweep(name, v):
    res = []
    for cff in CFFS:
        for vin in (9, 12, 16):
            for rload in (5.0, 10.0):
                fc, pm, _ = loop(v, vin, rload, cff, f"{name}_{cff}_{vin}_{int(rload)}")
                res.append({"cff_pF": cff, "vin": vin, "iout": VOUT / rload,
                            "fc_kHz": round(fc / 1e3, 2) if fc else None, "pm_deg": round(pm, 1) if pm else None})
    # pick Cff: highest worst-case PM, then highest worst-case fc; keep the variant's fixed Cff if given
    best = None
    for cff in CFFS:
        rows = [r for r in res if r["cff_pF"] == cff and r["pm_deg"]]
        if len(rows) < 6:
            continue
        score = (min(r["pm_deg"] for r in rows), min(r["fc_kHz"] for r in rows))
        if best is None or score[0] > best[1][0] + 2 or (abs(score[0] - best[1][0]) <= 2 and score[1] > best[1][1]):
            best = (cff, score)
    chosen = v.get("cff", best[0])
    rows = [r for r in res if r["cff_pF"] == chosen]
    return {"sweep": res, "cff_best_pF": best[0], "cff_used_pF": chosen,
            "pm_min_deg": min(r["pm_deg"] for r in rows), "fc_min_kHz": min(r["fc_kHz"] for r in rows),
            "fc_max_kHz": max(r["fc_kHz"] for r in rows),
            "fc_12V_1A_kHz": next(r["fc_kHz"] for r in rows if r["vin"] == 12 and r["iout"] == 1.0),
            "pm_12V_1A_deg": next(r["pm_deg"] for r in rows if r["vin"] == 12 and r["iout"] == 1.0)}


# ---------------------------------------------------------------- switching transient
def switching(name, v, cff, vin=12.0, tstop=5e-3):
    bin_ = models(v["vin"], vin); bout = models(v["vout"], VOUT)
    SE = 0.5 * VOUT / L * RI
    f_tr = os.path.join(WORK, f"_tr_{name}.txt")
    nin = len(bin_)
    sense_vecs = " ".join(f"i(Vci{i})" for i in range(nin))
    cir = f"""* switching {name}
.option method=gear reltol=1e-3
Vsrc src 0 {vin}
Rcable src vinc 0.05
Lcable vinc vin 0.5u
{branches('vin', bin_, 'ci', sense=True)}
Shs vin sw hg 0 swm_hs
Sls sw 0 lg 0 swm_ls
Dls 0 sw dbody
Csw sw 0 150p
Lo sw lx {L}
Vsense lx lxs 0
Rdcr lxs vout {DCR}
{branches('vout', bout, 'co')}
Rload vout 0 10
* 0.5 A load step at 1 A/us (an electronic load's typical slew), 1 A -> 0.5 A at 3 ms, back at 4 ms
Istep vout 0 PWL(0 0.5 3m 0.5 3.0005m 0 4m 0 4.0005m 0.5)
Rtop vout fb {RTOP}
{f'Cff vout fb {cff}p' if cff else ''}
Rbot fb 0 {RBOT}
Bref vref 0 V = min(0.596, 0.596*time/1.5m)
Gea vc 0 fb vref {GM}
Rea vc 0 {RO}
Rc vc cz {RC}
Cc cz 0 {CC}
Cp vc 0 {CP}
Vclk clk 0 PULSE(0 1 0 1n 1n 20n {1/FSW})
Bramp ramp 0 V = {SE} * (time - floor(time*{FSW})/{FSW})
Brst rst 0 V = ((i(Vsense)*{RI} + v(ramp) >= v(vc)) || (i(Vsense) >= 2.5)) ? 1 : 0
.model swm_hs sw vt=0.5 vh=0 ron=0.148 roff=1meg
.model swm_ls sw vt=0.5 vh=0 ron=0.078 roff=1meg
.model swm_step sw vt=0.5 vh=0 ron=0.001 roff=1g
.model dbody d is=1e-9 n=1.2 rs=0.05
aset [clk rst] [dset drst] adc
.model adc adc_bridge in_low=0.4 in_high=0.6
apu den pullup
.model pullup d_pullup
alatch dset drst den NULL NULL dq dqb latch
.model latch d_srlatch sr_value=0 rise_delay=5n fall_delay=5n
adac [dq dqb] [q qb] dac
.model dac dac_bridge out_low=0 out_high=1 t_rise=2n t_fall=2n
Bhg hg 0 V = v(q) > 0.5 ? 1 : 0
Rqd qb qbd 1k
Cqd qbd 0 10p
Blg lg 0 V = (v(qbd) > 0.9) && (v(q) < 0.5) ? 1 : 0
.save v(vout) i(Vsense) v(vin) {sense_vecs}
.tran 10n {tstop} 0 10n uic
.control
set wr_singlescale
run
wrdata {f_tr} v(vout) i(Vsense) v(vin) {sense_vecs}
.endc
.end
"""
    run(cir, f"sw_{name}")
    d = np.loadtxt(f_tr)
    t, vo, il, vi = d[:, 0], d[:, 1], d[:, 2], d[:, 3]
    icap = d[:, 4:4 + nin]
    w = lambda a, b: (t >= a) & (t <= b)

    def bw(x, fc=20e6):
        # a scope's 20 MHz bandwidth limit: one-pole low-pass on the (non-uniform) time grid
        y = np.empty_like(x); y[0] = x[0]; tau = 1 / (2 * math.pi * fc)
        a = np.exp(-np.diff(t) / tau)
        for k in range(1, len(x)):
            y[k] = a[k - 1] * y[k - 1] + (1 - a[k - 1]) * x[k]
        return y
    st = w(2.6e-3, 3.0e-3)
    vss = float(vo[st].mean())
    vob = bw(vo)                                   # the load-step numbers read through the same 20 MHz limit
    res = {
        "vin": vin,
        "vout_mean_V": round(vss, 4),
        "vout_ripple_pp_mV": round(float(np.ptp(vo[w(2.9e-3, 3.0e-3)])) * 1e3, 2),
        "vin_pin_ripple_pp_mV_20MHz": round(float(np.ptp(bw(vi)[w(2.9e-3, 3.0e-3)])) * 1e3, 1),
        "vout_ripple_pp_mV_20MHz": round(float(np.ptp(bw(vo)[w(2.9e-3, 3.0e-3)])) * 1e3, 2),
        "step_down_overshoot_mV": round(float((vob[w(3e-3, 3.5e-3)].max() - vss) * 1e3), 1),
        "step_up_undershoot_mV": round(float((vob[w(3.6e-3, 4.0e-3)].mean() - vob[w(4e-3, 4.5e-3)].min()) * 1e3), 1),
        "startup_overshoot_mV": round(float((vo[t < 2.6e-3].max() - vss) * 1e3), 1),
    }
    sb = w(4e-3, tstop); err = np.abs(vo[sb] - vss); ob = t[sb][err > 0.01 * vss]
    res["step_up_settle_1pct_us"] = round(float((ob.max() - 4e-3) * 1e6), 1) if len(ob) else 0.0
    # rms current per input cap over 10 steady cycles (uniform 5 ns grid is not guaranteed: weight by dt)
    m = w(2.98e-3, 3.0e-3)
    dt = np.gradient(t[m])
    rms = [float(np.sqrt(np.sum(icap[m, i] ** 2 * dt) / np.sum(dt))) for i in range(nin)]
    res["input_cap_rms_A"] = {f"{i}:{b[4]}": round(r, 3) for i, (b, r) in enumerate(zip(bin_, rms))}
    # waveform excerpt for the page plots
    keep = w(2.9e-3, 4.6e-3)
    step = max(1, int(keep.sum() / 4000))
    np.save(os.path.join(WORK, f"wave_{name}.npy"), np.vstack([t[keep][::step], vo[keep][::step], vi[keep][::step]]))
    return res


# ---------------------------------------------------------------- hot plug
def hotplug(name, v, vin=16.0, lcable=1e-6):
    bin_ = models(v["vin"], vin)
    f = os.path.join(WORK, f"_hp_{name}_{int(vin)}V_{int(lcable*1e9)}.txt")
    cir = f"""* hotplug {name}
Vsrc src 0 PWL(0 0 100n {vin})
Rcable src vinc 0.05
Lcable vinc vin {lcable}
{branches('vin', bin_, 'ci')}
.save v(vin)
.tran 2n 100u 0 2n
.control
set wr_singlescale
run
wrdata {f} v(vin)
.endc
.end
"""
    run(cir, f"hp_{name}_{int(vin)}V_{int(lcable*1e9)}")
    d = np.loadtxt(f)
    return round(float(d[:, 1].max()), 2)


# ---------------------------------------------------------------- input filter impedance vs converter Zin
def zin(name, v, vin=12.0):
    bin_ = models(v["vin"], vin)
    f = os.path.join(WORK, f"_zs_{name}.txt")
    cir = f"""* source impedance {name}
Rcable 0 vinc 0.05
Lcable vinc vin 0.5u
{branches('vin', bin_, 'ci')}
Iinj 0 vin AC 1
.ac dec 100 1k 10meg
.control
run
wrdata {f} vm(vin)
.endc
.end
"""
    run(cir, f"zs_{name}")
    d = np.loadtxt(f)
    pk = int(np.argmax(d[:, 1]))
    zconv = vin ** 2 / (VOUT * 1.0 / 0.93)
    return {"zs_peak_ohm": round(float(d[pk, 1]), 3), "zs_peak_kHz": round(float(d[pk, 0]) / 1e3, 1),
            "converter_zin_ohm": round(zconv, 1), "margin_x": round(zconv / float(d[pk, 1]), 1)}


def bom(v):
    rows = {}
    for side in ("vin", "vout"):
        for e in v[side]:
            for k in (e if isinstance(e, tuple) else (e,)):
                rows.setdefault(k, 0)
                rows[k] += 1
    cost = sum(LIB[k]["price100"] * n for k, n in rows.items())
    hmax = max(LIB[k]["h"] for k in rows)
    return {"parts": {LIB[k]["mpn"] or k: n for k, n in rows.items()}, "cap_cost_at_100_usd": round(cost, 3),
            "tallest_cap_mm": hmax}


def main(names):
    for name in names:
        v = VARIANTS[name]
        print(f"== {name}: {v['label']}", flush=True)
        r = {"variant": name, "label": v["label"]}
        r["vin_bank"] = [dict(zip(("C_uF", "ESR_mOhm", "ESL_nH", "extraR_ohm", "part"),
                                  (round(c * 1e6, 2), round(e * 1e3, 1), round(l * 1e9, 2), x, k)))
                         for c, e, l, x, k in models(v["vin"], 12.0)]
        r["vout_bank"] = [dict(zip(("C_uF", "ESR_mOhm", "ESL_nH", "extraR_ohm", "part"),
                                   (round(c * 1e6, 2), round(e * 1e3, 1), round(l * 1e9, 2), x, k)))
                          for c, e, l, x, k in models(v["vout"], VOUT)]
        r["cin_eff_uF_12V"] = round(total_c(models(v["vin"], 12.0)) * 1e6, 1)
        r["cin_eff_uF_16V"] = round(total_c(models(v["vin"], 16.0)) * 1e6, 1)
        r["cout_eff_uF"] = round(total_c(models(v["vout"], VOUT)) * 1e6, 1)
        r["fo_eq14_kHz"] = round(3.95 / (VOUT * r["cout_eff_uF"]) * 1e3, 1)
        r["loop"] = loop_sweep(name, v)
        print("   loop", {k: r["loop"][k] for k in r["loop"] if k != "sweep"}, flush=True)
        r["switching_12V"] = switching(name, v, r["loop"]["cff_used_pF"])
        print("   switching", r["switching_12V"], flush=True)
        r["hotplug_peak_V"] = {"16V_0.5uH": hotplug(name, v, 16, 0.5e-6), "16V_1uH": hotplug(name, v, 16, 1e-6),
                               "12V_1uH": hotplug(name, v, 12, 1e-6)}
        print("   hotplug", r["hotplug_peak_V"], flush=True)
        r["source_impedance"] = zin(name, v)
        print("   zs", r["source_impedance"], flush=True)
        r["bom"] = bom(v)
        print("   bom", r["bom"], flush=True)
        json.dump(r, open(os.path.join(OUT, name + ".json"), "w"), indent=1)


if __name__ == "__main__":
    main(sys.argv[1:] or list(VARIANTS))