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

# 소스 라우팅 문서의 그림을 만든다: 81_source-routing_fig1.svg, fig2.svg
# 실행: ~/.venvs/vault-plots/bin/python 81_source-routing_plot.py  (matplotlib 필요)
PREFIX = "81_source-routing"
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 rotate(h, ptr):
    return h[-1], [h[-1]] + h[:-1], ptr


def strip(h, ptr):
    return h[-1], h[:-1], ptr


def pointer(h, ptr):
    return h[ptr], h, ptr - 1


def run(method, header=(3, 0, 1)):
    """스위치 S1, S2, S3가 차례로 받은 (헤더, 포인터, 나간 포트)."""
    h, ptr, out = list(header), len(header) - 1, []
    for _ in range(3):
        got = (list(h), ptr)
        port, h, ptr = method(h, ptr)
        out.append((got[0], got[1], port))
    return out


def cells(ax, x, y, vals, read=None, w=0.36, h=0.32, size=10.5, ptr=None):
    """헤더 칸들을 그린다. read 번째 칸(스위치가 읽는 칸)을 주황으로 칠한다."""
    for i, v in enumerate(vals):
        col = ORANGE if i == read else INK
        ax.add_patch(Rectangle((x + i * w, y - h / 2), w, h, fc="none", ec=col, lw=1.4 if i == read else 1.0, zorder=5))
        ax.text(x + i * w + w / 2, y, str(v), ha="center", va="center", fontsize=size, color=col, zorder=6)
    if ptr is not None:
        arrow(ax, (x + ptr * w + w / 2, y - h / 2 - 0.32), (x + ptr * w + w / 2, y - h / 2 - 0.02), color=PURPLE,
              lw=1.3, ms=10)


# 그림 1: A -> B, 회전 방식
rot = run(rotate)
fig, ax = plt.subplots(figsize=(7.4, 4.6))
ax.set_aspect("equal")
ax.axis("off")
draw_topology(ax, hl_hosts=("A", "B"))
for (x, y), (h, _, _) in zip([(0.45, 3.5), (3.2, 4.25), (6.2, 2.15)], rot):
    cells(ax, x, y, h, read=len(h) - 1)
for (x1, y1), (x2, y2) in [((2.12, 3.0), (2.12, 3.92)), ((2.4, 4.32), (5.04, 3.12)), ((5.32, 2.72), (6.72, 1.08)),
                           ((6.88, 0.92), (7.43, 0.92))]:
    arrow(ax, (x1, y1), (x2, y2), color=ORANGE, lw=1.4, ls="--", ms=11)
ax.text(0.15, 2.95, "S1이 받은 헤더", fontsize=10, color=INK)
ax.text(3.0, 4.75, "S2가 받은 헤더", fontsize=10, color=INK)
ax.text(7.35, 2.15, "S3이 받은\n헤더", fontsize=10, color=INK, va="center")
ax.set_xlim(-0.2, 8.8)
ax.set_ylim(-0.6, 5.6)
save(fig, 1)

# 그림 2: 세 가지 처리 방식
fig, ax = plt.subplots(figsize=(7.2, 3.4))
ax.axis("off")
rows = [("회전", rotate), ("제거", strip), ("포인터", pointer)]
for j, sw in enumerate(["S1이 받은 헤더", "S2가 받은 헤더", "S3이 받은 헤더"]):
    ax.text(2.3 + j * 2.0, 3.55, sw, ha="center", fontsize=10)
for i, (name, m) in enumerate(rows):
    y = 2.7 - i * 1.05
    ax.text(0.2, y, name, fontsize=10.5, va="center", color=BLUE)
    for j, (h, ptr, _) in enumerate(run(m)):
        read = ptr if m is pointer else len(h) - 1
        x0 = 2.3 + j * 2.0 - len(h) * 0.36 / 2
        cells(ax, x0, y, h, read=read, ptr=ptr if m is pointer else None)
ax.set_xlim(0, 7.4)
ax.set_ylim(0.2, 3.85)
save(fig, 2)


if __name__ == "__main__":
    assert [r[0] for r in rot] == [[3, 0, 1], [1, 3, 0], [0, 1, 3]] and [r[2] for r in rot] == [1, 0, 3]
    assert [r[0] for r in run(strip)] == [[3, 0, 1], [3, 0], [3]] and [r[2] for r in run(strip)] == [1, 0, 3]
    pt = run(pointer)
    assert all(r[0] == [3, 0, 1] for r in pt) and [r[1] for r in pt] == [2, 1, 0] and [r[2] for r in pt] == [1, 0, 3]
    print("ALL CHECKS PASSED")