스위치와 확장성 있는 네트워크 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 스위치와 확장성 있는 네트워크 문서의 그림을 만든다: 77_switch-scalable-network_fig1.svg, _fig2.svg
# 실행: ~/.venvs/vault-plots/bin/python 77_switch-scalable-network_plot.py (matplotlib, numpy 필요)
#
# fig1: 스위치를 두 가지로 본 그림. 왼쪽은 포트만 보는 모델(입력 포트 -> 출력 포트),
# 오른쪽은 범용 컴퓨터로 만든 스위치 안에서 패킷 하나가 지나가는 길(저장 후 전달).
# fig2: 호스트 수에 따른 호스트 한 대의 몫. 모든 호스트가 동시에 쉬지 않고 보내고, 받는 쪽은 서로 다르다고 둔다.
# 공유 링크(100 Mbps 하나를 나눠 씀): 100 / n. MAC 오버헤드·충돌은 무시하므로 위쪽 한계다.
# 스위치(포트마다 100 Mbps, 스위치 전체 400 Mbps): min(100, 400 / n).
PREFIX = "77_switch-scalable-network"
import os
import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
import numpy as np
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,
})
LINK = 100.0 # 링크(포트) 하나의 전송률, Mbps
CAP = 400.0 # 스위치 전체가 동시에 넘길 수 있는 양, Mbps (800 Mbps 버스의 절반)
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, style="-|>", rad=0.0):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle=style, mutation_scale=ms, color=color, lw=lw, ls=ls,
shrinkA=0, shrinkB=0, connectionstyle=f"arc3,rad={rad}"))
def box(ax, x, y, w, h, text, color=INK, fs=10, lw=1.4, fc="none"):
ax.add_patch(Rectangle((x, y), w, h, fill=fc != "none", facecolor=fc, edgecolor=color, lw=lw))
if text:
ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", color=color, fontsize=fs)
def shared_share(n):
return LINK / n
def switch_share(n):
return min(LINK, CAP / n)
def fig1():
fig, (a, b) = plt.subplots(1, 2, figsize=(7.6, 3.4), gridspec_kw={"width_ratios": [1, 1.15]})
for ax in (a, b):
ax.set_axis_off()
ax.set_aspect("equal")
# 왼쪽: 포트만 보는 모델
a.set_xlim(0, 6.2)
a.set_ylim(-0.5, 5.0)
box(a, 2.0, 0.7, 2.2, 3.0, "", color=BLUE, lw=1.6)
a.text(3.6, 3.45, "스위치", ha="center", va="center", color=BLUE, fontsize=11)
names = ["T3", "T3", "STS-1"]
ys = [3.1, 2.2, 1.3]
for nm, y in zip(names, ys):
arrow(a, (0.75, y), (2.0, y), color=INK, lw=1.2)
a.text(0.7, y, nm, ha="right", va="center", fontsize=9.5)
arrow(a, (4.2, y), (5.45, y), color=INK, lw=1.2)
a.text(5.5, y, nm, ha="left", va="center", fontsize=9.5)
arrow(a, (2.05, 3.1), (4.15, 1.3), color=ORANGE, lw=1.8) # 들어온 패킷이 다른 출력 포트로 나감
a.text(1.35, 0.25, "입력 포트", ha="center", va="center", fontsize=10)
a.text(4.85, 0.25, "출력 포트", ha="center", va="center", fontsize=10)
a.text(3.1, 4.4, "모델: 포트에서 포트로", ha="center", va="center", fontsize=10.5)
# 오른쪽: 범용 컴퓨터로 만든 스위치 안
b.set_xlim(0, 7.4)
b.set_ylim(-0.5, 5.0)
box(b, 0.3, 2.6, 1.6, 1.1, "CPU", color=INK)
box(b, 0.3, 0.2, 1.6, 1.1, "메모리", color=INK)
b.add_patch(Rectangle((3.0, 0.0), 0.5, 3.9, fill=False, edgecolor=INK, lw=1.2))
b.text(3.25, -0.12, "I/O 버스", ha="center", va="top", fontsize=9.5)
iy = [3.2, 1.9, 0.6]
for k, y in enumerate(iy, start=1):
box(b, 4.4, y - 0.35, 2.1, 0.7, f"인터페이스 {k}", color=INK, fs=9.5)
b.plot([3.5, 4.4], [y, y], color=INK, lw=1.0)
b.plot([1.9, 3.0], [3.15, 3.15], color=INK, lw=1.0)
b.plot([1.9, 3.0], [0.75, 0.75], color=INK, lw=1.0)
# 1) 인터페이스 1 -> 버스 -> 메모리 (저장)
arrow(b, (4.4, 3.05), (1.95, 0.95), color=BLUE, lw=1.6, rad=0.15)
b.text(2.25, 2.35, "1 저장", ha="center", va="center", color=BLUE, fontsize=9.5)
# 2) 헤더를 CPU가 읽고 출력 포트를 정한다
arrow(b, (1.0, 1.3), (1.0, 2.6), color=PURPLE, lw=1.6)
b.text(0.9, 1.95, "2 헤더 보고\n포트 결정", ha="right", va="center", color=PURPLE, fontsize=9.5)
# 3) 메모리 -> 버스 -> 인터페이스 2 (전달)
arrow(b, (1.95, 0.45), (4.4, 1.75), color=ORANGE, lw=1.6, rad=0.25)
b.text(2.2, 0.12, "3 전달", ha="center", va="center", color=ORANGE, fontsize=9.5)
b.text(3.5, 4.75, "실제: 범용 컴퓨터 안", ha="center", va="center", fontsize=10.5)
save(fig, 1)
def fig2():
n = np.arange(1, 17)
sh = np.array([shared_share(k) for k in n])
sw = np.array([switch_share(k) for k in n])
fig, ax = plt.subplots(figsize=(7.0, 3.6))
ax.plot(n, sw, "-o", color=BLUE, lw=2.0, ms=4)
ax.plot(n, sh, "-o", color=ORANGE, lw=2.0, ms=4)
ax.axvline(4, color=INK, lw=0.8, ls=":")
ax.text(4.2, 104, "n = 4: 스위치 전체 400 Mbps를 다 씀", fontsize=9.5, va="bottom")
ax.text(9.0, 52, "스위치: 포트마다 100 Mbps,\n전체 400 Mbps까지", color=BLUE, fontsize=10)
ax.text(6.4, 4, "공유 링크 100 Mbps 하나", color=ORANGE, fontsize=10)
ax.annotate("25", (16, 25), (14.6, 34), color=BLUE, fontsize=9.5, arrowprops=dict(arrowstyle="-", color=BLUE))
ax.annotate("6.25", (16, 6.25), (14.4, 17), color=ORANGE, fontsize=9.5,
arrowprops=dict(arrowstyle="-", color=ORANGE))
ax.set_xlim(0.5, 16.8)
ax.set_ylim(0, 118)
ax.set_xticks([1, 2, 4, 8, 12, 16])
ax.set_xlabel("동시에 보내는 호스트 수 n")
ax.set_ylabel("호스트 한 대의 몫 (Mbps)")
save(fig, 2)
if __name__ == "__main__":
fig1()
fig2()
# 그림 2의 값: n = 1, 2, 4에서 스위치는 100, 공유 링크는 100, 50, 25
assert [switch_share(k) for k in (1, 2, 4)] == [100.0, 100.0, 100.0]
assert [shared_share(k) for k in (1, 2, 4)] == [100.0, 50.0, 25.0]
# n = 5부터 스위치 몫이 줄어든다: 400 / 5 = 80
assert switch_share(5) == 80.0 and switch_share(8) == 50.0
# n = 16: 스위치 25, 공유 6.25. n >= 4에서는 늘 4배 차이(= 400 / 100)
assert switch_share(16) == 25.0 and shared_share(16) == 6.25
assert all(abs(switch_share(k) / shared_share(k) - 4.0) < 1e-12 for k in range(4, 17))
# 스위치 전체 몫 = 링크 수 x 몫은 400을 넘지 않는다
assert all(k * switch_share(k) <= CAP + 1e-9 for k in range(1, 17))
# 400 Mbps = 800 Mbps 버스의 절반
assert CAP == 800.0 / 2
print("ALL CHECKS PASSED")