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

# CSMA/CD 문서의 그림을 만든다: 66_csma-cd_fig1.svg ~ fig3.svg
# fig1 최악 충돌 시나리오(위치-시간 그림), fig2 짧은 프레임이 일으키는 문제, fig3 충돌 횟수마다 고를 수 있는 대기 시간
# 가로축은 버스 위의 위치(왼쪽 끝 A, 오른쪽 끝 B), 세로축은 시간(위에서 아래로 흐른다).
# 편도 지연 d = 25.6 μs로 잡아 왕복 2d = 51.2 μs가 되게 했다(중계기·장비 지연을 포함한 최악값).
# 실행: ~/.venvs/vault-plots/bin/python -I 66_csma-cd_plot.py  (matplotlib, numpy 필요)
import os

import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import Polygon

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "66_csma-cd"
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.5, "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,
})

D = 25.6          # 편도 지연(μs)
JAM = 3.2         # 잼 32비트 = 3.2 μs (10 Mbps)


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"):
        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 band_from_left(ax, t0, t1, color, alpha=0.35):
    """왼쪽 끝(x=0)에서 [t0, t1] 동안 보낸 신호가 오른쪽으로 퍼지는 띠. x는 0~1(1 = 편도 D)."""
    ax.add_patch(Polygon([(0, t0), (1, t0 + D), (1, t1 + D), (0, t1)], closed=True,
                         facecolor=color, edgecolor=color, alpha=alpha, lw=1))


def band_from_right(ax, t0, t1, color, alpha=0.35):
    ax.add_patch(Polygon([(1, t0), (0, t0 + D), (0, t1 + D), (1, t1)], closed=True,
                         facecolor=color, edgecolor=color, alpha=alpha, lw=1))


def frame_axes(ax, tmax, title):
    ax.set_xlim(-0.32, 1.32)
    ax.set_ylim(tmax, -4)
    ax.set_xticks([0, 1])
    ax.set_xticklabels(["A (왼쪽 끝)", "B (오른쪽 끝)"])
    ax.set_ylabel("시간 (μs)")
    ax.axvline(0, color=INK, lw=1)
    ax.axvline(1, color=INK, lw=1)
    ax.spines["bottom"].set_visible(False)
    ax.tick_params(axis="x", length=0)
    ax.set_title(title, fontsize=11)


def worst_case_events():
    b_start = D - 0.6                 # A의 신호가 닿기 0.6 μs 전에 B가 감지 -> 비었다고 보고 보낸다
    b_detect = D                      # A의 첫 비트가 B에 닿는다
    a_detect = b_start + D            # B의 첫 비트가 A에 닿는다
    return b_start, b_detect, a_detect


def fig1():
    b_start, b_detect, a_detect = worst_case_events()
    fig, ax = plt.subplots(figsize=(6.6, 5.0))
    frame_axes(ax, 62, "최악의 충돌: 두 노드가 버스의 양 끝에 있을 때")
    band_from_left(ax, 0, a_detect + JAM, BLUE)
    band_from_right(ax, b_start, b_detect + JAM, ORANGE, alpha=0.5)
    ax.annotate("A 보내기 시작 (0)", xy=(0, 0), xytext=(-0.3, 4), fontsize=10, color=BLUE)
    ax.annotate(f"B: 비었다고 보고\n보내기 시작 ({b_start:.1f})", xy=(1, b_start), xytext=(1.03, b_start - 9),
                fontsize=10, color=ORANGE)
    ax.plot([1], [b_detect], "o", color=ORANGE, ms=5)
    ax.annotate(f"B가 충돌을 앎 ({b_detect:.1f})\n→ 잼 보내고 멈춤", xy=(1, b_detect), xytext=(1.03, b_detect + 3),
                fontsize=10, color=ORANGE)
    ax.plot([0], [a_detect], "o", color=BLUE, ms=5)
    ax.annotate(f"A가 충돌을 앎 ({a_detect:.1f})\n→ 잼 보내고 멈춤", xy=(0, a_detect), xytext=(-0.31, a_detect - 9),
                fontsize=10, color=BLUE)
    ax.annotate("", xy=(0.5, 0), xytext=(0.5, 2 * D),
                arrowprops=dict(arrowstyle="<->", color=PURPLE, lw=1.2))
    ax.text(0.52, D - 2, "2d = 51.2 μs\n(최악의 왕복)", color=PURPLE, fontsize=10)
    ax.text(0.30, 12, "A의 신호", color=BLUE, fontsize=10, rotation=-22)
    ax.text(0.62, 45, "B의 신호", color=ORANGE, fontsize=10, rotation=22)
    save(fig, 1)
    return b_start, b_detect, a_detect


