#!/usr/bin/env python3
"""Figures for the post "How wide is an FM signal?" (content/posts/tait-bandwidth.md).

Everything here is synthetic: complex-baseband FM made with numpy, no radio involved.
The 99% occupied bandwidths printed on the figures are computed from these signals.

Run:  python3 make_figures.py      (needs numpy and matplotlib; writes PNGs beside itself)
"""
import os

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

HERE = os.path.dirname(os.path.abspath(__file__))
FS = 96_000  # sample rate, Hz
NFFT = 1440  # 66.7 Hz bins; with a Hann window the noise bandwidth is 100 Hz
RNG_SEED = 20261204  # fixed only so the files do not change between runs

# Tait's total IF bandwidth at -3 dB, kHz (TM8100/TM8200 Service Manual, Table 3.1).
RX_FILTER = {"Narrow": 7.8, "Mid": 12.0, "Wide": 12.6}

# name: (channel spacing kHz, deviation limit kHz, colour). Okabe-Ito colours.
WIDTHS = {
    "Narrow": (12.5, 2.5, "#0072B2"),
    "Mid": (20.0, 4.0, "#E69F00"),
    "Wide": (25.0, 5.0, "#009E73"),
}
TOP_AUDIO_KHZ = 3.0
INK = "#1a1a1a"
GREY = "#8a8a8a"

plt.rcParams.update({
    "font.size": 13,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.edgecolor": INK,
    "axes.labelcolor": INK,
    "text.color": INK,
    "xtick.color": INK,
    "ytick.color": INK,
    "figure.facecolor": "white",
    "axes.facecolor": "white",
    "savefig.facecolor": "white",
})


def carson_khz(dev_khz, top_khz=TOP_AUDIO_KHZ):
    return 2 * (dev_khz + top_khz)


# ---------------------------------------------------------------- audio

def band_filter(x, gain_of_f):
    """Filter a real signal by an arbitrary gain curve, in the frequency domain."""
    spec = np.fft.rfft(x)
    f = np.fft.rfftfreq(len(x), 1 / FS)
    return np.fft.irfft(spec * gain_of_f(f), len(x))


def lowpass_3k(f):
    """Flat to 3 kHz, raised-cosine roll-off to nothing at 3.4 kHz."""
    g = np.ones_like(f)
    edge = (f > 3000) & (f < 3400)
    g[edge] = 0.5 * (1 + np.cos(np.pi * (f[edge] - 3000) / 400))
    g[f >= 3400] = 0
    return g


def speech_shape(f):
    """Long-term speech spectrum, roughly: 300 Hz to 3 kHz, falling 9 dB/octave above 500 Hz."""
    g = np.zeros_like(f)
    band = (f >= 300) & (f <= 3000)
    g[band] = np.where(f[band] < 500, 1.0, (f[band] / 500.0) ** -1.5)
    return g


def voice_like(seconds, rng, pre_emphasis=True, drive=0.35):
    """Speech-shaped noise through a voice radio's transmit chain.

    Pre-emphasis (6 dB/octave), a hard limiter at full scale, then the 3 kHz low-pass.
    Returns audio where +/-1.0 is the deviation limit. `drive` is the rms level into the
    limiter as a share of full scale: 0.35 means only the loudest peaks are clipped.
    """
    n = int(seconds * FS)
    x = band_filter(rng.standard_normal(n), speech_shape)
    if pre_emphasis:
        x = band_filter(x, lambda f: f / 1000.0)
    x *= drive / np.sqrt(np.mean(x ** 2))
    x = np.clip(x, -1.0, 1.0)
    return band_filter(x, lowpass_3k)


def tone(seconds, hz):
    t = np.arange(int(seconds * FS)) / FS
    return np.cos(2 * np.pi * hz * t)


def log_sweep(seconds, f0, f1):
    t = np.arange(int(seconds * FS)) / FS
    k = np.log(f1 / f0)
    phase = 2 * np.pi * f0 * seconds / k * (np.exp(t / seconds * k) - 1)
    return np.cos(phase)


