#!/usr/bin/env python3
"""
Amplifier efficiency from a TX-gain ramp: RF output at the apex monitor against the
electrical power above idle (power clamp), one point per gain step.

How the points are made:
  1. For every power clamp sample (every ~5 s), take the median RF power in a window
     around it. Pairs where the RF level changes inside that window (a step edge)
     are dropped.
  2. Idle levels: the detector floor (RF) and the power drawn without transmitting
     (P_idle, ~0.17 kW) are taken from the pairs where nothing is transmitted.
  3. Consecutive pairs at the same RF level form one step; each step becomes one
     point (median, with the spread as error bar). With a catalog, the step gets
     the tx_gain of the transmission it falls in.

The apex monitor isn't calibrated against the PA output, so the RF axis is relative
(power at the monitor) and the efficiency is normalised to its maximum.

In a notebook:
    from plot_efficiency import ramp_steps, efficiency_mpl, ramp_check_mpl
    steps = ramp_steps("ancillary", "2026-10-17", start="13:30", end="14:20", catalog="catalog")
    steps                                  # the numbers, one row per step
    ramp_check_mpl("ancillary", steps)     # time series with the steps marked
    efficiency_mpl(steps)                  # the figure for the paper

From the command line:
    python plot_efficiency.py ancillary/ 2026-10-17 --start 13:30 --end 14:20 \\
        --catalog catalog/ -o efficiency.pdf --check ramp_check.png
"""

import argparse
from pathlib import Path

import numpy as np
import pandas as pd

from ingest_ancillary import load_ancillary, parse_times

WINDOW_S = 5.0      # RF window around each power clamp sample
STABLE_DB = 0.3     # max RF spread (IQR) inside a window to count as steady
ON_DB = 3.0         # RF this far above the detector floor = transmitting
STEP_DB = 0.4       # RF change that starts a new step
MIN_PAIRS = 1       # pairs needed for a step (a 10 s transmission gives only 1-2)
OFF_KW = 0.02       # power clamp readings below this: amplifier switched off, not idle

# TX gain of steps the catalog doesn't know about (no SigMF recorded), by step start
# time (UTC, matched within KNOWN_GAINS_TOL_S). The power ramp of 2026-10-17, from the
# transmit log: 10 s CWs at 40, 43, 46, 49, 51, 52, 53, 54, 54 dB, then a 60 s CW at
# 54 dB. Checked against the RF time series: nine short blocks from 10:28:15 on, the
# 53 dB one (~10:31:25) was not detected as a step with MIN_PAIRS = 2.
KNOWN_GAINS = {
    "2026-10-17 10:28:17": 40,
    "2026-10-17 10:28:46": 43,
    "2026-10-17 10:29:21": 46,
    "2026-10-17 10:30:11": 49,
    "2026-10-17 10:30:49": 51,
    "2026-10-17 10:31:09": 52,
    "2026-10-17 10:31:28": 53,   # ~10:31:25-10:31:35; only found with MIN_PAIRS = 1
    "2026-10-17 10:32:14": 54,
    "2026-10-17 10:33:13": 54,
    "2026-10-17 10:35:34": 54,   # the 60 s CW
}
KNOWN_GAINS_TOL_S = 10

INK, INK_MUTED, GRID = "#0b0b0b", "#52514e", "#e4e3df"
SEQ = ["#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", "#0d366b"]


def _window(date, start, end):
    day = pd.Timestamp(date).date()
    t0 = pd.Timestamp(f"{day} {start or '00:00'}", tz="UTC")
    t1 = (pd.Timestamp(f"{day} {end}", tz="UTC") if end
          else t0.normalize() + pd.Timedelta(1, unit="D"))
    return t0, t1


def pair_samples(rf, pc, window_s=WINDOW_S):
    """One row per power clamp sample with the RF median and spread around it."""
    # integer nanoseconds, whatever resolution pandas stores (ns in 1.x/2.x, us in 3.x)
    t_rf = rf["time"].dt.tz_localize(None).to_numpy().astype("datetime64[ns]").astype("int64")
    db = rf["rf_power_dbm"].to_numpy(dtype=float)
    half = int(window_s / 2 * 1e9)
    rows = []
    for t, p in zip(pc["time"], pc["power_kw"]):
        ti = t.value
        i0, i1 = np.searchsorted(t_rf, [ti - half, ti + half])
        w = db[i0:i1]
        if len(w) < 0.5 * window_s * 10:          # less than half the expected samples
            continue
        q1, med, q3 = np.percentile(w, [25, 50, 75])
        rows.append((t, float(p), med, q3 - q1))
    return pd.DataFrame(rows, columns=["time", "power_kw", "rf_dbm", "rf_iqr_db"])


