가상 회선 스위칭 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 가상 회선 스위칭 문서의 그림을 만든다: 79_virtual-circuit_fig1.svg
# 실행: ~/.venvs/vault-plots/bin/python 79_virtual-circuit_plot.py (matplotlib 필요)
PREFIX = "79_virtual-circuit"
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)
# 가상 회선 A -> B. 링크마다 뒤 노드가 고른 VCI와 스위치마다의 VC 테이블 한 줄
LINK_VCI = [("A", "S1", 5), ("S1", "S2", 11), ("S2", "S3", 7), ("S3", "B", 4)]
TABLES = {"S1": (2, 5, 1, 11), "S2": (3, 11, 0, 7), "S3": (0, 7, 3, 4)}
def simulate():
"""테이블만 보고 패킷을 따라가며 링크마다 헤더의 VCI를 적는다."""
peer = {("S1", 1): ("S2", 3), ("S2", 0): ("S3", 0), ("S3", 3): ("B", 0)}
node, in_port, vci, seen = "S1", 2, 5, [5]
while node != "B":
ip, iv, op, ov = TABLES[node]
assert (ip, iv) == (in_port, vci)
node, in_port = peer[(node, op)]
vci = ov
seen.append(vci)
return seen
fig, ax = plt.subplots(figsize=(7.6, 4.6))
ax.set_aspect("equal")
ax.axis("off")
draw_topology(ax, hl_hosts=("A", "B"))
for (x, y), (_, _, v) in zip([(2.6, 3.45), (3.75, 4.1), (6.45, 2.15), (7.25, 1.25)], LINK_VCI):
ax.add_patch(Rectangle((x - 0.33, y - 0.15), 0.66, 0.3, fc="none", ec=ORANGE, lw=1.3, zorder=5))
ax.plot([x + 0.01, x + 0.01], [y - 0.15, y + 0.15], color=ORANGE, lw=1.0, zorder=5)
ax.text(x + 0.17, y, str(v), ha="center", va="center", fontsize=10, color=ORANGE, zorder=6)
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.9, 1.9, "헤더에는 주소 대신\n그 링크의 VCI", fontsize=10, color=ORANGE, ha="center")
# VC 테이블
tx, ty = 8.35, 5.2
cols = ["들어온\n포트", "VCI", "나갈\n포트", "나갈\nVCI"]
for k, sw in enumerate(["S1", "S2", "S3"]):
y0 = ty - k * 1.75
ax.text(tx - 0.35, y0 - 0.55, sw, fontsize=10.5, color=BLUE, ha="center", va="center")
for j, c in enumerate(cols):
ax.text(tx + 0.2 + j * 0.66, y0 - 0.25, c, fontsize=9.5, ha="center", va="center", linespacing=0.95)
ax.plot([tx - 0.05, tx + 2.45], [y0 - 0.62, y0 - 0.62], color=INK, lw=0.8)
for j, v in enumerate(TABLES[sw]):
ax.text(tx + 0.2 + j * 0.66, y0 - 0.9, str(v), fontsize=10, ha="center", va="center",
color=ORANGE if j in (1, 3) else INK)
ax.set_xlim(-0.2, 11.0)
ax.set_ylim(-0.6, 5.6)
save(fig, 1)
if __name__ == "__main__":
assert simulate() == [v for _, _, v in LINK_VCI] == [5, 11, 7, 4]
# 앞 스위치의 '나갈 VCI'는 다음 스위치의 '들어온 VCI'와 같다
assert TABLES["S1"][3] == TABLES["S2"][1] and TABLES["S2"][3] == TABLES["S3"][1]
print("ALL CHECKS PASSED")