def fsk_9600(seconds, rng, bt=0.5):
    """Random 9600 baud two-level data, Gaussian filtered. +/-1.0 is the peak deviation."""
    sps = FS // 9600
    bits = rng.integers(0, 2, int(seconds * 9600)) * 2.0 - 1.0
    x = np.repeat(bits, sps)
    sigma = np.sqrt(np.log(2)) / (2 * np.pi * bt) * sps
    taps = np.exp(-0.5 * (np.arange(-4 * sps, 4 * sps + 1) / sigma) ** 2)
    return np.convolve(x, taps / taps.sum(), mode="same")


def fm(audio, dev_khz):
    """Frequency-modulate a carrier at 0 Hz. Unit amplitude, so total power is 1."""
    return np.exp(2j * np.pi * np.cumsum(audio) * dev_khz * 1000 / FS)


# ---------------------------------------------------------------- measurement

def spectrum(iq):
    """Averaged spectrum. Returns (offset in kHz, power per 100 Hz slice relative to the total)."""
    win = np.hanning(NFFT)
    hop = NFFT // 2
    count = (len(iq) - NFFT) // hop + 1
    acc = np.zeros(NFFT)
    for i in range(count):
        seg = iq[i * hop:i * hop + NFFT] * win
        acc += np.abs(np.fft.fft(seg)) ** 2
    p = np.fft.fftshift(acc / count) / win.sum() ** 2
    f = np.fft.fftshift(np.fft.fftfreq(NFFT, 1 / FS)) / 1000
    return f, p


def occupied_bandwidth(f, p, share=0.99):
    """Lower edge, upper edge and width (kHz) of the band holding `share` of the power.

    The ITU definition: 0.5% of the total mean power lies below the lower limit and 0.5%
    above the upper one.
    """
    c = np.cumsum(p) / p.sum()
    tail = (1 - share) / 2
    lo = f[np.searchsorted(c, tail)]
    hi = f[np.searchsorted(c, 1 - tail)]
    return lo, hi, hi - lo


def db(p):
    return 10 * np.log10(np.maximum(p, 1e-12))


# ---------------------------------------------------------------- drawing

def mark_channel(ax, spacing, colour, label=True):
    ax.axvspan(-spacing / 2, spacing / 2, color=colour, alpha=0.10, lw=0)
    for edge in (-spacing / 2, spacing / 2):
        ax.axvline(edge, color=colour, lw=1.2, alpha=0.6)
    if label:
        ax.text(spacing / 2 - 0.3, -77, f"channel, {spacing:g} kHz", color=colour, ha="right", va="bottom", fontsize=11,
                bbox=dict(facecolor="white", edgecolor="none", pad=1.5, alpha=0.85))


def mark_carson(ax, width_khz, y=-22):
    for edge in (-width_khz / 2, width_khz / 2):
        ax.axvline(edge, color=INK, lw=1.3, ls=(0, (5, 3)))
    ax.annotate("", xy=(-width_khz / 2, y), xytext=(width_khz / 2, y),
                arrowprops=dict(arrowstyle="<->", color=INK, lw=1.2))
    ax.text(0, y + 1, f"Carson, {width_khz:g} kHz", ha="center", va="bottom", fontsize=11,
            bbox=dict(facecolor="white", edgecolor="none", pad=1.5, alpha=0.85))


def mark_obw(ax, lo, hi, colour, y=-36, label="99% of the power", digits=1):
    ax.annotate("", xy=(lo, y), xytext=(hi, y), arrowprops=dict(arrowstyle="<->", color=colour, lw=2.2))
    ax.text((lo + hi) / 2, y - 1.5, f"{label}, {hi - lo:.{digits}f} kHz", ha="center", va="top", fontsize=11,
            color=colour, fontweight="bold",
            bbox=dict(facecolor="white", edgecolor="none", pad=1.5, alpha=0.85))


def style_spectrum_axis(ax, xlim=18):
    ax.set_xlim(-xlim, xlim)
    ax.set_ylim(-80, 2)
    ax.set_yticks([-80, -60, -40, -20, 0])
    ax.grid(axis="y", color="#e4e4e4", lw=1)
    ax.set_axisbelow(True)


