확산 스펙트럼 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 확산 스펙트럼 문서의 그림을 만든다: 70_spread-spectrum_fig1.svg(좁게 몰아 쓰기와 넓게 펴 쓰기),
# fig2.svg(직접 시퀀스: 데이터 1010과 4칩 무작위 열의 XOR), fig3.svg(주파수 호핑 두 쌍).
# 문서의 주장(XOR 결과, XOR을 다시 하면 복원, 0/1 -> +1/-1이면 XOR = 곱, 바커 11칩은 5칩까지 깨져도 복원,
# 79채널 호핑의 겹침 확률 1/79)도 확인한다.
# 실행: ~/.venvs/vault-plots/bin/python -I 70_spread-spectrum_plot.py  (matplotlib, numpy 필요)
PREFIX = "70_spread-spectrum"
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=":")


DATA = "1010"
RANDOM = "0100101101011001"                    # 칩 4개 x 4비트
BARKER = [1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1]   # 802.11 1·2 Mbps DSSS의 11칩 바커 코드


def xor_spread(data, chips):
    n = len(chips) // len(data)
    expanded = "".join(b * n for b in data)
    return expanded, "".join(str(int(a) ^ int(c)) for a, c in zip(expanded, chips))


def fig1():
    """좁은 띠에 몰아 쓰기와 넓게 펴서 쓰기: 같은 에너지(넓이), 다른 높이."""
    fig, axs = plt.subplots(1, 2, figsize=(7.6, 2.6), sharey=True)
    f = np.linspace(0, 100, 1001)
    narrow = np.where(np.abs(f - 40) <= 2.5, 1.0, 0.0)
    wide = np.where(np.abs(f - 50) <= 40, 5 / 80, 0.0)
    other = np.where(np.abs(f - 41) <= 2.5, 1.0, 0.0)
    ax = axs[0]
    ax.fill_between(f, narrow, color=BLUE, alpha=0.6, lw=0)
    ax.fill_between(f, other, color=ORANGE, alpha=0.45, lw=0)
    ax.text(47, 0.85, "내 신호", color=BLUE, fontsize=10)
    ax.text(47, 0.65, "옆 사람 신호(같은 자리)", color=ORANGE, fontsize=10)
    ax.set_title("좁은 띠에 몰아 쓴다", fontsize=10.5, color=INK)
    ax = axs[1]
    ax.fill_between(f, wide, color=BLUE, alpha=0.6, lw=0)
    ax.fill_between(f, other, color=ORANGE, alpha=0.45, lw=0)
    ax.text(52, 0.2, "넓게 편 내 신호", color=BLUE, fontsize=10)
    ax.text(47, 0.85, "옆 사람 신호", color=ORANGE, fontsize=10)
    ax.set_title("넓게 펴서 쓴다", fontsize=10.5, color=INK)
    for ax in axs:
        ax.set_xticks([]); ax.set_yticks([])
        ax.set_xlabel("주파수", fontsize=10)
        ax.set_ylim(0, 1.1)
    axs[0].set_ylabel("세기", fontsize=10)
    fig.tight_layout()
    save(fig, 1)
    return np.trapezoid(narrow, f), np.trapezoid(wide, f)


def fig2():
    """직접 시퀀스: 데이터 1010, 무작위 칩열, XOR 결과."""
    expanded, out = xor_spread(DATA, RANDOM)
    fig, ax = plt.subplots(figsize=(7.6, 3.3))
    rows = [("데이터 1010\n(비트 하나 = 칩 4개 폭)", expanded, BLUE), ("약속한 칩열", RANDOM, ORANGE),
            ("XOR 결과(실제로 보냄)", out, GREEN)]
    for r, (label, bits, col) in enumerate(rows):
        y = 2 - r
        vals = [int(b) for b in bits]
        xs, ys = [], []
        for i, v in enumerate(vals):
            xs += [i, i + 1]; ys += [y + v * 0.55, y + v * 0.55]
        ax.plot(xs, ys, color=col, lw=1.8)
        ax.text(-0.4, y + 0.27, label, ha="right", va="center", fontsize=10)
        step = 4 if r == 0 else 1
        for i in range(0, 16, step):
            ax.text(i + step / 2, y + 0.62, bits[i], ha="center", va="bottom", fontsize=9.5, color=col)
    for k in range(1, 4):
        ax.plot([4 * k, 4 * k], [-0.1, 2.85], color=INK, lw=0.8, ls="--")
    ax.set_xlim(-0.2, 16.2); ax.set_ylim(-0.2, 3.0)
    ax.axis("off")
    save(fig, 2)
    return out