def _eff_rel(steps):
    """RF out / power above idle, relative to the step at the highest power."""
    ratio = steps["rf_rel"] / steps["added_kw"]
    usable = steps["added_kw"] > 0.05 * steps["added_kw"].max()   # avoid dividing by ~0
    return (ratio / ratio[steps["added_kw"].idxmax()]).where(usable)


def apply_known_gains(steps):
    """Fill tx_gain from KNOWN_GAINS where the catalog didn't provide one."""
    if "tx_gain" not in steps:
        steps["tx_gain"] = np.nan
    for t, g in KNOWN_GAINS.items():
        t = pd.Timestamp(t, tz="UTC")
        dt = (steps["t_start"] - t).abs().dt.total_seconds()
        hit = (dt <= KNOWN_GAINS_TOL_S) & steps["tx_gain"].isna()
        steps.loc[hit, "tx_gain"] = float(g)
    return steps


def read_steps(csv):
    """Steps table saved with --csv, ready for fit_overhead / efficiency_mpl."""
    steps = pd.read_csv(csv)
    for c in ("t_start", "t_end"):
        steps[c] = parse_times(steps[c])
    steps.attrs["p_idle_kw"] = float((steps["power_kw"] - steps["added_kw"]).median())
    steps["eff_rel"] = _eff_rel(steps)
    return apply_known_gains(steps)


def fit_overhead(steps, min_kw=None):
    """Straight line RF = k * (added - x0) through the steps (optionally only those with
    added_kw >= min_kw). Returns a dict with x0 (kW above idle where RF would be zero),
    the total overhead x0 + P_idle, the slope relative to the efficiency at the highest
    step (marginal / average), their 1-sigma errors and the points used."""
    use = steps if min_kw is None else steps[steps["added_kw"] >= min_kw]
    x = use["added_kw"].to_numpy(float)
    y = (use["rf_rel"] / steps["rf_rel"][steps["added_kw"].idxmax()]).to_numpy(float)
    n = len(x)
    if n < 2:
        raise ValueError("need at least 2 steps for a line fit")
    A = np.vstack([x, np.ones(n)]).T
    (k, b), *_ = np.linalg.lstsq(A, y, rcond=None)
    x0 = -b / k
    out = {"n": n, "slope": k, "x0_kw": x0, "overhead_kw": x0 + steps.attrs["p_idle_kw"],
           "slope_rel": k * steps["added_kw"].max(),   # marginal / average eff at top
           "x0_err": np.nan, "slope_rel_err": np.nan, "rms_resid": np.nan, "min_kw": min_kw}
    if n > 2:
        res = y - (k * x + b)
        cov = (res @ res / (n - 2)) * np.linalg.inv(A.T @ A)
        var_k, var_b, cov_kb = cov[0, 0], cov[1, 1], cov[0, 1]
        out["x0_err"] = np.sqrt(var_b + x0 ** 2 * var_k + 2 * x0 * cov_kb) / abs(k)
        out["slope_rel_err"] = np.sqrt(var_k) * steps["added_kw"].max()
        out["rms_resid"] = np.sqrt(np.mean(res ** 2))
    return out


def compression_point(steps, db=1.0):
    """Gain compression against TX gain: how far the RF (dBm) falls behind a slope-1
    line through the lowest-gain step. Returns the TX gain where that reaches `db`
    (linear interpolation), or None. The lowest step is assumed to be linear, so the
    result is an upper limit if the amplifier already compresses there."""
    d = steps.dropna(subset=["tx_gain"]).groupby("tx_gain")["rf_dbm"].median().sort_index()
    if len(d) < 3:
        return None
    g0, r0 = d.index[0], d.iloc[0]
    comp = (d.index - g0) - (d - r0)
    above = np.nonzero(comp.to_numpy() >= db)[0]
    out = {"g_ref": float(g0), "rf_ref": float(r0), "db": db,
           "compression": comp, "g_1db": None}
    if len(above) and above[0] > 0:
        i = above[0]
        ga, gb, ca, cb = d.index[i - 1], d.index[i], comp.iloc[i - 1], comp.iloc[i]
        out["g_1db"] = float(ga + (db - ca) / (cb - ca) * (gb - ga))
    return out