def figure_spectra(rng):
    """(a) Tone and voice-like audio at the three widths, with all three bandwidths marked."""
    fig, axes = plt.subplots(3, 2, figsize=(12, 11.2), sharex=True, sharey=True)
    results = {}
    for row, (name, (spacing, dev, colour)) in enumerate(WIDTHS.items()):
        signals = (
            ("3 kHz tone at full deviation", fm(tone(20, 3000), dev)),
            ("voice-like audio through the voice path", fm(voice_like(40, rng), dev)),
        )
        for col, (what, iq) in enumerate(signals):
            ax = axes[row, col]
            f, p = spectrum(iq)
            lo, hi, obw = occupied_bandwidth(f, p)
            results[(name, col)] = obw
            mark_channel(ax, spacing, colour)
            ax.fill_between(f, db(p), -80, color=colour, alpha=0.35, lw=0)
            ax.plot(f, db(p), color=colour, lw=1.6)
            mark_carson(ax, carson_khz(dev))
            # A tone's power sits in lines 3 kHz apart, so its 99% width moves in whole lines.
            mark_obw(ax, lo, hi, colour, digits=1 if col else 0)
            style_spectrum_axis(ax)
            ax.set_title(f"{name}, ±{dev:g} kHz: {what}", fontsize=13, loc="left", color=INK)
            if col == 0:
                ax.set_ylabel("power in 100 Hz, dB\nrelative to the whole signal")
            if row == 2:
                ax.set_xlabel("offset from the carrier, kHz")
    fig.suptitle("Channel spacing, Carson's necessary bandwidth and the measured 99% bandwidth",
                 x=0.012, ha="left", fontsize=15)
    fig.text(0.012, 0.008, "Synthetic FM signals. Voice-like audio is speech-shaped noise, pre-emphasised, "
             "limited and low-passed at 3 kHz.", color=GREY, fontsize=10.5)
    fig.tight_layout(rect=(0, 0.02, 1, 0.97))
    fig.savefig(os.path.join(HERE, "spectra.png"), dpi=120)
    plt.close(fig)
    return results


def figure_waterfall(rng):
    """(b) The same signals over time, as an SDR waterfall shows them."""
    fig, axes = plt.subplots(1, 3, figsize=(12, 7.4), sharey=True)
    nfft, hop = 2048, 1024
    win = np.hanning(nfft)
    image = None
    for ax, (name, (spacing, dev, colour)) in zip(axes, WIDTHS.items()):
        audio = np.concatenate([
            np.zeros(2 * FS),             # 0 to 2 s: carrier only
            log_sweep(6, 300, 3000),      # 2 to 8 s: tone sweep at full deviation
            voice_like(6, rng),           # 8 to 14 s: voice-like audio
        ])
        iq = fm(audio, dev)
        rows = (len(iq) - nfft) // hop + 1
        frames = np.stack([iq[i * hop:i * hop + nfft] * win for i in range(rows)])
        p = np.abs(np.fft.fftshift(np.fft.fft(frames, axis=1), axes=1)) ** 2 / win.sum() ** 2
        f = np.fft.fftshift(np.fft.fftfreq(nfft, 1 / FS)) / 1000
        keep = np.abs(f) <= 16
        image = ax.imshow(db(p[:, keep]), aspect="auto", cmap="viridis", vmin=-70, vmax=0,
                          extent=(f[keep][0], f[keep][-1], len(iq) / FS, 0), interpolation="bilinear")
        for edge in (-spacing / 2, spacing / 2):
            ax.axvline(edge, color="white", lw=1.6)
        for edge in (-carson_khz(dev) / 2, carson_khz(dev) / 2):
            ax.axvline(edge, color="white", lw=1.3, ls=(0, (5, 4)))
        ax.set_title(f"{name}: ±{dev:g} kHz in {spacing:g} kHz", color=colour, fontweight="bold", fontsize=13)
        ax.set_xlabel("offset from the carrier, kHz")
        ax.set_xticks([-15, -10, -5, 0, 5, 10, 15])
        ax.set_xticklabels(["", "-10", "", "0", "", "10", ""])
        for spine in ax.spines.values():
            spine.set_visible(False)
    axes[0].set_ylabel("time, s")
    for y, text in ((1.0, "carrier only"), (5.0, "tone sweep,\n300 Hz to 3 kHz,\nfull deviation"), (11.0, "voice-like\naudio")):
        axes[2].text(17.5, y, text, color=INK, fontsize=11, va="center", ha="left", clip_on=False).set_in_layout(False)
    fig.suptitle("The same signals on a waterfall. Solid lines: channel edges. Dashed: Carson's bandwidth.",
                 x=0.012, ha="left", fontsize=15)
    fig.tight_layout(rect=(0, 0.13, 0.875, 0.95))
    bar = fig.add_axes((0.25, 0.085, 0.40, 0.02))
    fig.colorbar(image, cax=bar, orientation="horizontal")
    bar.set_xlabel("power in 70 Hz, dB relative to the whole signal", fontsize=11)
    bar.tick_params(labelsize=10)
    fig.savefig(os.path.join(HERE, "waterfall.png"), dpi=120)
    plt.close(fig)


