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

# 데이터그램 문서의 그림을 만든다: 78_datagram_fig1.svg
# 실행: ~/.venvs/vault-plots/bin/python 78_datagram_plot.py  (matplotlib 필요)
from collections import deque

PREFIX = "78_datagram"
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)


def next_port(sw, dst):
    """토폴로지에서 너비 우선 탐색으로 sw가 dst로 보내려면 어느 포트로 내보내야 하는지 구한다."""
    peer = {}
    for (a, pa), (b, pb) in TRUNKS:
        peer[(a, pa)], peer[(b, pb)] = (b, pb), (a, pa)
    for h, (s, p) in HOSTS.items():
        peer[(s, p)], peer[(h, 0)] = (h, 0), (s, p)
    first = {}
    q = deque()
    for (n, p), (m, _) in peer.items():
        if n == sw:
            first[m] = p
            q.append(m)
    seen = {sw} | set(first)
    while q:
        u = q.popleft()
        for (n, p), (m, _) in peer.items():
            if n == u and m not in seen:
                seen.add(m)
                first[m] = first[u]
                q.append(m)
    return first[dst]


S2_TABLE = [("A", 3), ("B", 0), ("C", 3), ("D", 3), ("E", 2), ("F", 1), ("G", 0), ("H", 0)]

fig, ax = plt.subplots(figsize=(7.6, 4.6))
ax.set_aspect("equal")
ax.axis("off")
draw_topology(ax, hl_hosts=("A", "B"))
# 패킷 B가 지나는 길과 링크 위의 패킷
path = [host_xy("A"), port_xy("S1", 2), port_xy("S1", 1), port_xy("S2", 3), port_xy("S2", 0), port_xy("S3", 0),
        port_xy("S3", 3), host_xy("B")]
for (x1, y1), (x2, y2) in [(path[0], path[1]), (path[2], path[3]), (path[4], path[5]), (path[6], path[7])]:
    arrow(ax, (x1 + 0.12, y1 + 0.12 if y1 == y2 else y1), (x2 + 0.12, y2 + 0.12 if y1 == y2 else y2),
          color=ORANGE, lw=1.4, ls="--", ms=11)
for (x, y) in [(2.6, 3.45), (3.75, 4.1), (6.45, 2.15), (7.25, 1.25)]:
    ax.add_patch(Rectangle((x - 0.33, y - 0.15), 0.66, 0.3, fc="none", ec=ORANGE, lw=1.3, zorder=5))
    ax.text(x + 0.17, y, "B", ha="center", va="center", fontsize=10, color=ORANGE, zorder=6)
    ax.plot([x + 0.01, x + 0.01], [y - 0.15, y + 0.15], color=ORANGE, lw=1.0, zorder=5)
ax.text(1.0, 1.9, "목적지 주소 B를\n헤더에 단 패킷", fontsize=10, color=ORANGE, ha="center")
# 스위치 2의 포워딩 테이블
tx, ty = 8.6, 4.9
ax.text(tx + 0.7, ty + 0.25, "S2의 포워딩 테이블", fontsize=10, color=BLUE, ha="center")
ax.text(tx + 0.3, ty - 0.1, "목적지", fontsize=10, ha="center")
ax.text(tx + 1.1, ty - 0.1, "포트", fontsize=10, ha="center")
ax.plot([tx - 0.1, tx + 1.5], [ty - 0.27, ty - 0.27], color=INK, lw=0.8)
for i, (h, p) in enumerate(S2_TABLE):
    y = ty - 0.55 - i * 0.36
    col = ORANGE if h == "B" else INK
    ax.text(tx + 0.3, y, h, fontsize=10, ha="center", color=col)
    ax.text(tx + 1.1, y, str(p), fontsize=10, ha="center", color=col)
ax.set_xlim(-0.2, 10.3)
ax.set_ylim(-0.6, 5.6)
save(fig, 1)


if __name__ == "__main__":
    # 그림의 S2 테이블은 토폴로지에서 구한 다음 포트와 같다.
    assert all(next_port("S2", h) == p for h, p in S2_TABLE)
    # 패킷 B의 길: S1은 1번, S2는 0번, S3은 3번 포트
    assert (next_port("S1", "B"), next_port("S2", "B"), next_port("S3", "B")) == (1, 0, 3)
    # 카드 C2: S3의 테이블
    s3 = {h: next_port("S3", h) for h in HOSTS}
    assert s3 == {"A": 0, "C": 0, "D": 0, "E": 0, "F": 0, "B": 3, "G": 1, "H": 2}
    # S1의 테이블(본문 예시)
    s1 = {h: next_port("S1", h) for h in HOSTS}
    assert s1 == {"D": 0, "A": 2, "C": 3, "B": 1, "E": 1, "F": 1, "G": 1, "H": 1}
    print("ALL CHECKS PASSED")