"""
Runs (1) the independent system-level model, (2) the integrated block-level model, back-annotates
(2) -> (1), and writes comparison figures + a summary table to results/.

    python run_all.py            # full run (~2 min)
    python run_all.py --quick    # fewer Monte-Carlo symbols
"""
import sys
import math
from copy import deepcopy
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from hbc.params import SystemParams, vpp_to_dbm, dbm_to_vpp
from hbc.system_model import SystemModel
from hbc.integrated import IntegratedSystem
from hbc.calibrate import back_annotate, edge_jitter
from hbc.blocks.resonant_tx import ResonantTX

QUICK = "--quick" in sys.argv
N_MC = 2500 if QUICK else 6000
OUT = Path(__file__).parent / "results"
OUT.mkdir(exist_ok=True)

# reference categorical palette (fixed order) + text inks
C1, C2, C3, C4, C5 = "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#6250d6"
INK, INK2, GRID = "#0b0b0b", "#52514e", "#e4e3df"
plt.rcParams.update({
    "figure.facecolor": "#fcfcfb", "axes.facecolor": "#fcfcfb", "savefig.facecolor": "#fcfcfb",
    "axes.edgecolor": INK2, "axes.labelcolor": INK, "text.color": INK,
    "xtick.color": INK2, "ytick.color": INK2, "axes.grid": True, "grid.color": GRID,
    "grid.linewidth": 0.8, "axes.spines.top": False, "axes.spines.right": False,
    "lines.linewidth": 2, "lines.markersize": 7, "font.size": 10, "legend.frameon": False,
    "axes.titleweight": "bold", "axes.titlesize": 11,
})


def save(fig, name):
    fig.tight_layout()
    fig.savefig(OUT / name, dpi=140)
    plt.close(fig)
    print("  wrote", OUT / name)


# ============================================================ setup
print("== back-annotating block-level results into the system model")
p_cal = back_annotate(SystemParams())
p_naive = deepcopy(p_cal)
p_naive.rx.diff_penalty_db = 3.0        # paper's quoted differentiator penalty, no wander model
sys_naive = SystemModel(p_naive, baseline_wander=False)     # paper-only abstraction
sys_cal = SystemModel(p_cal)                                 # back-annotated
blk = IntegratedSystem(p_cal)
print(f"   TX calibrated C_TUNE code = {blk.p.tx.C_tune_code}, electrode Vpp = {blk.tx_vpp:.3f} V")

rows = []  # summary table rows: (metric, paper, system, block)

# ============================================================ F1 TX waveforms
print("== F1 resonant TX waveform")
pulse = blk.pulse
t = pulse["t"] * 1e9
tx = blk.p.tx
w = 1 / math.sqrt(tx.L * tx.C_total)
tt = np.clip(pulse["t"], 0, tx.t_pass)
v_ideal = np.where((pulse["t"] >= 0) & (pulse["t"] <= tx.t_pass), tx.V_TX * (1 - np.cos(2 * np.pi * tx.f_target * tt)), 0)
i_ideal = np.where((pulse["t"] >= 0) & (pulse["t"] <= tx.t_pass),
                   tx.C_total * tx.V_TX * 2 * np.pi * tx.f_target * np.sin(2 * np.pi * tx.f_target * tt), 0)
fig, ax = plt.subplots(3, 1, figsize=(7.5, 7), sharex=True)
ax[0].plot(t, v_ideal, color=C2, ls="--", label="System: ideal V_TX(1 - cos wt)")
ax[0].plot(t, pulse["v_out"], color=C1, label="Block: switched-RLC V_OUT")
ax[0].set_ylabel("V_OUT (V)"); ax[0].legend(loc="upper right")
ax[0].set_title(f"Resonant TX pulse, V_TX = {tx.V_TX} V -> {blk.tx_vpp:.2f} Vpp (ideal 2 x V_TX)")
ax[1].plot(t, i_ideal * 1e3, color=C2, ls="--", label="System: C V_TX w sin(wt)")
ax[1].plot(t, pulse["i_L"] * 1e3, color=C1, label="Block: inductor current")
ax[1].axhline(0, color=INK2, lw=0.8)
ax[1].set_ylabel("i_L (mA)"); ax[1].legend(loc="upper right")
ax[1].annotate("negative current = energy\nreturned to V_TX", xy=(50, -2), color=INK2, fontsize=9)
ax[2].step(t, pulse["pass_on"] * 1.0, color=C3, where="post", label="Pass")
ax[2].step(t, pulse["reset_on"] * 0.6, color=C5, where="post", label="Reset (force discharge)")
ax[2].set_ylabel("switch"); ax[2].set_yticks([]); ax[2].legend(loc="upper right")
ax[2].set_xlabel("time (ns)"); ax[2].set_xlim(-5, 240)
save(fig, "F1_tx_waveform.png")