def figure_flat_path(rng):
    """(c) What pre-emphasis does, and what an unpoliced flat input can do."""
    fig, axes = plt.subplots(1, 2, figsize=(12, 5.6), sharey=True)
    results = {}

    # Left: wide voice, with and without pre-emphasis, same limiter, filter and drive.
    spacing, dev, colour = WIDTHS["Wide"]
    ax = axes[0]
    seed = rng.integers(1 << 30)
    flat = fm(voice_like(40, np.random.default_rng(seed), pre_emphasis=False), dev)
    emph = fm(voice_like(40, np.random.default_rng(seed), pre_emphasis=True), dev)
    mark_channel(ax, spacing, colour)
    f, p_flat = spectrum(flat)
    f, p_emph = spectrum(emph)
    ax.plot(f, db(p_flat), color=GREY, lw=1.8)
    ax.plot(f, db(p_emph), color=colour, lw=1.8)
    lo, hi, results["emph"] = occupied_bandwidth(f, p_emph)
    mark_obw(ax, lo, hi, colour, y=-36, label="pre-emphasised, 99%")
    lo, hi, results["flat"] = occupied_bandwidth(f, p_flat)
    mark_obw(ax, lo, hi, "#5c5c5c", y=-50, label="no pre-emphasis, 99%")
    mark_carson(ax, carson_khz(dev), y=-18)
    style_spectrum_axis(ax)
    ax.set_title("Wide voice: with and without pre-emphasis", fontsize=13, loc="left")
    ax.set_ylabel("power in 100 Hz, dB\nrelative to the whole signal")
    ax.set_xlabel("offset from the carrier, kHz")

    # Right: 9600 baud data into a flat input at 3 kHz deviation, on the narrow grid.
    spacing, dev, colour = WIDTHS["Narrow"]
    ax = axes[1]
    mark_channel(ax, spacing, colour)
    f, p_voice = spectrum(fm(voice_like(40, rng), dev))
    f, p_data = spectrum(fm(fsk_9600(40, rng), 3.0))
    ax.fill_between(f, db(p_voice), -80, color=colour, alpha=0.30, lw=0)
    ax.plot(f, db(p_voice), color=colour, lw=1.6)
    ax.plot(f, db(p_data), color=INK, lw=1.8)
    lo, hi, results["data"] = occupied_bandwidth(f, p_data)
    mark_obw(ax, lo, hi, INK, y=-36, label="9600 baud data, 99%")
    lo, hi, results["narrow_voice"] = occupied_bandwidth(f, p_voice)
    mark_obw(ax, lo, hi, colour, y=-50, label="narrow voice, 99%")
    mark_carson(ax, carson_khz(dev), y=-18)
    style_spectrum_axis(ax)
    ax.set_title("Narrow channel: voice, and 9600 baud on a flat input", fontsize=13, loc="left")
    ax.set_xlabel("offset from the carrier, kHz")

    fig.suptitle("What the voice path adds, and what the flat path leaves to you", x=0.012, ha="left", fontsize=15)
    fig.text(0.012, 0.012, "Synthetic FM signals. Data: random bits, Gaussian filtered (BT 0.5), ±3 kHz deviation, "
             "no limiter or filter after it.", color=GREY, fontsize=10.5)
    fig.tight_layout(rect=(0, 0.04, 1, 0.94))
    fig.savefig(os.path.join(HERE, "flat-path.png"), dpi=120)
    plt.close(fig)
    return results


# ---------------------------------------------------------------- neighbours