def fig2():
    frame_len = 20.0                  # 200비트짜리 짧은 프레임
    b_start, b_detect, a_detect = worst_case_events()
    xc = 0.2
    fig, ax = plt.subplots(figsize=(6.6, 5.0))
    frame_axes(ax, 62, "프레임이 2d보다 짧으면")
    band_from_left(ax, 0, frame_len, BLUE)
    band_from_right(ax, b_start, b_detect + JAM, ORANGE, alpha=0.5)
    ax.axvline(xc, color=GREEN, lw=1, ls="--")
    c_end = xc * D + frame_len
    c_hit = b_start + (1 - xc) * D
    ax.plot([xc, xc], [xc * D, c_end], color=GREEN, lw=4, solid_capstyle="butt")
    ax.text(xc + 0.02, xc * D + 9, "C: 프레임을\n온전히 받음", color=GREEN, fontsize=10)
    ax.plot([xc], [c_hit], "x", color=ORANGE, ms=7)
    ax.text(xc + 0.06, c_hit + 9, f"B의 신호는 {c_hit:.1f}에야\nC에 도착", color=ORANGE, fontsize=10)
    ax.annotate(f"A 보내기 끝 ({frame_len:.0f})\n충돌을 모른 채\n성공으로 여김", xy=(0, frame_len), xytext=(-0.31, frame_len + 3),
                fontsize=10, color=BLUE)
    ax.plot([0], [a_detect], "o", color=INK, ms=5)
    ax.text(-0.31, a_detect + 4, f"B의 신호가 A에\n닿는 때 ({a_detect:.1f})", fontsize=10)
    ax.text(1.03, b_detect + 3, f"B: 충돌\n(A의 프레임이\n깨져서 도착)", color=ORANGE, fontsize=10)
    ax.text(xc - 0.05, -1.5, "C", color=GREEN, fontsize=10)
    save(fig, 2)
    return c_end, c_hit, a_detect, frame_len


def fig3():
    fig, ax = plt.subplots(figsize=(7.4, 2.8))
    for n in (1, 2, 3, 4):
        ks = range(2 ** n)
        ax.plot([k * 51.2 for k in ks], [n] * len(ks), "o", color=C[n - 1], ms=6)
        ax.text(2 ** n * 51.2 - 30, n + 0.28, f"{2 ** n}가지", color=C[n - 1], fontsize=10)
    ax.set_yticks([1, 2, 3, 4])
    ax.set_yticklabels(["1번째 충돌 뒤", "2번째", "3번째", "4번째"])
    ax.set_ylim(4.7, 0.4)
    ax.set_xlabel("다시 시도하기 전에 기다리는 시간 (μs) = k × 51.2")
    ax.set_xticks([0, 51.2, 153.6, 358.4, 768])
    ax.set_xticklabels(["0", "51.2", "153.6", "358.4", "768"])
    save(fig, 3)


if __name__ == "__main__":
    b_start, b_detect, a_detect = fig1()
    assert abs(b_start - 25.0) < 1e-9 and b_detect == 25.6 and abs(a_detect - 50.6) < 1e-9
    assert a_detect < 2 * D                          # 최악의 경우 A는 2d 바로 전에 안다
    c_end, c_hit, a_det2, frame_len = fig2()
    assert abs(c_end - 25.12) < 1e-9 and abs(c_hit - 45.48) < 1e-9
    assert c_end < c_hit                             # C에는 깨지지 않은 프레임이 먼저 다 도착한다
    assert frame_len < a_det2                        # A는 B의 신호가 오기 전에 보내기를 끝낸다
    fig3()
    assert 15 * 51.2 == 768.0
    print("ALL CHECKS PASSED")