main
John Lauer ECAS study: clear the impedance chart's labels 25fe102
#!/usr/bin/env python3
"""VIN rail impedance on the real copper, from Adom Fields' own PDN solves.

Adom Fields 0.7.13 solved two copies of the board with the measured capacitor curves (spec capCurves ->
../fields/curves): the board as built, and the same board with C1's MPN set to the 33 uF ECAS
(fields/out-asbuilt, fields/out-ecas-c1). A third curve adds the 0.22 ohm damping resistor in series with
C1 to the ECAS solve's own branches (same copper, same mounting inductance) and re-solves in ngspice.
Run: python3 pdn_compare.py -> ../results/pdn_compare.json, ../img/pdn-vin.png
"""
import json, os, subprocess
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.join(HERE, "..")
WORK = os.path.join(ROOT, "work")
RDAMP = 0.22


def rail(out, net="VIN"):
    d = json.load(open(os.path.join(ROOT, "fields", out, "fields.json")))
    p = d["review"]["pdn"]
    return np.array(p["fHz"]), next(r for r in p["rails"] if r["net"] == net)


def solve(tag, branches, f):
    lines = ["* " + tag, "Iin 0 rail AC 1"]
    for i, b in enumerate(branches):
        lines += [f"R{i}a rail n{i}a {b['r']}", f"L{i}a n{i}a n{i}b {b['l'] or 1e-15}"]
        tail = f"n{i}b"
        if b.get("lp"):
            lines += [f"L{i}p n{i}b n{i}c {b['lp']}", f"R{i}p n{i}b n{i}c {b['rp']}"]
            tail = f"n{i}c"
        lines.append(f"C{i} {tail} 0 {b['c']}" if b["c"] else f"R{i}g {tail} 0 1e-6")
    w = os.path.join(WORK, f"_pdn_{tag}.txt")
    lines += [f".ac dec 40 {f[0]:g} {f[-1]:g}", ".control", "run", f"wrdata {w} vm(rail)", ".endc", ".end"]
    p = os.path.join(WORK, f"pdn_{tag}.cir")
    open(p, "w").write("\n".join(lines) + "\n")
    subprocess.run(["ngspice", "-b", p], capture_output=True, check=True)
    d = np.loadtxt(w)
    return d[:, 0], d[:, 1]


fa, ra = rail("out-asbuilt")
fe, re_ = rail("out-ecas-c1")
br = [dict(b) for b in re_["branches"]]
for b in br:
    if b["name"] == "C1":
        b["r"] = b["r"] + RDAMP
curves = {"as built (Adom Fields, measured parts)": (fa, np.array(ra["zOhm"])),
          "C1 = 33 µF ECAS, bare (Adom Fields)": (fe, np.array(re_["zOhm"])),
          f"C1 = 33 µF ECAS + {RDAMP} Ω": solve("VIN_ecas_damped", br, fe)}
lo, hi = ra["bandHz"]
res = {"target_ohm": ra["targetOhm"], "band_Hz": [lo, hi],
       "middlebrook": {"as built": ra["middlebrook"], "ecas bare": re_["middlebrook"]}}
for k, (f, z) in curves.items():
    m = (f >= lo) & (f <= 2e5)
    i = int(np.argmax(z[m]))
    res[k] = {"low_peak_ohm": round(float(z[m][i]), 4), "low_peak_Hz": round(float(f[m][i])),
              "z_at_500kHz_ohm": round(float(np.interp(5e5, f, z)), 4)}
json.dump(res, open(os.path.join(ROOT, "results", "pdn_compare.json"), "w"), indent=1)
print(json.dumps(res, indent=1))

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
SURF, INK2, GRID = "#fcfcfb", "#52514e", "#e4e3df"
S = ["#2a78d6", "#eb6834", "#1baf7a"]
plt.rcParams.update({"figure.facecolor": SURF, "axes.facecolor": SURF, "axes.edgecolor": GRID, "axes.labelcolor": INK2,
                     "xtick.color": INK2, "ytick.color": INK2, "axes.grid": True, "grid.color": GRID,
                     "axes.spines.top": False, "axes.spines.right": False, "legend.frameon": False,
                     "axes.titlesize": 13, "axes.titleweight": "bold", "font.size": 11})
fig, ax = plt.subplots(figsize=(10, 5))
for i, (k, (f, z)) in enumerate(curves.items()):
    ax.loglog(f, z, color=S[i], lw=2, label=k)
    p = res[k]
    ax.plot([p["low_peak_Hz"]], [p["low_peak_ohm"]], "o", color=S[i], ms=7, mec=SURF, mew=2)
    off = [(8, 6), (-66, -2), (6, -16)][i]
    ax.annotate(f"{p['low_peak_ohm']*1e3:.0f} mΩ", (p["low_peak_Hz"], p["low_peak_ohm"]), xytext=off, textcoords="offset points", fontsize=9.5)
ax.axhline(ra["targetOhm"], color=INK2, lw=1, ls="--")
ax.text(9e7, ra["targetOhm"] * 1.12, f"target {ra['targetOhm']*1e3:.0f} mΩ (5 % of 12 V at a {ra['stepA']:g} A step)", fontsize=9.5, color=INK2, ha="right")
ax.set_xlim(1e3, 1e8); ax.set_ylim(1e-3, 3)
ax.set_xlabel("Hz"); ax.set_ylabel(f"|Z| at {ra['load']} (Ω)")
ax.set_title("VIN rail impedance on the board's real copper", loc="left")
ax.legend(loc="lower left", fontsize=9.5)
fig.tight_layout(); fig.savefig(os.path.join(ROOT, "img", "pdn-vin.png"), dpi=130); plt.close(fig)