# title, signal width, raster kHz, receive filter of
NEIGHBOUR_CASES = (
    ("Narrow signals on a 12.5 kHz raster", "Narrow", 12.5, "Narrow"),
    ("Mid signals on a 20 kHz raster", "Mid", 20.0, "Mid"),
    ("Wide signals on a 25 kHz raster", "Wide", 25.0, "Wide"),
    ("Wide signals on a 12.5 kHz raster, heard by a narrow receiver", "Wide", 12.5, "Narrow"),
)


def shift(iq, khz):
    t = np.arange(len(iq)) / FS
    return iq * np.exp(2j * np.pi * khz * 1000 * t)


def figure_neighbours(rng):
    """(d) A wanted signal with a neighbour either side: the gaps, and where the receiver cuts."""
    fig, axes = plt.subplots(4, 1, figsize=(12, 14.4), sharex=True)
    results = {}
    for ax, (title, width, raster, rx) in zip(axes, NEIGHBOUR_CASES):
        _, dev, colour = WIDTHS[width]
        filt = RX_FILTER[rx]
        for k in range(-2, 3):
            ax.axvline((k + 0.5) * raster, color=GREY, lw=1, ls=(0, (2, 3)))
        ax.axvspan(-filt / 2, filt / 2, facecolor="none", edgecolor=INK, lw=1.6)
        ax.text(0, -1, f"receive filter\n{filt:g} kHz at -3 dB", ha="center", va="top", fontsize=11,
                bbox=dict(facecolor="white", edgecolor="none", pad=1.5, alpha=0.85))
        leak = None
        for k in (-1, 1, 0):
            iq = shift(fm(voice_like(40, rng), dev), k * raster)
            f, p = spectrum(iq)
            wanted = k == 0
            ax.fill_between(f, db(p), -80, color=colour if wanted else GREY, alpha=0.40 if wanted else 0.25, lw=0)
            ax.plot(f, db(p), color=colour if wanted else "#5c5c5c", lw=1.8 if wanted else 1.4)
            if wanted:
                lo, hi, obw = occupied_bandwidth(f, p)
            elif k == 1:
                # Share of this neighbour's power between the receive filter's -3 dB points.
                leak = 10 * np.log10(p[np.abs(f) <= filt / 2].sum() / p.sum())
        gap = raster - obw
        carson_gap = raster - carson_khz(dev)
        mark_obw(ax, lo, hi, colour, y=-40, label="99%")
        ax.text(-raster, -1, "neighbour", ha="center", va="top", fontsize=11, color="#5c5c5c")
        ax.text(raster, -1, "neighbour", ha="center", va="top", fontsize=11, color="#5c5c5c")
        leak_text = f"{leak:.0f} dB" if leak > -80 else "below -80 dB"
        between = (f"{gap:.1f} kHz clear between the 99% bands" if gap > 0
                   else f"the 99% bands overlap by {-gap:.1f} kHz")
        by_carson = (f"{carson_gap:g} kHz by Carson" if carson_gap > 0 else f"Carson overlaps by {-carson_gap:g} kHz")
        ax.text(0, 1.03, f"{between} ({by_carson}). Neighbour's power inside the receive filter: {leak_text}.",
                transform=ax.transAxes, ha="left", va="bottom", fontsize=11.5)
        results[title] = (obw, gap, carson_gap, leak)
        ax.set_xlim(-40, 40)
        ax.set_ylim(-80, 2)
        ax.set_yticks([-80, -60, -40, -20, 0])
        ax.grid(axis="y", color="#e4e4e4", lw=1)
        ax.set_axisbelow(True)
        ax.set_title(f"{title} (\u00b1{dev:g} kHz deviation)", fontsize=13, loc="left", color=colour, fontweight="bold", pad=26)
        ax.set_ylabel("power in 100 Hz, dB\nrelative to one signal")
    axes[-1].set_xlabel("offset from the wanted carrier, kHz")
    fig.suptitle("Neighbours one channel either side, and where the receiver's filter cuts", x=0.012, ha="left", fontsize=15)
    fig.text(0.012, 0.006, "Synthetic voice-like FM, three equal signals. Dotted lines: channel edges. Box: Tait's receive filter "
             "width, drawn as a brick wall for the power figure.", color=GREY, fontsize=10.5)
    fig.tight_layout(rect=(0, 0.018, 1, 0.975))
    fig.savefig(os.path.join(HERE, "neighbours.png"), dpi=120)
    plt.close(fig)
    return results


