학습 브리지 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 학습 브리지 문서의 그림을 만든다: 84_learning-bridge_fig1.svg
# 포트 6개짜리 스위치(포트마다 호스트 하나)에서 A->A'(목적지를 몰라 flood)와 A'->A(아는 포트 하나로만)를 나란히 그린다.
# 그림 속 동작과 표는 아래 LearningBridge가 계산한 값이다(84_learning-bridge_impl.py와 같은 규칙을 복사해 씀).
# 실행: ~/.venvs/vault-plots/bin/python -I 84_learning-bridge_plot.py  (matplotlib, numpy 필요)
import math
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__))
PREFIX = "84_learning-bridge"
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,
    "text.color": INK, "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
})


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)


class LearningBridge:
    def __init__(self, ports, ttl=60):
        self.ports, self.ttl, self.table = list(ports), ttl, {}

    def receive(self, src, dst, in_port, now):
        for a in [a for a, (_, e) in self.table.items() if e <= now]:
            del self.table[a]
        self.table[src] = [in_port, now + self.ttl]
        others = [p for p in self.ports if p != in_port]
        if dst not in self.table:
            return others, "flood"
        p = self.table[dst][0]
        return ([], "filter") if p == in_port else ([p], "forward")


HOME = {"A": 1, "B": 2, "C": 3, "A'": 4, "B'": 5, "C'": 6}
NAME = {p: h for h, p in HOME.items()}


def pos(port, r=1.0):
    ang = math.radians(90 - (port - 1) * 60)          # 포트 1이 위, 시계 방향으로 2, 3, ...
    return r * math.cos(ang), r * math.sin(ang)


def panel(ax, title, src, dst, out, table):
    ax.set_xlim(-1.75, 1.75)
    ax.set_ylim(-2.55, 1.45)
    ax.set_aspect("equal")
    ax.axis("off")
    ax.set_title(title, fontsize=10.5, color=INK)
    ax.add_patch(Rectangle((-0.27, -0.17), 0.54, 0.34, fill=False, edgecolor=PURPLE, lw=1.3))
    ax.text(0, 0, "스위치", ha="center", va="center", fontsize=9.5, color=PURPLE)
    for port in range(1, 7):
        x, y = pos(port, 1.05)
        h = NAME[port]
        col = ORANGE if h == src else (GREEN if h == dst else INK)
        ax.add_patch(Rectangle((x - 0.2, y - 0.14), 0.4, 0.28, fill=False, edgecolor=col, lw=1.2))
        ax.text(x, y, h, ha="center", va="center", fontsize=10, color=col)
        x0, y0 = pos(port, 0.3)
        x1, y1 = pos(port, 0.86)
        ax.plot([x0, x1], [y0, y1], color=INK, lw=0.8)
        xm, ym = pos(port, 0.5)
        lx, ly = pos(port + 0.5, 0.42)
        ax.text(xm + 0.6 * (lx - xm), ym + 0.6 * (ly - ym), str(port), fontsize=9.5, ha="center", va="center",
                color=INK)
        if port == HOME[src]:
            ax.add_patch(FancyArrowPatch(pos(port, 0.86), pos(port, 0.3), arrowstyle="-|>", mutation_scale=10,
                                         color=ORANGE, lw=1.8))
        if port in out:
            ax.add_patch(FancyArrowPatch(pos(port, 0.3), pos(port, 0.86), arrowstyle="-|>", mutation_scale=10,
                                         color=BLUE, lw=1.8))
    # 아래에 스위치 표
    ax.text(0, -1.5, "주소  포트  TTL", ha="center", fontsize=10, color=INK)
    for i, (a, (p, e)) in enumerate(sorted(table.items())):
        ax.text(0, -1.82 - 0.3 * i, f"{a:<3}   {p}    {e}", ha="center", fontsize=10, color=GREEN)


def main():
    br = LearningBridge(range(1, 7))
    out1, act1 = br.receive("A", "A'", HOME["A"], 0)
    tab1 = {a: tuple(v) for a, v in br.table.items()}
    out2, act2 = br.receive("A'", "A", HOME["A'"], 0)
    tab2 = {a: tuple(v) for a, v in br.table.items()}
    fig, axes = plt.subplots(1, 2, figsize=(7.4, 4.3))
    panel(axes[0], "① A가 A'에게: A'를 모른다", "A", "A'", out1, tab1)
    panel(axes[1], "② A'가 A에게: A는 포트 1", "A'", "A", out2, tab2)
    save(fig, 1)
    return (out1, act1, tab1), (out2, act2, tab2)


if __name__ == "__main__":
    s1, s2 = main()
    assert s1 == ([2, 3, 4, 5, 6], "flood", {"A": (1, 60)})
    assert s2 == ([1], "forward", {"A": (1, 60), "A'": (4, 60)})
    print("①", s1)
    print("②", s2)
    print("ALL CHECKS PASSED")