def ramp_steps(root, date, start=None, end=None, catalog=None):
    """Steps of a power ramp as a DataFrame (one row per step).

    Columns: t_start, t_end, n, power_kw, power_kw_err, added_kw, rf_dbm, rf_dbm_err,
    rf_rel (linear RF above the detector floor, relative), eff_rel (efficiency,
    max = 1), tx_gain. The idle levels are in steps.attrs.
    """
    t0, t1 = _window(date, start, end)
    rf = load_ancillary(root, "rfpower", t0, t1)
    pc = load_ancillary(root, "powerclamp", t0, t1).dropna(subset=["power_kw"])
    pairs = pair_samples(rf, pc)
    pairs = pairs[pairs["rf_iqr_db"] < STABLE_DB].reset_index(drop=True)
    if pairs.empty:
        raise ValueError("no steady RF/power pairs in this period")

    floor = rf["rf_power_dbm"].quantile(0.02)
    floor = rf.loc[rf["rf_power_dbm"] < floor + 1, "rf_power_dbm"].median()
    on = pairs["rf_dbm"] > floor + ON_DB
    if (~on).sum() < 3:
        raise ValueError("too few idle samples to determine the idle power; "
                         "widen the start/end window to include some time without TX")
    idle = ~on & (pairs["power_kw"] > OFF_KW)
    if idle.sum() < 3:
        raise ValueError("too few idle samples with the amplifier switched on")
    p_idle = pairs.loc[idle, "power_kw"].median()

    # group consecutive transmitting pairs at the same RF level into steps
    tx = pairs[on].copy()
    new = (tx["rf_dbm"].diff().abs() > STEP_DB) | \
          (tx["time"].diff().dt.total_seconds() > 2.5 * WINDOW_S)
    tx["step"] = new.cumsum()
    steps = []
    for _, g in tx.groupby("step"):
        if len(g) >= 3:
            g = g.iloc[1:]           # first clamp reading may still be mid-transition
        if len(g) < MIN_PAIRS:
            continue
        steps.append({
            "t_start": g["time"].iloc[0], "t_end": g["time"].iloc[-1], "n": len(g),
            "power_kw": g["power_kw"].median(), "power_kw_err": g["power_kw"].std(),
            "rf_dbm": g["rf_dbm"].median(), "rf_dbm_err": g["rf_dbm"].std(),
        })
    steps = pd.DataFrame(steps)
    if steps.empty:
        raise ValueError("no steps found; check the time window")

    steps["added_kw"] = steps["power_kw"] - p_idle
    # linear RF at the monitor above the detector floor, in units of the floor
    steps["rf_rel"] = 10 ** ((steps["rf_dbm"] - floor) / 10) - 1
    steps["eff_rel"] = _eff_rel(steps)

    steps["tx_gain"] = np.nan
    if catalog is not None:
        cat = pd.read_csv(Path(catalog) / "transmissions.csv")
        for c in ("tx_time", "tx_end"):
            cat[c] = parse_times(cat[c])
        mid = steps["t_start"] + (steps["t_end"] - steps["t_start"]) / 2
        for i, m in enumerate(mid):
            hit = cat[(cat["tx_time"] <= m) & (cat["tx_end"].fillna(cat["tx_time"]) >= m)]
            if len(hit):
                steps.loc[i, "tx_gain"] = hit["tx_gain"].iloc[0]
    apply_known_gains(steps)

    steps.attrs.update(p_idle_kw=float(p_idle), rf_floor_dbm=float(floor),
                       window=(str(t0), str(t1)))
    return steps


# --------------------------------------------------------------------------
# Figures
# --------------------------------------------------------------------------

def _style(ax):
    ax.grid(color=GRID, lw=0.7)
    ax.set_axisbelow(True)
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    for side in ("left", "bottom"):
        ax.spines[side].set_color(GRID)
    ax.tick_params(colors=INK_MUTED, labelsize=8.5)


