이더넷 평가와 확장 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 이더넷 평가와 확장 문서의 그림을 만든다: 67_ethernet-evaluation_fig1.svg, fig2.svg
# fig1 두 세그먼트를 중계기로 이을 때와 브리지로 이을 때: A가 B에게 보내는 동안 C가 D에게 보낼 수 있나
# fig2 프레임 길이에 따른 CSMA/CD 효율의 근사식 1 / (1 + 5a), a = 최대 전파 시간 / 프레임 싣는 시간
#      (Kurose & Ross, Computer Networking, 6장. 보낼 프레임이 늘 있는 노드가 아주 많을 때의 근사)
# 실행: ~/.venvs/vault-plots/bin/python -I 67_ethernet-evaluation_plot.py  (matplotlib, numpy 필요)
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 Rectangle

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "67_ethernet-evaluation"
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, "font.size": 10.5, "axes.unicode_minus": False, "svg.fonttype": "path",
    "svg.hashsalt": PREFIX, "text.color": INK,
    "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
    "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
    "axes.spines.top": False, "axes.spines.right": False, "legend.frameon": False,
})

RATE = 10e6            # 10 Mbps
D_WORST = 25.6e-6      # 최악 편도 전파 시간(왕복 51.2 μs)
D_SHORT = 2.5e-6       # 짧은 LAN(왕복 약 5 μs)


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 efficiency(frame_bytes, d_prop, rate=RATE):
    t_trans = frame_bytes * 8 / rate
    a = d_prop / t_trans
    return 1 / (1 + 5 * a)


def link_state(device):
    """A가 B에게 보내는 동안 오른쪽 세그먼트가 바쁜지, C가 D에게 보낼 수 있는지."""
    right_busy = device == "repeater"          # 중계기는 모든 비트를 반대쪽으로 다시 낸다
    return right_busy, not right_busy


def fig1():
    fig, axes = plt.subplots(2, 1, figsize=(7.4, 4.4))
    results = {}
    for ax, device, title in [(axes[0], "repeater", "중계기로 이었을 때"),
                              (axes[1], "bridge", "브리지로 이었을 때")]:
        right_busy, cd_ok = link_state(device)
        results[device] = (right_busy, cd_ok)
        ax.set_xlim(0, 10)
        ax.set_ylim(-0.9, 1.5)
        ax.axis("off")
        ax.text(0, 1.3, title, fontsize=11)
        # 세그먼트 두 개
        ax.plot([0.3, 4.3], [0, 0], color=BLUE, lw=6, alpha=0.45)                       # 왼쪽: A가 보내는 중
        ax.plot([5.7, 9.7], [0, 0], color=BLUE if right_busy else INK, lw=6 if right_busy else 2,
                alpha=0.45 if right_busy else 1)
        box_col = ORANGE if device == "repeater" else PURPLE
        ax.add_patch(Rectangle((4.4, -0.25), 1.2, 0.5, facecolor=box_col, alpha=0.25, edgecolor=box_col))
        ax.text(5.0, 0, "중계기" if device == "repeater" else "브리지", ha="center", va="center", fontsize=10,
                color=box_col)
        ax.plot([4.3, 4.4], [0, 0], color=INK, lw=2)
        ax.plot([5.6, 5.7], [0, 0], color=INK, lw=2)
        for x, name in [(1.0, "A"), (3.4, "B"), (6.6, "C"), (9.0, "D")]:
            ax.plot([x, x], [0, 0.45], color=INK, lw=1)
            ax.add_patch(Rectangle((x - 0.25, 0.45), 0.5, 0.4, facecolor="none", edgecolor=INK))
            ax.text(x, 0.65, name, ha="center", va="center", fontsize=10.5)
        ax.annotate("", xy=(3.4, -0.35), xytext=(1.0, -0.35),
                    arrowprops=dict(arrowstyle="-|>", color=BLUE, lw=1.4))
        ax.text(2.2, -0.7, "A → B 보내는 중", ha="center", fontsize=10, color=BLUE)
        if cd_ok:
            ax.annotate("", xy=(9.0, -0.35), xytext=(6.6, -0.35),
                        arrowprops=dict(arrowstyle="-|>", color=GREEN, lw=1.4))
            ax.text(7.8, -0.7, "C → D 동시에 보냄", ha="center", fontsize=10, color=GREEN)
        else:
            ax.text(7.8, -0.7, "C: 캐리어가 들려 기다림", ha="center", fontsize=10, color=ORANGE)
    fig.tight_layout()
    save(fig, 1)
    return results


def fig2():
    sizes = np.linspace(64, 1518, 400)
    fig, ax = plt.subplots(figsize=(7.0, 3.6))
    for d, col, label in [(D_WORST, BLUE, "최악 왕복 51.2 μs"), (D_SHORT, GREEN, "짧은 LAN, 왕복 약 5 μs")]:
        eff = [efficiency(s, d) for s in sizes]
        ax.plot(sizes, eff, color=col, lw=2)
        ax.text(1530, eff[-1], label, color=col, fontsize=10, va="center")
    for s in (64, 1500):
        e = efficiency(s, D_WORST)
        ax.plot([s], [e], "o", color=BLUE, ms=5)
        ax.annotate(f"{s}바이트: {e:.0%}", xy=(s, e), xytext=(s + 60, e - 0.12), fontsize=10, color=BLUE)
    ax.set_xlim(0, 1550)
    ax.set_ylim(0, 1.02)
    ax.set_xlabel("프레임 길이 (바이트)")
    ax.set_ylabel("효율")
    ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
    ax.set_yticklabels(["0", "25%", "50%", "75%", "100%"])
    save(fig, 2)


if __name__ == "__main__":
    res = fig1()
    assert res["repeater"] == (True, False) and res["bridge"] == (False, True)
    fig2()
    # 근사식의 핵심 값
    assert abs(efficiency(1500, D_WORST) - 1 / (1 + 5 * 25.6 / 1200)) < 1e-12
    assert round(efficiency(1500, D_WORST), 3) == 0.904
    assert abs(efficiency(64, D_WORST) - 1 / 3.5) < 1e-12               # a = 25.6/51.2 = 0.5
    assert round(efficiency(64, D_SHORT), 3) == 0.804
    assert efficiency(64, D_WORST) < efficiency(1500, D_WORST)          # 큰 프레임이 효율이 높다
    # 10 Mbps의 30%는 3 Mbps
    assert round(0.3 * RATE) == 3_000_000
    # 같은 512비트가 100 Mbps에서는 5.12 μs, 1 Gbps에서는 0.512 μs. 1 Gbps 반이중의 4,096비트(512바이트)는 4.096 μs
    assert abs(512 / 100e6 - 5.12e-6) < 1e-15 and abs(512 / 1e9 - 0.512e-6) < 1e-15
    assert abs(4096 / 1e9 - 4.096e-6) < 1e-15 and 4096 // 8 == 512
    print("ALL CHECKS PASSED")