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

# CDMA 문서의 그림을 만든다: 71_cdma_fig1.svg(FDMA·TDMA·CDMA가 자원을 나누는 방식), 71_cdma_fig2.svg(두 사용자 칩 예),
# 71_cdma_fig3.svg(칩 6개짜리 무작위 키 예: 1은 +1, 0은 -1로 그린다. 받는 쪽은 키를 곱해 비트 시간마다 쌓고 부호로 판정)
# 칩과 데이터는 +1/-1. A의 코드 (+1,-1,+1,-1), B의 코드 (+1,+1,-1,-1), A는 +1, -1을, B는 +1, +1을 보낸다.
# 실행: ~/.venvs/vault-plots/bin/python -I 71_cdma_plot.py  (matplotlib, numpy 필요)
PREFIX = "71_cdma"
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=":")


A_CODE = [1, -1, 1, -1]
B_CODE = [1, 1, -1, -1]
A_DATA = [1, -1]
B_DATA = [1, 1]


def spread(data, code):
    return [d * c for d in data for c in code]


def fig1():
    """FDMA, TDMA, CDMA가 시간-주파수 자원을 나누는 방식."""
    fig, axs = plt.subplots(1, 3, figsize=(7.6, 2.9))
    cols = [BLUE, ORANGE, GREEN]
    # FDMA: 주파수 띠 3개, 시간은 모두
    ax = axs[0]
    for i in range(3):
        ax.add_patch(Rectangle((0, i + 0.08), 3, 0.84, color=cols[i], alpha=0.55, lw=0))
        ax.text(1.5, i + 0.5, f"사용자 {i + 1}", ha="center", va="center", color="white", fontsize=10)
    ax.set_title("FDMA: 주파수를 나눈다", fontsize=10.5, color=INK)
    # TDMA: 시간 칸 3개(되풀이), 주파수는 모두
    ax = axs[1]
    for k in range(6):
        i = k % 3
        ax.add_patch(Rectangle((k * 0.5 + 0.03, 0), 0.44, 3, color=cols[i], alpha=0.55, lw=0))
        ax.text(k * 0.5 + 0.25, 1.5, f"{i + 1}", ha="center", va="center", color="white", fontsize=10)
    ax.set_title("TDMA: 시간을 나눈다", fontsize=10.5, color=INK)
    # CDMA: 모두 전체 시간·전체 주파수, 코드 축으로 층이 쌓인다
    ax = axs[2]
    for i in range(3):
        off = (2 - i) * 0.3
        ax.add_patch(Rectangle((off, off), 2.4, 2.4, color=cols[i], alpha=0.5, lw=1.2, ec=cols[i]))
        ax.text(off + 0.08, off + 2.4 + 0.04, f"코드 {i + 1}", ha="left", va="bottom", color=cols[i], fontsize=9.5)
    ax.annotate("", xy=(3.05, 0.75), xytext=(2.45, 0.15),
                arrowprops=dict(arrowstyle="-|>", color=INK, lw=1.1))
    ax.text(2.88, 0.2, "코드", ha="left", va="center", fontsize=9.5)
    ax.set_title("CDMA: 코드로 가른다", fontsize=10.5, color=INK)
    for ax in axs:
        ax.set_xlim(0, 3.1); ax.set_ylim(0, 3.4)
        ax.set_xticks([]); ax.set_yticks([])
        ax.set_xlabel("시간", fontsize=10); ax.set_ylabel("주파수", fontsize=10)
        ax.set_aspect("equal")
    fig.tight_layout()
    save(fig, 1)


def fig2():
    """두 사용자 예: A의 신호, B의 신호, 합, 합 x A의 코드, 비트별 합."""
    a = spread(A_DATA, A_CODE)
    b = spread(B_DATA, B_CODE)
    z = [x + y for x, y in zip(a, b)]
    prod = [zz * c for zz, c in zip(z, A_CODE * 2)]
    rows = [("A가 보내는 칩", a, BLUE, 0.35), ("B가 보내는 칩", b, ORANGE, 0.35),
            ("공중에서 더해진 신호 Z", z, PURPLE, 0.25), ("Z × A의 코드", prod, GREEN, 0.25)]
    fig, ax = plt.subplots(figsize=(7.6, 5.2))
    ys = [7.6, 5.7, 3.6, 1.3]
    for (label, vals, col, sc), y in zip(rows, ys):
        steps(ax, vals, y, col, scale=sc)
        ax.text(-0.3, y, label, ha="right", va="center", fontsize=10)
        for i, v in enumerate(vals):
            ax.text(i + 0.5, y + v * sc + (0.12 if v >= 0 else -0.12), f"{v:+d}" if v else "0",
                    ha="center", va="bottom" if v >= 0 else "top", fontsize=9.5, color=col)
    for x in (4,):
        ax.plot([x, x], [0.4, 8.3], color=INK, lw=1, ls="--")
    for k in range(2):
        s = sum(prod[4 * k:4 * k + 4])
        ax.text(4 * k + 2, 0.15, f"칩 4개 합 = {s:+d}, ÷4 = {s // 4:+d}", ha="center", va="top", fontsize=10,
                color=GREEN)
        ax.text(4 * k + 2, 8.45, f"{k + 1}번째 비트 시간", ha="center", va="bottom", fontsize=10)
    ax.set_xlim(-0.2, 8.2); ax.set_ylim(-0.4, 8.8)
    ax.axis("off")
    save(fig, 2)
    return a, b, z, prod