def fig3(seed_a=3, seed_b=11, slots=24, channels=79):
    """주파수 호핑: 두 쌍이 각자의 씨앗으로 채널을 건너뛴다. 같은 칸에 겹친 순간만 X."""
    ra, rb = np.random.default_rng(seed_a), np.random.default_rng(seed_b)
    ha = ra.integers(0, channels, slots)
    hb = rb.integers(0, channels, slots)
    fig, ax = plt.subplots(figsize=(7.6, 3.0))
    for t in range(slots):
        ax.add_patch(Rectangle((t + 0.1, ha[t] - 0.7), 0.8, 1.4, color=BLUE, alpha=0.8, lw=0))
        ax.add_patch(Rectangle((t + 0.1, hb[t] - 0.7), 0.8, 1.4, color=ORANGE, alpha=0.8, lw=0))
    hits = [t for t in range(slots) if ha[t] == hb[t]]
    for t in hits:
        ax.text(t + 0.5, ha[t] + 3, "겹침", ha="center", va="bottom", fontsize=9.5, color=PURPLE)
    ax.text(slots + 0.3, 70, "쌍 1", color=BLUE, fontsize=10)
    ax.text(slots + 0.3, 60, "쌍 2", color=ORANGE, fontsize=10)
    ax.set_xlim(0, slots + 2.5); ax.set_ylim(-3, channels + 3)
    ax.set_xlabel("시간(칸 하나 = 한 번 머무는 시간)", fontsize=10)
    ax.set_ylabel("채널 번호(0~78)", fontsize=10)
    ax.set_xticks([])
    save(fig, 3)
    return hits


def despread(chips, code):
    return sum(a * b for a, b in zip(chips, code))


if __name__ == "__main__":
    e_n, e_w = fig1()
    assert abs(e_n - e_w) < 0.1, (e_n, e_w)                       # 같은 넓이(에너지)
    out = fig2()
    assert out == "1011101110101001"                     # 예제의 XOR 결과와 같다
    # XOR을 한 번 더 하면 데이터가 돌아온다
    back = "".join(str(int(a) ^ int(c)) for a, c in zip(out, RANDOM))
    assert back == "1111000011110000"
    # 0 -> +1, 1 -> -1로 바꾸면 XOR은 곱셈과 같다
    m = {"0": 1, "1": -1}
    for a in "01":
        for b in "01":
            assert m[str(int(a) ^ int(b))] == m[a] * m[b]
    hits = fig3()
    assert hits == [23], hits                          # 24칸 중 한 번만 겹친다
    # 바커 11칩: 자기 자신과의 내적 11, 칩 f개가 뒤집히면 11 - 2f. f <= 5면 부호가 그대로
    assert despread(BARKER, BARKER) == 11
    for f in range(12):
        noisy = [(-c if i < f else c) for i, c in enumerate(BARKER)]
        assert despread(noisy, BARKER) == 11 - 2 * f
    assert max(f for f in range(12) if 11 - 2 * f > 0) == 5
    # 두 쌍이 79채널을 독립으로 고르면 한 칸에서 겹칠 확률은 1/79
    rng = np.random.default_rng(0)
    a = rng.integers(0, 79, 200000); b = rng.integers(0, 79, 200000)
    p = np.mean(a == b)
    assert abs(p - 1 / 79) < 0.002
    # 카드 C1: 데이터 01, 칩열 11001010(비트마다 4칩) -> 11000101, 받는 쪽이 같은 칩열과 XOR하면 0000 1111
    _, c1 = xor_spread("01", "11001010")
    assert c1 == "11000101"
    assert "".join(str(int(a) ^ int(c)) for a, c in zip(c1, "11001010")) == "00001111"
    # 칩 4개 중 하나가 깨져도(11000101 -> 11100101) 다수결로 0을 읽는다
    bad = "11100101"
    rec = "".join(str(int(a) ^ int(c)) for a, c in zip(bad, "11001010"))
    assert rec[:4] == "0010" and rec[:4].count("0") == 3
    # 칩 n개로 펴면 칩 속도는 n배: 1 Mbps에 11칩이면 11 Mchip/s
    assert 1e6 * len(BARKER) == 11e6
    print(f"hop collision rate ~ {p:.4f} (1/79 = {1/79:.4f})")
    print("ALL CHECKS PASSED")