무선 LAN 구조 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 무선 LAN 구조 문서의 그림을 만든다: 69_wireless-lan_fig1.svg(2.4 GHz ISM 대역의 와이파이 채널 1~11과 블루투스 79채널),
# 69_wireless-lan_fig2.svg(인프라 모드의 BSS 두 개와 애드혹 모드).
# 와이파이 채널 k의 가운데는 2412 + 5(k-1) MHz, 폭은 약 22 MHz. 서로 안 겹치는 채널이 1, 6, 11뿐임을 확인한다.
# 실행: ~/.venvs/vault-plots/bin/python -I 69_wireless-lan_plot.py  (matplotlib, numpy 필요)
PREFIX = "69_wireless-lan"
import os

import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import font_manager
from matplotlib.patches import FancyArrowPatch, Rectangle, Circle, Polygon

HERE = os.path.dirname(os.path.abspath(__file__))
INK = "#888888"                                         # 밝은 테마와 어두운 테마 모두에서 보이는 회색
C = ["#3b82c4", "#d9622b", "#3a9a5b", "#9b59b6", "#c49a1b"]
BLUE, ORANGE, GREEN, PURPLE, GOLD = C
_fonts = {f.name for f in font_manager.fontManager.ttflist}
FONT = next((n for n in ["Apple SD Gothic Neo", "NanumGothic", "Noto Sans CJK KR"] if n in _fonts), "DejaVu Sans")
plt.rcParams.update({
    "font.family": FONT, "mathtext.fontset": "dejavusans",
    "font.size": 10, "axes.unicode_minus": False, "svg.fonttype": "path", "svg.hashsalt": PREFIX,
    "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
    "text.color": INK, "legend.frameon": False,
    "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
    "axes.spines.top": False, "axes.spines.right": False,
})


def save(fig, k):
    fig.savefig(os.path.join(HERE, f"{PREFIX}_fig{k}.svg"), bbox_inches="tight", metadata={"Date": None})
    if os.environ.get("PREVIEW_DIR"):                   # 눈으로 확인할 PNG (볼트 밖 폴더에만)
        fig.savefig(os.path.join(os.environ["PREVIEW_DIR"], f"{PREFIX}_fig{k}.png"), bbox_inches="tight", dpi=110,
                    facecolor="white")
    plt.close(fig)


def arrow(ax, p, q_, color=INK, lw=1.2, style="-|>", ls="-", ms=10):
    ax.add_patch(FancyArrowPatch(p, q_, arrowstyle=style, mutation_scale=ms, color=color, lw=lw, ls=ls,
                                 shrinkA=0, shrinkB=0))


def steps(ax, vals, y0, color, scale=0.35, lw=1.8):
    """칩(또는 비트) 값 목록을 계단 파형으로 그린다. 칸 하나의 폭은 1."""
    xs, ys = [], []
    for i, v in enumerate(vals):
        xs += [i, i + 1]
        ys += [y0 + v * scale, y0 + v * scale]
    ax.plot(xs, ys, color=color, lw=lw, solid_joinstyle="miter")
    ax.plot([0, len(vals)], [y0, y0], color=INK, lw=0.6, ls=":")


def wifi_center(k):
    return 2412 + 5 * (k - 1)                  # 채널 k의 가운데 주파수(MHz)


def overlap(i, j, width=22):
    return abs(wifi_center(i) - wifi_center(j)) < width


def fig1():
    fig, (ax, bx) = plt.subplots(2, 1, figsize=(7.6, 3.8), sharex=True, gridspec_kw={"height_ratios": [3, 1]})
    f = np.linspace(-11, 11, 200)
    for k in range(1, 12):
        c = wifi_center(k)
        y = np.cos(f / 11 * np.pi / 2) ** 1.0
        main = k in (1, 6, 11)
        col = [BLUE, ORANGE, GREEN][(1, 6, 11).index(k)] if main else INK
        ax.plot(c + f, y, color=col, lw=2.0 if main else 0.9, ls="-" if main else ":")
        ax.text(c, (1.04 if main else 0.62 + 0.08 * (k % 2)), str(k), ha="center", va="bottom",
                fontsize=10 if main else 9.5, color=col)
    ax.annotate("", xy=(2401, -0.12), xytext=(2423, -0.12),
                arrowprops=dict(arrowstyle="<->", color=BLUE, lw=1))
    ax.text(2412, -0.2, "폭 22 MHz", ha="center", va="top", fontsize=9.5, color=BLUE)
    ax.annotate("", xy=(2412, 1.32), xytext=(2417, 1.32), arrowprops=dict(arrowstyle="<->", color=INK, lw=1))
    ax.text(2419, 1.32, "가운데끼리 5 MHz", va="center", fontsize=9.5)
    ax.axvspan(2400, 2483.5, color=GOLD, alpha=0.08, lw=0)
    ax.set_ylim(-0.35, 1.45); ax.set_yticks([])
    ax.spines["left"].set_visible(False)
    ax.set_title("와이파이(802.11) 채널 1~11", fontsize=10.5, color=INK, loc="left")
    for ch in range(79):
        fc = 2402 + ch
        bx.add_patch(Rectangle((fc - 0.45, 0), 0.9, 1, color=PURPLE, alpha=0.7, lw=0))
    bx.set_ylim(0, 1.6); bx.set_yticks([])
    bx.spines["left"].set_visible(False)
    bx.set_title("블루투스 채널 79개(각 1 MHz)", fontsize=10.5, color=INK, loc="left")
    bx.set_xlim(2396, 2488)
    bx.set_xticks([2400, 2412, 2437, 2462, 2483.5])
    bx.set_xticklabels(["2400", "2412", "2437", "2462", "2483.5"], fontsize=9.5)
    bx.set_xlabel("주파수(MHz)", fontsize=10)
    fig.tight_layout()
    save(fig, 1)