def efficiency_mpl(steps, width=None, fit=True, fit_min_kw=None,
                   color_by_time=None, compression=None):
    """(a) RF at the monitor vs electrical power above idle, with a straight-line fit
    RF = k (P - P_idle - x0); (b) efficiency relative to the highest measured power,
    with the curve that line implies. Both relative: the apex monitor isn't calibrated.

    color_by_time: colour points by time and join them in time order (shows ramp up vs
    down); default on from 8 steps.
    compression: add panel c, RF (dBm) against TX gain with the 1 dB compression point;
    default on when at least 3 different TX gains are known."""
    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap

    if color_by_time is None:
        color_by_time = len(steps) >= 8
    top = steps["added_kw"].idxmax()
    rf_norm = steps["rf_rel"] / steps["rf_rel"][top]
    rf_err = rf_norm * steps["rf_dbm_err"] * np.log(10) / 10     # dB spread -> linear
    xmax = steps["added_kw"].max() * 1.08
    comp = compression_point(steps) if "tx_gain" in steps else None
    if compression is None:
        compression = comp is not None
    compression = compression and comp is not None
    ncol = 3 if compression else 2
    width = width or (14 if compression else 10)
    fig, axes = plt.subplots(1, ncol, figsize=(width, width * 0.38 * 2 / ncol))
    a, b = axes[0], axes[1]

    f = fit_overhead(steps, fit_min_kw) if fit and len(steps) >= 2 else None
    if f is not None:
        xs = np.linspace(max(f["x0_kw"], 0), xmax, 100)
        a.plot(xs, f["slope"] * (xs - f["x0_kw"]), color=INK_MUTED, lw=1, ls="--", zorder=1)
        xs = np.linspace(max(f["x0_kw"], 1e-3), xmax, 200)
        b.plot(xs, f["slope_rel"] * (1 - f["x0_kw"] / xs), color=INK_MUTED, lw=1, ls="--",
               zorder=1)
        b.axhline(f["slope_rel"], color=INK_MUTED, lw=0.8, ls=":", zorder=1)
        b.text(xmax * 0.02, f["slope_rel"], "  limit if the slope stays constant",
               va="bottom", fontsize=7.5, color=INK_MUTED)
        a.text(0.03, 0.97,
               f"RF = 0 at {f['x0_kw']:.2f} kW above idle\n"
               f"(overhead {f['overhead_kw']:.2f} kW total)\n"
               f"marginal efficiency\n"
               f"{f['slope_rel']:.2f} × top-step efficiency",
               transform=a.transAxes, va="top", fontsize=8, color=INK, linespacing=1.4)

    if color_by_time:
        cmap = LinearSegmentedColormap.from_list("seq", SEQ[1:])
        minutes = (steps["t_start"] - steps["t_start"].iloc[0]).dt.total_seconds() / 60
        colors = dict(c=minutes, cmap=cmap)
    else:
        colors = dict(color=SEQ[4])
    for ax, y, yerr in ((a, rf_norm, rf_err), (b, steps["eff_rel"], None)):
        if color_by_time:
            ax.plot(steps["added_kw"], y, color=GRID, lw=1, zorder=1)
        ax.errorbar(steps["added_kw"], y, xerr=steps["power_kw_err"], yerr=yerr,
                    fmt="none", ecolor=INK_MUTED, elinewidth=0.6, capsize=0, zorder=2)
        sc = ax.scatter(steps["added_kw"], y, s=40, edgecolors="white", linewidths=1,
                        zorder=3, **colors)
        _style(ax)
        ax.set_xlabel(f"Electrical power above idle (kW; idle {steps.attrs['p_idle_kw']:.2f} kW)",
                      color=INK_MUTED, fontsize=9)
        ax.set_xlim(0, xmax)
        ax.set_ylim(bottom=0)

    # TX gain labels: one per point, or one range label for points too close together
    if "tx_gain" in steps and steps["tx_gain"].notna().any():
        d = pd.DataFrame({"x": steps["added_kw"], "y": rf_norm, "g": steps["tx_gain"]})
        d = d.dropna().sort_values("x")
        groups, cur = [], []
        for r in d.itertuples():
            if cur and r.x - cur[-1].x > 0.035 * xmax:
                groups.append(cur)
                cur = []
            cur.append(r)
        groups.append(cur)
        for grp in groups:
            lo, hi = min(r.g for r in grp), max(r.g for r in grp)
            text = f"{lo:g} dB" if lo == hi else f"{lo:g}–{hi:g} dB"
            r = grp[0]
            a.annotate(text, (r.x, r.y), xytext=(-7, 3), textcoords="offset points",
                       ha="right", va="bottom", fontsize=7.5, color=INK_MUTED)
        a.text(0.97, 0.03, "labels: TX gain", transform=a.transAxes, ha="right",
               fontsize=7.5, color=INK_MUTED)

    if compression:
        c = axes[2]
        g = steps["tx_gain"]
        gx = np.linspace(g.min() - 1, g.max() + 1, 10)
        c.plot(gx, comp["rf_ref"] + (gx - comp["g_ref"]), color=INK_MUTED, lw=1, ls="--",
               zorder=1)
        c.annotate("slope 1 (linear)", (comp["g_ref"] + 4, comp["rf_ref"] + 4),
                   xytext=(-8, 4), textcoords="offset points", ha="right",
                   fontsize=7.5, color=INK_MUTED)
        if color_by_time:
            c.plot(g, steps["rf_dbm"], color=GRID, lw=1, zorder=1)
        c.errorbar(g, steps["rf_dbm"], yerr=steps["rf_dbm_err"], fmt="none",
                   ecolor=INK_MUTED, elinewidth=0.6, capsize=0, zorder=2)
        c.scatter(g, steps["rf_dbm"], s=40, edgecolors="white", linewidths=1, zorder=3,
                  **colors)
        if comp["g_1db"] is not None:
            g1 = comp["g_1db"]
            r1 = comp["rf_ref"] + (g1 - comp["g_ref"]) - comp["db"]
            c.plot([g1, g1], [r1 - 2.5, r1 + 2.5], color=INK, lw=0.8, zorder=2)
            c.annotate(f"1 dB compression\nat {g1:.1f} dB TX gain", (g1, r1 - 2.5),
                       xytext=(6, -2), textcoords="offset points", va="top",
                       fontsize=8, color=INK, linespacing=1.3)
        _style(c)
        c.set_xlim(gx[0], gx[-1])
        from matplotlib.ticker import MultipleLocator
        c.xaxis.set_major_locator(MultipleLocator(5))
        c.xaxis.set_minor_locator(MultipleLocator(1))
        ylo = min(steps["rf_dbm"].min(), comp["rf_ref"]) - 3
        c.set_ylim(ylo, steps["rf_dbm"].max() + 3)
        c.set_xlabel("TX gain (dB)", color=INK_MUTED, fontsize=9)
        c.set_ylabel("RF at apex monitor (dBm)", color=INK_MUTED, fontsize=9)
        c.set_title("c  Compression", loc="left", fontsize=10, color=INK)

    a.set_ylabel("RF at apex monitor (top step = 1)", color=INK_MUTED, fontsize=9)
    a.set_ylim(0, 1.15)
    b.set_ylabel("Efficiency (top step = 1)", color=INK_MUTED, fontsize=9)
    b.set_ylim(0, max(1.15, (f["slope_rel"] * 1.1) if f is not None else 0))
    a.set_title("a  RF output", loc="left", fontsize=10, color=INK)
    b.set_title("b  Efficiency, RF out / (P − P_idle)", loc="left", fontsize=10, color=INK)
    if color_by_time:
        cb = fig.colorbar(sc, ax=list(axes), pad=0.012, aspect=30)
        cb.set_label("Minutes since first step", color=INK_MUTED, fontsize=8.5)
        cb.outline.set_visible(False)
        cb.ax.tick_params(colors=INK_MUTED, labelsize=8)
    else:
        fig.tight_layout()
    return fig