# ============================================================ F2 TX energy & calibration
print("== F2 TX energy vs C_TUNE and vs V_TX")
txb = ResonantTX(deepcopy(blk.p.tx))
cal = txb.calibrate(codes=range(0, 128, 4))
codes = cal["codes"]
C_of = lambda c: tx.C_load + tx.C_par_out + c * tx.C_tune_unit
sys_det = [sys_cal.detune_energy(tx.V_TX, C_of(c)) for c in codes]
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
e_ref = 2 * C_of(cal["best"]) * tx.V_TX ** 2     # 1/2 C (2 V_TX)^2 : energy at pulse peak
ax[0].plot(codes, cal["residual"], color=C1, marker="o", label="Block: |V_OUT| at Pass-off (V)")
ax[0].plot(codes, np.sqrt(2 * np.array(sys_det) / C_of(codes)), color=C2, ls="--",
           label="System: lossless detune residual (V-equiv.)")
ax[0].axvline(cal["best"], color=INK2, lw=1, ls=":")
ax[0].annotate(f"block optimum: code {cal['best']}\n(system: code ~16, it ignores\nC_lx / damper loading)",
               xy=(cal["best"], 0.12), xytext=(45, 0.05), color=INK2, fontsize=9,
               arrowprops=dict(arrowstyle="->", color=INK2, lw=0.8))
ax[0].set_xlabel("C_TUNE code (127 fF/LSB)"); ax[0].set_ylabel("residual at Pass-off (V)")
ax[0].set_title("Foreground resonance calibration (Fig. 5)"); ax[0].legend(loc="upper left")
vtx = np.linspace(0.3, 1.65, 10)
e_blk, e_sys, e_cmos = [], [], []
for v in vtx:
    tb = ResonantTX(deepcopy(blk.p.tx)); tb.p.V_TX = v
    e_blk.append(tb.simulate_pulse()["energy"]["total"])
    e_sys.append(sys_cal.tx_energy_per_pulse(v)["total"] - sys_cal.p.tx.E_dtc_per_pulse)
    e_cmos.append(sys_cal.cmos_energy_per_pulse(2 * v))
ax[1].semilogy(2 * vtx, np.array(e_cmos) * 1e12, color=INK2, ls=":", label="CMOS driver C V^2/2 (same swing)")
ax[1].semilogy(2 * vtx, np.array(e_sys) * 1e12, color=C2, ls="--", label="System model")
ax[1].semilogy(2 * vtx, np.array(e_blk) * 1e12, color=C1, marker="o", label="Block (circuit sim)")
ax[1].set_xlabel("output swing 2 x V_TX (V)"); ax[1].set_ylabel("energy per pulse (pJ)")
ax[1].set_title("TX energy per pulse (6 bits/pulse -> divide by 6 for pJ/b)"); ax[1].legend()
save(fig, "F2_tx_energy_calibration.png")