def host(ax, x, y, label=None, color=BLUE):
    ax.add_patch(Rectangle((x - 0.13, y - 0.1), 0.26, 0.2, facecolor=color, alpha=1.0, ec=INK, lw=0.8, zorder=3))
    if label:
        ax.text(x, y - 0.17, label, ha="center", va="top", fontsize=9.5)


def ap(ax, x, y, label):
    ax.add_patch(Polygon([(x - 0.17, y - 0.12), (x + 0.17, y - 0.12), (x, y + 0.18)], closed=True,
                         facecolor=ORANGE, alpha=0.75, ec=INK, lw=0.8, zorder=3))
    ax.text(x + 0.22, y + 0.02, label, ha="left", va="center", fontsize=9.5, color=ORANGE)


BSS_CENTERS = [(1.0, 1.15), (3.2, 1.15)]


def fig2():
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(7.7, 3.5), gridspec_kw={"width_ratios": [2.2, 1]})
    # 인프라 모드
    ax.add_patch(Rectangle((1.6, 3.15), 1.0, 0.36, facecolor="none", ec=INK, lw=1))
    ax.text(2.1, 3.33, "인터넷", ha="center", va="center", fontsize=9.5)
    ax.add_patch(Rectangle((1.55, 2.35), 1.1, 0.36, facecolor="#cccccc", alpha=0.5, ec=INK, lw=1))
    ax.text(2.1, 2.53, "스위치·라우터", ha="center", va="center", fontsize=9.5)
    ax.plot([2.1, 2.1], [2.71, 3.15], color=INK, lw=1.4)
    for k, (cx, cy) in enumerate(BSS_CENTERS):
        ax.add_patch(Circle((cx, cy), 0.95, fill=False, ec=GREEN, lw=1.2, ls="--"))
        ax.text(cx, cy - 1.08, f"BSS {k + 1}", ha="center", va="top", fontsize=9.5, color=GREEN)
        ap(ax, cx, cy + 0.45, "AP")
        ax.plot([cx, 2.1], [cy + 0.63, 2.35], color=INK, lw=1.4)          # AP는 유선으로 스위치에 붙는다
    hosts = {"가": (0.45, 0.85), "나": (1.5, 0.75), "다": (2.75, 0.8), "라": (3.65, 0.75)}
    for name, (x, y) in hosts.items():
        host(ax, x, y, name)
    # 같은 BSS 안의 가 -> 나도 AP를 거친다
    ax_ap = (BSS_CENTERS[0][0], BSS_CENTERS[0][1] + 0.45)
    arrow(ax, (0.5, 0.97), (ax_ap[0] - 0.12, ax_ap[1] - 0.1), color=PURPLE, lw=1.4)
    arrow(ax, (ax_ap[0] + 0.1, ax_ap[1] - 0.12), (1.47, 0.88), color=PURPLE, lw=1.4)
    ax.text(1.0, -0.35, "가 → 나도 AP를 거친다", ha="center", va="center", fontsize=9.5, color=PURPLE)
    ax.set_xlim(-0.1, 4.4); ax.set_ylim(-0.6, 3.6); ax.set_aspect("equal"); ax.axis("off")
    ax.set_title("인프라 모드", fontsize=10.5, color=INK)
    # 애드혹 모드
    pts = [(0.3, 1.9), (1.3, 2.3), (1.6, 1.1), (0.55, 0.7)]
    for i in range(len(pts)):
        for j in range(i + 1, len(pts)):
            if (i, j) != (1, 3):
                bx.plot([pts[i][0], pts[j][0]], [pts[i][1], pts[j][1]], color=PURPLE, lw=1.1, ls=":")
    for (x, y), name in zip(pts, ["가", "나", "다", "라"]):
        host(bx, x, y, name)
    bx.text(0.95, 0.15, "AP 없이 기기끼리 직접", ha="center", va="center", fontsize=9.5, color=PURPLE)
    bx.set_xlim(-0.1, 2.0); bx.set_ylim(-0.6, 3.6); bx.set_aspect("equal"); bx.axis("off")
    bx.set_title("애드혹 모드", fontsize=10.5, color=INK)
    fig.tight_layout()
    save(fig, 2)


if __name__ == "__main__":
    fig1()
    fig2()
    assert len(BSS_CENTERS) == 2
    assert [wifi_center(k) for k in (1, 6, 11)] == [2412, 2437, 2462]
    # 서로 안 겹치는 채널 묶음: 가운데 차이가 22 MHz 이상, 곧 번호 차이 5 이상
    assert not overlap(1, 6) and not overlap(6, 11) and overlap(1, 5)
    best = max((s for s in __import__("itertools").combinations(range(1, 12), 3)
                if all(not overlap(a, b) for a, b in __import__("itertools").combinations(s, 2))), default=None)
    assert best is not None
    four = [s for s in __import__("itertools").combinations(range(1, 12), 4)
            if all(not overlap(a, b) for a, b in __import__("itertools").combinations(s, 2))]
    assert four == []                            # 1~11에서 서로 안 겹치는 채널은 최대 3개
    assert wifi_center(11) + 11 <= 2483.5 and wifi_center(1) - 11 >= 2400
    assert 2402 + 78 == 2480                     # 블루투스 마지막 채널
    print("ALL CHECKS PASSED")