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

# 학습 브리지 추적 연습 문서의 그림을 만든다: 84_learning-bridge-practice_fig1.svg, 84_learning-bridge-practice_fig2.svg
# fig1: 문제 2의 연결 모양(포트 4개 스위치, 포트 1에는 허브로 A·B, 포트 2~4에 C·D·E)
# fig2: 문제 4의 연결 모양(LAN1 -B1- LAN2 -B2- LAN3, A·B·C가 한 LAN에 하나씩)
# 그림에는 연결 모양만 그린다. 표의 변화(답)는 그리지 않는다.
# 실행: ~/.venvs/vault-plots/bin/python -I 84_learning-bridge-practice_plot.py  (matplotlib, numpy 필요)
import os

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

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "84_learning-bridge-practice"
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)


def box(ax, x, y, w, h, text, color=INK, fs=10):
    ax.add_patch(Rectangle((x - w / 2, y - h / 2), w, h, fill=False, edgecolor=color, lw=1.2))
    ax.text(x, y, text, ha="center", va="center", fontsize=fs, color=color)


# 문제 2: 호스트 -> 스위치 포트
P2_HOME = {"A": 1, "B": 1, "C": 2, "D": 3, "E": 4}
# 문제 4: 브리지 -> [포트 1의 LAN, 포트 2의 LAN], 호스트 -> LAN
P4_BRIDGES = {"B1": ["LAN1", "LAN2"], "B2": ["LAN2", "LAN3"]}
P4_HOSTS = {"A": "LAN1", "B": "LAN2", "C": "LAN3"}


def fig1():
    fig, ax = plt.subplots(figsize=(6.4, 3.6))
    ax.set_xlim(0, 16)
    ax.set_ylim(0, 9)
    ax.axis("off")
    sw = (8, 4.5)
    box(ax, *sw, 2.4, 1.2, "스위치", PURPLE)
    # 포트 1: 허브와 A, B (왼쪽)
    hub = (3.6, 4.5)
    box(ax, *hub, 1.6, 0.9, "허브")
    ax.plot([hub[0] + 0.8, sw[0] - 1.2], [4.5, 4.5], color=INK, lw=1.1)
    ax.text(sw[0] - 1.45, 4.75, "1", fontsize=10, ha="center", color=PURPLE)
    for name, y in (("A", 7.2), ("B", 1.8)):
        box(ax, 1.2, y, 1.2, 0.9, name, BLUE)
        ax.plot([1.8, hub[0]], [y, 4.5 + (0.45 if y > 4.5 else -0.45)], color=INK, lw=1.0)
    # 포트 2~4: 오른쪽 위, 오른쪽, 오른쪽 아래
    spots = {2: (12.4, 7.6), 3: (13.6, 4.5), 4: (12.4, 1.4)}
    for h, p in P2_HOME.items():
        if p == 1:
            continue
        x, y = spots[p]
        box(ax, x, y, 1.2, 0.9, h, BLUE)
        sx, sy = sw[0] + 1.2, sw[1] + {2: 0.4, 3: 0.0, 4: -0.4}[p]
        ax.plot([sx, x - 0.6], [sy, y], color=INK, lw=1.0)
        ax.text(sx + 0.35, sy + {2: 0.45, 3: 0.2, 4: -0.6}[p], str(p), fontsize=10, color=PURPLE)
    save(fig, 1)


def fig2():
    fig, ax = plt.subplots(figsize=(7.2, 2.6))
    ax.set_xlim(0, 22)
    ax.set_ylim(0, 6)
    ax.axis("off")
    lan_x = {"LAN1": (0.6, 6.4), "LAN2": (8.0, 14.0), "LAN3": (15.6, 21.4)}
    y = 2.0
    for lan, (a, b) in lan_x.items():
        ax.plot([a, b], [y, y], color=INK, lw=2.2)
        ax.text((a + b) / 2, y - 0.7, lan, ha="center", fontsize=10)
    for h, lan in P4_HOSTS.items():
        a, b = lan_x[lan]
        x = (a + b) / 2
        ax.plot([x, x], [y, 3.4], color=INK, lw=1.0)
        box(ax, x, 3.85, 1.2, 0.9, h, BLUE)
    for br, (l1, l2) in P4_BRIDGES.items():
        x = (lan_x[l1][1] + lan_x[l2][0]) / 2
        box(ax, x, y, 1.3, 1.0, br, PURPLE)
        ax.plot([lan_x[l1][1], x - 0.65], [y, y], color=PURPLE, lw=1.2)
        ax.plot([x + 0.65, lan_x[l2][0]], [y, y], color=PURPLE, lw=1.2)
        ax.text(x - 0.95, y + 0.25, "1", fontsize=10, color=PURPLE, ha="center")
        ax.text(x + 0.95, y + 0.25, "2", fontsize=10, color=PURPLE, ha="center")
    save(fig, 2)


if __name__ == "__main__":
    fig1()
    fig2()
    # 그림의 연결 모양이 문제 코드(p2, p4)의 값과 같은지 확인한다
    assert P2_HOME == {"A": 1, "B": 1, "C": 2, "D": 3, "E": 4}
    assert P4_BRIDGES == {"B1": ["LAN1", "LAN2"], "B2": ["LAN2", "LAN3"]}
    assert P4_HOSTS == {"A": "LAN1", "B": "LAN2", "C": "LAN3"}
    print("ALL CHECKS PASSED")