def figure_neighbours_waterfall(rng):
    """(d) The same four cases over time: three stations coming and going."""
    fig, axes = plt.subplots(2, 2, figsize=(12, 10.4), sharex=True, sharey=True)
    nfft, hop = 2048, 1024
    win = np.hanning(nfft)
    total = 12
    talk = {-1: (0, 8), 0: (2, 12), 1: (5, 10)}  # station: (start, stop) in seconds
    image = None
    for ax, (title, width, raster, rx) in zip(axes.ravel(), NEIGHBOUR_CASES):
        _, dev, colour = WIDTHS[width]
        filt = RX_FILTER[rx]
        iq = np.zeros(total * FS, dtype=complex)
        for k, (start, stop) in talk.items():
            burst = shift(fm(voice_like(stop - start, rng), dev), k * raster)
            iq[start * FS:stop * FS] += burst
        rows = (len(iq) - nfft) // hop + 1
        frames = np.stack([iq[i * hop:i * hop + nfft] * win for i in range(rows)])
        p = np.abs(np.fft.fftshift(np.fft.fft(frames, axis=1), axes=1)) ** 2 / win.sum() ** 2
        f = np.fft.fftshift(np.fft.fftfreq(nfft, 1 / FS)) / 1000
        keep = np.abs(f) <= 40
        image = ax.imshow(db(p[:, keep]), aspect="auto", cmap="viridis", vmin=-70, vmax=-10,
                          extent=(f[keep][0], f[keep][-1], total, 0), interpolation="bilinear")
        for k in range(-2, 3):
            ax.axvline((k + 0.5) * raster, color="white", lw=1.3)
        for edge in (-filt / 2, filt / 2):
            ax.axvline(edge, color="white", lw=1.4, ls=(0, (5, 4)))
        ax.set_title(f"{title.replace(', heard by a narrow receiver', '')}", color=colour, fontweight="bold", fontsize=13, loc="left")
        for spine in ax.spines.values():
            spine.set_visible(False)
    for ax in axes[1]:
        ax.set_xlabel("offset from the wanted carrier, kHz")
    for ax in axes[:, 0]:
        ax.set_ylabel("time, s")
    fig.suptitle("Three stations coming and going. Solid lines: channel edges. Dashed: the receive filter.",
                 x=0.012, ha="left", fontsize=15)
    fig.tight_layout(rect=(0, 0.10, 1, 0.96))
    bar = fig.add_axes((0.30, 0.055, 0.40, 0.016))
    fig.colorbar(image, cax=bar, orientation="horizontal")
    bar.set_xlabel("power in 70 Hz, dB relative to one signal", fontsize=11)
    bar.tick_params(labelsize=10)
    fig.savefig(os.path.join(HERE, "neighbours-waterfall.png"), dpi=120)
    plt.close(fig)


def main():
    rng = np.random.default_rng(RNG_SEED)
    spectra = figure_spectra(rng)
    figure_waterfall(rng)
    flat = figure_flat_path(rng)
    neighbours = figure_neighbours(rng)
    figure_neighbours_waterfall(rng)
    print("99% occupied bandwidth, kHz")
    for name, (spacing, dev, _) in WIDTHS.items():
        print(f"  {name:6s} spacing {spacing:4.1f}  Carson {carson_khz(dev):4.1f}  "
              f"3 kHz tone {spectra[(name, 0)]:5.2f}  voice-like {spectra[(name, 1)]:5.2f}")
    print(f"  wide voice, pre-emphasised {flat['emph']:.2f}; without pre-emphasis {flat['flat']:.2f}")
    print(f"  narrow voice {flat['narrow_voice']:.2f}; 9600 baud at 3 kHz deviation {flat['data']:.2f}")
    for title, (obw, gap, carson_gap, leak) in neighbours.items():
        print(f"  {title}: 99% {obw:.2f}, gap {gap:.2f}, by Carson {carson_gap:g}, neighbour in filter {leak:.1f} dB")


if __name__ == "__main__":
    main()