# ============================================================ F3 spectrum
print("== F3 spectra")
sp = SystemModel.pulse_spectra()
r_prbs = blk.run(1500, rx_vpp=0.06, keep=True)
v = r_prbs["v_tx"]
fs = blk.p.rx.fs
nseg = 1 << 14
segs = v[: (v.size // nseg) * nseg].reshape(-1, nseg) * np.hanning(nseg)
psd = np.mean(np.abs(np.fft.rfft(segs, axis=1)) ** 2, axis=0)
fp = np.fft.rfftfreq(nseg, 1 / fs)
psd_db = 10 * np.log10(psd / psd[(fp > 1e5)].max())
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
m = (sp["f"] > 1e6) & (sp["f"] < 2e8)
for name, col in (("square", C3), ("staircase", C4), ("cosine", C1)):
    ax[0].semilogx(sp["f"][m], sp[name][m], color=col, label=dict(square="Square (CMOS)",
                   staircase="4-level adiabatic [1]", cosine="Raised cosine (this work)")[name])
ax[0].axvspan(30e6, 2e8, color=C2, alpha=0.08)
ax[0].text(35e6, -5, "> 30 MHz: leaves the body", color=INK2, fontsize=9)
ax[0].set_ylim(-80, 3); ax[0].set_xlabel("frequency (Hz)"); ax[0].set_ylabel("dB (normalised)")
ax[0].set_title("System: single-pulse spectra (Fig. 3)"); ax[0].legend(loc="lower left")
mm = (fp > 1e5) & (fp < 1e8)
ax[1].semilogx(fp[mm], psd_db[mm], color=C1)
ax[1].set_xlabel("frequency (Hz)"); ax[1].set_ylabel("dB (normalised)")
ax[1].set_title("Block: PSD of the simulated DMPPM PRBS electrode voltage (Fig. 11)")
save(fig, "F3_spectrum.png")

# ============================================================ F4 RX internal waveforms
print("== F4 RX internal waveforms")
r = blk.run(40, rx_vpp=0.05, keep=True, seed=3)
rx = r["rx"]
tt = np.arange(r["v_rx"].size) / fs * 1e9
sl = (tt > 950) & (tt < 2400)
fig, ax = plt.subplots(4, 1, figsize=(9, 8), sharex=True)
ax[0].plot(tt[sl], r["v_rx"][sl] * 1e3, color=C1); ax[0].set_ylabel("RX in (mV)")
ax[0].set_title("Block-level RX internal waveforms (cf. paper Fig. 7)")
ax[1].plot(tt[sl], rx["s1"][sl] * 1e3, color=C1, label="S1 output")
ax[1].axhline(blk.p.rx.vth_coarse * 1e3, color=C2, ls="--", label="coarse threshold")
ax[1].set_ylabel("S1 (mV)"); ax[1].legend(loc="upper right")
ax[2].fill_between(tt[sl], 0, rx["gate"][sl], color=C3, alpha=0.35, step="mid", label="S3 power-gate (one-shot)")
ax[2].set_ylabel("gated VDD"); ax[2].set_yticks([]); ax[2].legend(loc="upper right")
ax[3].plot(tt[sl], rx["s3_in"][sl] * 1e3, color=C5, label="d/dt path (S3 input)")
ax[3].axhline(0, color=INK2, lw=0.8)
for s in rx["timestamps"]:
    if 950 < s * 1e9 < 2400:
        for a in ax:
            a.axvline(s * 1e9, color=C2, lw=1, ls=":")
ax[3].set_ylabel("S3 in (mV)"); ax[3].set_xlabel("time (ns)"); ax[3].legend(loc="upper right")
save(fig, "F4_rx_waveforms.png")

# ============================================================ F5 walk error
print("== F5 amplitude-induced timing error: threshold vs zero-crossing")
sig_a = [0.0, 0.05, 0.10, 0.20, 0.30]
res = {"zero_cross": [], "threshold": []}
sysres = {"zero_cross": [], "threshold": []}
for mode in res:
    for sa in sig_a:
        q = deepcopy(p_cal); q.ch.amp_var_sigma = sa
        I = IntegratedSystem(q, mode=mode, nominal_rx_vpp=0.06)
        res[mode].append(edge_jitter(I, 0.06, n_sym=800))
        sysres[mode].append(SystemModel(q).timing_sigma(0.06, mode))
fig, ax = plt.subplots(figsize=(7, 4.2))
x = np.array(sig_a) * 100
ax.plot(x, np.array(res["threshold"]) * 1e9, color=C2, marker="o", label="Block: fixed threshold")
ax.plot(x, np.array(sysres["threshold"]) * 1e9, color=C2, ls="--", label="System: threshold (walk model)")
ax.plot(x, np.array(res["zero_cross"]) * 1e9, color=C1, marker="o", label="Block: peak-to-zero-crossing")
ax.plot(x, np.array(sysres["zero_cross"]) * 1e9, color=C1, ls="--", label="System: zero-crossing")
ax.axhline(blk.p.dmppm.t_slot / 2 / 3 * 1e9, color=INK2, ls=":", lw=1)
ax.text(0.5, blk.p.dmppm.t_slot / 6 * 1e9 + 0.05, "slot/6 (~3 sigma inside half-slot)", color=INK2, fontsize=9)
ax.set_xlabel("per-pulse amplitude variation (% rms)"); ax.set_ylabel("RX edge timing error (ns rms)")
ax.set_title("Why the paper differentiates: walk error vs amplitude variation (60 mVpp)")
ax.legend()
save(fig, "F5_walk_error.png")

# ============================================================ F6 BER vs input power
print("== F6 BER vs input power (6 b/pulse and 1 b/pulse)")
fig, ax = plt.subplots(figsize=(8, 5))
paper_sens = {6: -47.0, 1: -61.0}
for bpp, col in ((6, C1), (1, C3)):
    q = deepcopy(p_cal); q.dmppm.bits_per_pulse = bpp
    qn = deepcopy(p_naive); qn.dmppm.bits_per_pulse = bpp
    S, Sn = SystemModel(q), SystemModel(qn, baseline_wander=False)
    I = IntegratedSystem(q)
    dbm = np.linspace(-68, -38, 61)
    ax.semilogy(dbm, [S.link(dbm_to_vpp(d)).ber for d in dbm], color=col, label=f"System, back-annotated ({bpp} b/p)")
    ax.semilogy(dbm, [Sn.link(dbm_to_vpp(d)).ber for d in dbm], color=col, ls=":", label=f"System, paper-only ({bpp} b/p)")
    pts = np.arange(-66, -39, 2) if bpp == 1 else np.arange(-54, -39, 2)
    bb = []
    for d in pts:
        rr = I.run(N_MC if bpp == 6 else N_MC * 3, rx_vpp=dbm_to_vpp(d), seed=int(-d))
        bb.append(rr["ber"])
    bb = np.array(bb, float)
    keep = bb > 0
    ax.semilogy(pts[keep], bb[keep], ls="none", marker="o", color=col, label=f"Block-level Monte Carlo ({bpp} b/p)")
    ax.plot(paper_sens[bpp], 1e-3, marker="*", ms=14, color=C2, ls="none",
            label="Paper measured sensitivity" if bpp == 6 else None)
    s_sys = vpp_to_dbm(S.sensitivity())
    s_blk = float(np.interp(-3, np.log10(np.maximum(bb[::-1], 1e-7)), pts[::-1].astype(float)))
    rows.append((f"Sensitivity @BER 1e-3, {bpp} b/pulse (dBm)", f"{paper_sens[bpp]}", f"{s_sys:.1f}", f"{s_blk:.1f}"))
ax.axhline(1e-3, color=INK2, ls="--", lw=1)
ax.set_ylim(1e-5, 0.6); ax.set_xlabel("RX input power (dBm, 8 kOhm reference as in the paper)")
ax.set_ylabel("BER"); ax.set_title("BER vs input power (cf. Fig. 9)")
ax.legend(fontsize=8, ncol=2, loc="lower left")
save(fig, "F6_ber.png")

# ============================================================ F7 energy vs BPP
print("== F7 energy vs bits/pulse")
eb = sys_cal.energy_vs_bpp()
fig, ax = plt.subplots(figsize=(7, 4.2))
ax.semilogy(eb["bpp"], eb["tx"] * 1e12, color=C2, label="TX ~ K_TX / DR")
ax.semilogy(eb["bpp"], eb["rx"] * 1e12, color=C1, label="RX ~ floor/DR + K_RX 2^(2DR)")
ax.semilogy(eb["bpp"], eb["total"] * 1e12, color=C3, ls="--", label="1 TX + 1 RX")
rb = blk.run(N_MC, rx_vpp=0.06)
ax.plot(6, rb["link_pj_per_bit"], marker="*", ms=14, color=C5, ls="none", label="Block-level integrated (6 b/p)")
ax.axvline(eb["opt"], color=INK2, ls=":", lw=1)
ax.text(eb["opt"] + 0.1, eb["total"].max() * 0.6, f"optimum ~{eb['opt']:.0f} b/pulse", color=INK2)
ax.set_xlabel("encoding density (bits/pulse) @ 2.5 MHz pulse rate"); ax.set_ylabel("energy (pJ/bit)")
ax.set_title("System model: energy vs DMPPM encoding density (Fig. 8)"); ax.legend(fontsize=9)
save(fig, "F7_energy_vs_bpp.png")

# ============================================================ F8 power breakdown
print("== F8 power breakdown")
st = sys_cal.summary()
txs, rxs = st["tx_breakdown"], st["rx_breakdown"]
txb_, rxb_ = rb["tx_breakdown"], rb["rx_breakdown"]
paper_tx = dict(resistive=7.3, parasitic=3.52, gate=1.65, dtc=0.28)
paper_rx = dict(tdc=15.67, s0=10.5, s1=10.5, s2=6.3, s3=2.4)
cats_tx = ["resistive", "parasitic", "gate", "dtc"]
sys_tx = [txs["resistive"], txs["parasitic"] + txs["detune"], txs["gate"], txs["dtc"]]
blk_tx = [txb_["resistive"] + max(txb_["pass_gate"] - 0.5 * blk.p.tx.C_lx * blk.p.tx.V_TX ** 2 * 2.5e6, 0),
          txb_["damper_reset"] + 0.5 * blk.p.tx.C_lx * blk.p.tx.V_TX ** 2 * 2.5e6, txb_["gate"], txb_["dtc"]]
cats_rx = ["tdc", "s0", "s1", "s2", "s3"]
sys_rx = [rxs["tdc"], rxs["amp_s0"], rxs["amp_s1"], rxs["amp_s2"], rxs["amp_s3"]]
blk_rx = [rxb_["tdc"], rxb_["amp_s0"], rxb_["amp_s1"], rxb_["amp_s2"], rxb_["amp_s3"]]
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
for a, cats, pap, sy, bl, ttl in ((ax[0], cats_tx, paper_tx, sys_tx, blk_tx, "TX (uW)"),
                                  (ax[1], cats_rx, paper_rx, sys_rx, blk_rx, "RX (uW)")):
    xx = np.arange(len(cats)); wbar = 0.26
    a.bar(xx - wbar, [pap[c] for c in cats], wbar - 0.02, color=INK2, label="Paper Fig. 13")
    a.bar(xx, np.array(sy) * 1e6, wbar - 0.02, color=C2, label="System model")
    a.bar(xx + wbar, np.array(bl) * 1e6, wbar - 0.02, color=C1, label="Block-level integrated")
    a.set_xticks(xx, cats); a.set_title(ttl); a.legend(fontsize=9); a.grid(axis="x", visible=False)
ax[0].set_ylabel("power (uW)")
save(fig, "F8_power_breakdown.png")

rows += [
    ("Average bit rate (Mb/s)", "15", f"{st['bitrate'] / 1e6:.2f}", f"{rb['bitrate'] / 1e6:.2f}"),
    ("TX power (uW)", "12.75", f"{st['tx_power'] * 1e6:.2f}", f"{rb['tx_power'] * 1e6:.2f}"),
    ("RX power (uW)", "48", f"{st['rx_power'] * 1e6:.2f}", f"{rb['rx_power'] * 1e6:.2f}"),
    ("TX energy (pJ/b)", "0.85", f"{st['tx_pj_per_bit']:.2f}", f"{rb['tx_pj_per_bit']:.2f}"),
    ("RX energy (pJ/b)", "3.2", f"{st['rx_pj_per_bit']:.2f}", f"{rb['rx_pj_per_bit']:.2f}"),
    ("TX+RX energy (pJ/b)", "2.2 (definition unclear)", f"{st['link_pj_per_bit']:.2f}", f"{rb['link_pj_per_bit']:.2f}"),
    ("Tank Q (sqrt(L/C)/R)", ">40 inductor only", f"{st['Q']:.1f}", "-"),
    ("Resonant / CMOS energy", "-", f"{st['resonant_vs_cmos']:.3f}", "-"),
    ("S3 comparator duty", "-", f"{min(1, blk.p.rx.oneshot / blk.p.dmppm.t_mean):.2f}", f"{rb['s3_duty']:.2f}"),
    ("Interval error rms @60 mVpp, incl. 1 ns DTC rounding (ns)", "<2 (edge jitter, Fig. 11)",
     f"{math.hypot(sys_cal.interval_sigma(0.06), blk.p.tx.dtc_lsb / math.sqrt(6)) * 1e9:.2f}",
     f"{rb['interval_err_rms'] * 1e9:.2f}"),
]

# ============================================================ F9 multi-node TDMA
print("== F9 multi-node TDMA demo")
nodes = [dict(name="Video (TX1, 90 cm)", d_cm=90, rate=10.0),
         dict(name="Audio (TX2, 120 cm)", d_cm=120, rate=4.0),
         dict(name="ECG (TX3, 150 cm)", d_cm=150, rate=0.2)]
rt = blk.run_tdma(nodes, n_packets=150 if QUICK else 400, keep=True)
fig, ax = plt.subplots(2, 1, figsize=(10, 6))
tt = np.arange(rt["v_rx"].size) / fs * 1e6
ax[0].plot(tt, rt["v_rx"] * 1e3, color=C1, lw=0.6)
ax[0].set_xlim(0, min(tt[-1], 80)); ax[0].set_xlabel("time (us)"); ax[0].set_ylabel("RX in (mV)")
ax[0].set_title("Block-level TDMA: three body-worn TXs into one RX hub (cf. Fig. 10)")
names = [n["name"] for n in rt["nodes"]]
ser = [max(n["ser"], 1e-5) for n in rt["nodes"]]
share = [n["share"] * 100 for n in rt["nodes"]]
ax[1].barh(names, ser, color=[C1, C3, C5])
for i, n in enumerate(rt["nodes"]):
    ax[1].text(ser[i] * 1.3, i, f"SER {n['ser']:.1e}, {share[i]:.1f}% of {rt['bitrate'] / 1e6:.1f} Mb/s, "
               f"RX amp {SystemModel(p_cal).rx_vpp_at(n['d_cm']) * 1e3:.0f} mVpp (system)", va="center", fontsize=9)
ax[1].set_xscale("log"); ax[1].set_xlim(1e-5, 10); ax[1].set_xlabel("symbol error rate (floor 1e-5 = none seen)")
ax[1].grid(axis="y", visible=False)
save(fig, "F9_tdma.png")

# ============================================================ F10 BER vs distance
print("== F10 BER vs distance")
fig, ax = plt.subplots(figsize=(7, 4.2))
dist = np.linspace(60, 260, 41)
for v_tx, col in ((1.0, C1), (1.65, C2)):
    ax.semilogy(dist, [max(sys_cal.link(sys_cal.rx_vpp_at(d, v_tx)).ber, 1e-9) for d in dist], color=col,
                label=f"System, {2 * v_tx:.1f} Vpp TX")
    q = deepcopy(p_cal); q.tx.V_TX = v_tx
    I = IntegratedSystem(q)
    pts = np.arange(120, 261, 20)
    bb = np.array([I.run(N_MC // 2, d_cm=float(d), seed=int(d))["ber"] for d in pts])
    k = bb > 0
    ax.semilogy(pts[k], bb[k], ls="none", marker="o", color=col, label=f"Block, {2 * v_tx:.1f} Vpp TX")
ax.axhline(1e-3, color=INK2, ls="--", lw=1)
ax.set_ylim(1e-6, 0.5); ax.set_xlabel("TX-RX distance on body (cm, extrapolated beyond 150 cm)")
ax.set_ylabel("BER"); ax.set_title("Reach vs TX amplitude (6 b/pulse)"); ax.legend(fontsize=9)
save(fig, "F10_ber_vs_distance.png")

# ============================================================ summary
md = ["| Metric | Paper | System model | Block-level integrated |", "|---|---|---|---|"]
md += [f"| {a} | {b} | {c} | {d} |" for a, b, c, d in rows]
md += ["", f"Back-annotated: e_n = {p_cal.rx.en_in * 1e9:.0f} nV/rtHz, S0/S1 gain = {p_cal.rx.g_s0:.2f}, "
       f"timing penalty = {p_cal.rx.diff_penalty_db:+.2f} dB (paper: ~3 dB), TX C_TUNE code = {blk.p.tx.C_tune_code}",
       "", "TDMA per-node:"] + [f"- {n['name']}: SER {n['ser']:.2e}, share {n['share'] * 100:.1f}%" for n in rt["nodes"]]
(OUT / "summary.md").write_text("\n".join(md) + "\n")
print("\n".join(md))