def ramp_check_mpl(root, steps, width=12):
    """RF power and power clamp against time, with the detected steps shaded:
    to check that the step detection picked the right plateaus."""
    import matplotlib.dates as mdates
    import matplotlib.pyplot as plt

    t0, t1 = (pd.Timestamp(t) for t in steps.attrs["window"])
    rf = load_ancillary(root, "rfpower", t0, t1)
    pc = load_ancillary(root, "powerclamp", t0, t1)
    naive = lambda s: s.dt.tz_convert("UTC").dt.tz_localize(None)
    fig, (a, b) = plt.subplots(2, 1, sharex=True, figsize=(width, 3.6),
                               gridspec_kw={"hspace": 0.1})
    a.plot(naive(rf["time"]), rf["rf_power_dbm"], color=INK, lw=0.6)
    b.plot(naive(pc["time"]), pc["power_kw"], color=INK, lw=0.8, marker=".", ms=2.5)
    for ax in (a, b):
        for s, e in zip(steps["t_start"], steps["t_end"]):
            ax.axvspan(s.tz_localize(None) - pd.Timedelta(2500, unit="ms"),
                       e.tz_localize(None) + pd.Timedelta(2500, unit="ms"),
                       color=SEQ[2], alpha=0.35, lw=0)
        _style(ax)
    b.axhline(steps.attrs["p_idle_kw"], color=INK_MUTED, lw=0.8, ls="--")
    a.set_ylabel("RF (dBm)", color=INK_MUTED, fontsize=9)
    b.set_ylabel("Power (kW)", color=INK_MUTED, fontsize=9)
    b.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
    b.set_xlabel(f"Time (UTC); {len(steps)} steps shaded, dashed = idle power",
                 color=INK_MUTED, fontsize=9)
    return fig


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("root", nargs="?", help="ancillary directory (from ingest_ancillary.py)")
    ap.add_argument("date", nargs="?", help="e.g. 2026-10-17")
    ap.add_argument("--from-csv", type=Path, help="plot a steps table saved earlier with --csv "
                    "(no ancillary data needed)")
    ap.add_argument("--fit-min", type=float, help="fit only steps at least this many kW above idle")
    ap.add_argument("--start", help="start of the ramp, e.g. 13:30 (UTC)")
    ap.add_argument("--end", help="end of the ramp, e.g. 14:20 (UTC)")
    ap.add_argument("--catalog", help="catalog directory, to label steps with tx_gain")
    ap.add_argument("-o", "--out", type=Path, help="efficiency figure (.pdf, .png)")
    ap.add_argument("--check", type=Path, help="also save the time-series check figure")
    ap.add_argument("--csv", type=Path, help="also save the steps table")
    args = ap.parse_args(argv)

    if args.from_csv:
        steps = read_steps(args.from_csv)
    elif args.root and args.date:
        steps = ramp_steps(args.root, args.date, args.start, args.end, args.catalog)
    else:
        ap.error("give ancillary directory and date, or --from-csv")
    with pd.option_context("display.width", 160, "display.max_columns", 20):
        cols = ["n", "tx_gain", "power_kw", "added_kw", "rf_dbm", "eff_rel"]
        table = steps[cols].round(3)
        table.insert(0, "t_start", steps["t_start"].dt.strftime("%H:%M:%S"))
        print(table.to_string(index=False))
    floor = steps.attrs.get("rf_floor_dbm")
    print(f"idle power {steps.attrs['p_idle_kw']:.3f} kW"
          + (f", detector floor {floor:.2f} dBm" if floor is not None else ""))
    if len(steps) >= 2:
        f = fit_overhead(steps, args.fit_min)
        print(f"line fit ({f['n']} steps): RF = 0 at {f['x0_kw']:.3f} ± {f['x0_err']:.3f} kW "
              f"above idle = {f['overhead_kw']:.3f} kW total; marginal efficiency "
              f"{f['slope_rel']:.3f} ± {f['slope_rel_err']:.3f} × efficiency at top step; "
              f"rms residual {f['rms_resid']:.4f} (top step = 1)")
    comp = compression_point(steps)
    if comp is not None:
        print("compression vs slope 1 from", f"{comp['g_ref']:g} dB:",
              ", ".join(f"{g:g} dB: {v:.2f}" for g, v in comp["compression"].items()))
        if comp["g_1db"] is not None:
            print(f"1 dB compression at {comp['g_1db']:.1f} dB TX gain")
    if args.csv:
        steps.to_csv(args.csv, index=False)
    if args.check and not args.from_csv:
        ramp_check_mpl(args.root, steps).savefig(args.check, dpi=200, bbox_inches="tight")
        print(f"written {args.check}")
    if args.out:
        efficiency_mpl(steps, fit_min_kw=args.fit_min).savefig(args.out, dpi=200,
                                                                bbox_inches="tight")
        print(f"written {args.out}")
    if not (args.out or args.check):
        import matplotlib.pyplot as plt
        efficiency_mpl(steps, fit_min_kw=args.fit_min)
        plt.show()


if __name__ == "__main__":
    main()
