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

# 스위치 성능 문서의 그림을 만든다: 82_switch-performance_fig1.svg
# 실행: ~/.venvs/vault-plots/bin/python 82_switch-performance_plot.py  (matplotlib, numpy 필요)
import numpy as np

PREFIX = "82_switch-performance"
import os

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

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.4, ls="-", ms=12):
    ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=ms, color=color, lw=lw, ls=ls,
                                 shrinkA=0, shrinkB=0))


# 예제 그림의 토폴로지: 스위치 3개와 포트 번호(0 위, 1 오른쪽, 2 아래, 3 왼쪽 방향 등)
SW = {"S1": (2.0, 4.2), "S2": (5.2, 3.0), "S3": (6.6, 0.8)}
DIR = {  # 스위치별 포트 방향 (dx, dy)
    "S1": {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)},
    "S2": {0: (0, -1), 1: (1, 0), 2: (0, 1), 3: (-1, 0)},
    "S3": {0: (0, 1), 1: (-1, 0), 2: (0, -1), 3: (1, 0)},
}
HOSTS = {"D": ("S1", 0), "A": ("S1", 2), "C": ("S1", 3), "F": ("S2", 1), "E": ("S2", 2),
         "G": ("S3", 1), "H": ("S3", 2), "B": ("S3", 3)}
TRUNKS = [(("S1", 1), ("S2", 3)), (("S2", 0), ("S3", 0))]
HS = 0.28   # 스위치 상자 반 폭


def port_xy(sw, p, r=HS):
    x, y = SW[sw]
    dx, dy = DIR[sw][p]
    return x + dx * r, y + dy * r


def host_xy(h):
    sw, p = HOSTS[h]
    x, y = SW[sw]
    dx, dy = DIR[sw][p]
    return x + dx * 1.05, y + dy * 1.05


def draw_topology(ax, hosts=None, hl_hosts=()):
    hosts = list(HOSTS) if hosts is None else hosts
    for (a, pa), (b, pb) in TRUNKS:
        (x1, y1), (x2, y2) = port_xy(a, pa), port_xy(b, pb)
        ax.plot([x1, x2], [y1, y2], color=INK, lw=1.3, zorder=1)
    for h in hosts:
        sw, p = HOSTS[h]
        (x1, y1), (x2, y2) = port_xy(sw, p), host_xy(h)
        dx, dy = DIR[sw][p]
        ax.plot([x1, x2 - dx * 0.22], [y1, y2 - dy * 0.16], color=INK, lw=1.3, zorder=1)
        col = ORANGE if h in hl_hosts else INK
        ax.add_patch(Rectangle((x2 - 0.22, y2 - 0.16), 0.44, 0.32, fill=False, ec=col, lw=1.4, zorder=3))
        ax.text(x2, y2, h, ha="center", va="center", fontsize=11, color=col, zorder=4)
    for sw, (x, y) in SW.items():
        ax.add_patch(Rectangle((x - HS, y - HS), 2 * HS, 2 * HS, fc="none", ec=BLUE, lw=1.6, zorder=3))
        ax.text(x, y, sw, ha="center", va="center", fontsize=10.5, color=BLUE, zorder=4)
        for p, (dx, dy) in DIR[sw].items():
            ax.text(x + dx * 0.43 + (0.1 if dy else 0), y + dy * 0.43 + (0.1 if dx else 0), str(p),
                    ha="center", va="center", fontsize=9.5, color=INK, zorder=4)

BUS = 800e6                     # I/O 버스 대역폭
CAP = BUS / 2                   # 버스를 두 번 지나므로 총 대역폭은 절반


def pps_line(pps, size):
    return pps * size * 8


L = np.linspace(64, 1600, 800)
fig, ax = plt.subplots(figsize=(7.2, 4.2))
for pps, col, name in [(100_000, BLUE, "초당 100,000개"), (15_000, GREEN, "초당 15,000개")]:
    y = pps_line(pps, L) / 1e6
    ax.plot(L, y, color=col, lw=1.0, ls=":")
    ax.plot(L, np.minimum(y, CAP / 1e6), color=col, lw=2.2)
ax.axhline(CAP / 1e6, color=ORANGE, lw=1.2, ls="--")
ax.text(1590, CAP / 1e6 + 12, "버스 한계 400 Mbps (800 Mbps 버스의 절반)", color=ORANGE, ha="right", fontsize=10)
ax.text(250, 520, "초당 100,000개 처리", color=BLUE, fontsize=10)
ax.text(1080, 95, "초당 15,000개 처리", color=GREEN, fontsize=10)
ax.plot([500], [400], "o", color=BLUE, ms=5)
ax.annotate("500바이트: 두 한계가 만남", (500, 400), (620, 300), color=BLUE, fontsize=10,
            arrowprops=dict(arrowstyle="-", color=BLUE, lw=0.8))
ax.set_xlim(0, 1620)
ax.set_ylim(0, 620)
ax.set_xticks([64, 500, 1000, 1500])
ax.set_xlabel("패킷 길이 (바이트)")
ax.set_ylabel("스위치를 지나는 총 처리량 (Mbps)")
save(fig, 1)


if __name__ == "__main__":
    assert CAP == 400e6
    assert CAP / (100_000 * 8) == 500                      # 갈림점 500바이트
    assert pps_line(15_000, 1500) == 180e6 < CAP            # 15,000 pps는 1,500바이트에서도 pps가 한계
    assert pps_line(100_000, 1500) == 1.2e9 > CAP           # 100,000 pps는 긴 패킷에서 버스가 한계
    print("ALL CHECKS PASSED")