KA = "100110010100100010110011"
KB = "010101001110101000010111"
DA, DB = "1101", "0100"


def fig3():
    """칩 6개짜리 무작위 키 예. 0/1을 -1/+1로 그린다(1이 위)."""
    pm = lambda bits: np.array([2 * int(b) - 1 for b in bits])
    xor = lambda D, K: "".join(str(int(D[i // 6]) ^ int(K[i])) for i in range(len(K)))
    sa, sb = pm(xor(DA, KA)), pm(xor(DB, KB))
    z = sa + sb
    prod = z * pm(KA)
    run = []
    for k in range(4):
        acc = 0
        run.append(0)
        for v in prod[6 * k:6 * k + 6]:
            acc += v
            run.append(acc)
    sums = [int(prod[6 * k:6 * k + 6].sum()) for k in range(4)]
    out = "".join("1" if v > 0 else "0" for v in sums)
    fig, ax = plt.subplots(figsize=(7.7, 5.6))
    rows = [("A가 보내는 칩", sa, BLUE, 0.3), ("B가 보내는 칩", sb, ORANGE, 0.3), ("더해진 신호 A+B", z, PURPLE, 0.2),
            ("A의 키", pm(KA), INK, 0.3), ("(A+B) × A의 키", prod, GREEN, 0.2)]
    ys = [9.6, 8.3, 6.8, 5.4, 3.9]
    for (label, vals, col, sc), y in zip(rows, ys):
        steps(ax, list(vals), y, col, scale=sc, lw=1.5)
        ax.text(-0.4, y, label, ha="right", va="center", fontsize=9.5)
    # 비트 시간마다 쌓은 합
    y0 = 1.9
    for k in range(4):
        xs = np.arange(6 * k, 6 * k + 7)
        ax.plot(xs, y0 + np.array(run[7 * k:7 * k + 7]) * 0.13, color=GOLD, lw=1.6)
        ax.text(6 * k + 6, y0 + sums[k] * 0.13 + (0.15 if sums[k] > 0 else -0.15), f"{sums[k]:+d}", ha="right",
                va="bottom" if sums[k] > 0 else "top", fontsize=9.5, color=GOLD)
    ax.plot([0, 24], [y0, y0], color=INK, lw=0.6, ls=":")
    ax.text(-0.4, y0, "비트 시간마다 쌓은 합", ha="right", va="center", fontsize=9.5)
    for k in range(4):
        ax.text(6 * k + 3, 0.35, out[k], ha="center", va="center", fontsize=10.5, color=GOLD)
        ax.text(6 * k + 3, 10.35, f"A {DA[k]} / B {DB[k]}", ha="center", va="bottom", fontsize=9.5)
    ax.text(-0.4, 0.35, "합의 부호(+ -> 1)", ha="right", va="center", fontsize=9.5)
    for k in range(1, 4):
        ax.plot([6 * k, 6 * k], [0, 10.3], color=INK, lw=0.8, ls="--")
    ax.set_xlim(-0.2, 24.2); ax.set_ylim(-0.1, 10.9)
    ax.axis("off")
    save(fig, 3)
    return sums, out


if __name__ == "__main__":
    fig1()
    a, b, z, prod = fig2()
    assert a == [1, -1, 1, -1, -1, 1, -1, 1]
    assert b == [1, 1, -1, -1, 1, 1, -1, -1]
    assert z == [2, 0, 0, -2, 0, 2, -2, 0]
    assert sum(prod[:4]) == 4 and sum(prod[4:]) == -4
    assert sum(np.array(z[:4]) * B_CODE) == 4 and sum(np.array(z[4:]) * B_CODE) == 4
    sums, out = fig3()
    assert sums == [-8, -6, 8, -4] and out == "0010"
    assert "".join("1" if c == "0" else "0" for c in out) == DA
    print("ALL CHECKS PASSED")