브리지와 확장 LAN 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 브리지와 확장 LAN 문서의 그림을 만든다: 83_bridge-extended-lan_fig1.svg, 83_bridge-extended-lan_fig2.svg
# fig1: 브리지로 이은 두 LAN에서 프레임이 지나는 여덟 순간(t1~t8)과 그때의 프레임 모양
# fig2: 같은 순간에 1->3, 11->13 두 전송이 있을 때 리피터와 브리지에서 각 LAN에 실리는 프레임
# 실행: ~/.venvs/vault-plots/bin/python -I 83_bridge-extended-lan_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 FancyArrowPatch, Rectangle, Ellipse
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "83_bridge-extended-lan"
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 arrow(ax, p, q, color=INK, lw=1.2, ls="-"):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=10, color=color, lw=lw, ls=ls,
shrinkA=0, shrinkB=0))
def box(ax, x, y, w, h, text, color=INK, fill="none", fs=10, tc=None):
ax.add_patch(Rectangle((x, y), w, h, fill=fill != "none", facecolor=fill, edgecolor=color, lw=1.1))
ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=fs, color=tc or color)
# ---------------------------------------------------------------
# fig1의 모델: 위에서 아래로 내려갈 때 붙이는 헤더, 브리지는 MAC까지만 올라갔다 내려간다
# ---------------------------------------------------------------
LAYERS = ["USER", "LLC", "MAC", "PHY"]
def frame_at(layer_above_link):
"""경계(그 층 아래)를 지나는 순간의 프레임 모양"""
if layer_above_link == "USER":
return ["User data"]
if layer_above_link == "LLC":
return ["LLC-H", "User data"]
return ["MAC-H", "LLC-H", "User data", "MAC-T"]
# 순간 -> 어느 경계인가(그 위 층 이름)
MOMENTS = {"t1": "USER", "t2": "LLC", "t3": "MAC", "t4": "MAC", "t5": "MAC", "t6": "MAC", "t7": "LLC", "t8": "USER"}
def fig1():
fig, ax = plt.subplots(figsize=(7.8, 5.0))
ax.set_xlim(0, 100)
ax.set_ylim(0, 64)
ax.set_ylim(9, 63)
ax.axis("off")
h = 4.2
top = 60
# 송신 스테이션
for i, name in enumerate(LAYERS):
box(ax, 3, top - (i + 1) * h, 13, h, name, color=BLUE)
ax.text(9.5, top + 1.2, "보내는 스테이션", ha="center", fontsize=10)
for i, name in enumerate(LAYERS):
box(ax, 84, top - (i + 1) * h, 13, h, name, color=BLUE)
ax.text(90.5, top + 1.2, "받는 스테이션", ha="center", fontsize=10)
# 브리지: MAC 한 칸, PHY 두 칸
by = top - 4 * h
box(ax, 42, by + h, 16, h, "MAC", color=ORANGE)
box(ax, 42, by, 8, h, "PHY", color=ORANGE)
box(ax, 50, by, 8, h, "PHY", color=ORANGE)
ax.text(50, by + 2 * h + 1.2, "브리지", ha="center", fontsize=10, color=ORANGE)
# LAN 구름
for cx in (29, 71):
ax.add_patch(Ellipse((cx, by + h / 2), 14, 6, fill=False, edgecolor=INK, lw=1.1))
ax.text(cx, by + h / 2, "LAN", ha="center", va="center")
ax.plot([16, 22], [by + h / 2] * 2, color=INK, lw=1.1)
ax.plot([36, 42], [by + h / 2] * 2, color=INK, lw=1.1)
ax.plot([58, 64], [by + h / 2] * 2, color=INK, lw=1.1)
ax.plot([78, 84], [by + h / 2] * 2, color=INK, lw=1.1)
# 순간 표시: 송신 쪽 t1~t3(층 경계), 브리지 t4, t5, 수신 쪽 t6~t8
for i, t in enumerate(["t1", "t2", "t3"]):
ax.text(17.2, top - (i + 1) * h, t, fontsize=10, va="center", color=GREEN)
for i, t in enumerate(["t8", "t7", "t6"]):
ax.text(80.8, top - (i + 1) * h, t, fontsize=10, va="center", ha="right", color=GREEN)
ax.text(39.5, by + h / 2 + 1.6, "t4", fontsize=10, ha="center", color=GREEN)
ax.text(60.5, by + h / 2 + 1.6, "t5", fontsize=10, ha="center", color=GREEN)
# 아래: 순간별 프레임 모양
rows = [("t1, t8", "USER"), ("t2, t7", "LLC"), ("t3, t4, t5, t6", "MAC")]
widths = {"User data": 16, "LLC-H": 10, "MAC-H": 10, "MAC-T": 10}
fills = {"User data": BLUE, "LLC-H": GREEN, "MAC-H": ORANGE, "MAC-T": ORANGE}
y = 30
for label, layer in rows:
parts = frame_at(layer)
total = sum(widths[p] for p in parts)
x = 82 - total
ax.text(8, y + 1.6, label, fontsize=10, va="center", color=GREEN)
for p in parts:
box(ax, x, y, widths[p], 3.2, p, color=fills[p], fs=9.5)
x += widths[p]
y -= 6.5
ax.text(50, 12, "브리지를 지나기 전(t4)과 지난 뒤(t5)의 프레임은 똑같다", ha="center", fontsize=10, color=ORANGE)
save(fig, 1)
return {t: frame_at(l) for t, l in MOMENTS.items()}
# ---------------------------------------------------------------
# fig2의 모델: 두 LAN, 1->3과 11->13이 같은 순간 출발
# ---------------------------------------------------------------
LAN_OF = {1: "A", 2: "A", 3: "A", 11: "B", 12: "B", 13: "B"}
LAN_OF_ALL = {k: ("A" if k <= 10 else "B") for k in range(1, 21)} # 카드 C2: 1~10은 LAN A, 11~20은 LAN B
SENDS = [(1, 3), (11, 13)]
def carried(device, sends=SENDS, lan_of=LAN_OF):
"""각 LAN에 실리는 프레임 목록. 리피터는 비트를 그대로 넘기고, 브리지는 목적지가 다른 쪽일 때만 넘긴다."""
on = {"A": [], "B": []}
for s, d in sends:
home, other = lan_of[s], ("B" if lan_of[s] == "A" else "A")
on[home].append(f"{s}→{d}")
if device == "repeater" or lan_of[d] != home:
on[other].append(f"{s}→{d}")
return on
def fig2():
fig, axes = plt.subplots(1, 2, figsize=(7.8, 3.6))
result = {}
for ax, device, title in zip(axes, ["repeater", "bridge"], ["리피터로 이었을 때", "브리지로 이었을 때"]):
on = carried(device)
result[device] = on
ax.set_xlim(0, 50)
ax.set_ylim(0, 40)
ax.axis("off")
ax.set_title(title, fontsize=10.5, color=INK)
for lan, y in (("A", 30), ("B", 10)):
ax.plot([3, 47], [y, y], color=INK, lw=2)
ax.text(1.5, y, f"LAN {lan}", ha="right", va="center", fontsize=10)
for i, st in enumerate([s for s, l in LAN_OF.items() if l == lan]):
x = 8 + i * 11
ax.plot([x, x], [y, y + 3], color=INK, lw=1)
box(ax, x - 3.5, y + 3, 7, 3.4, str(st), fs=9.5)
frames = on[lan]
col = ORANGE if len(frames) > 1 else BLUE
txt = " + ".join(frames)
ax.text(25, y - 3.2, txt, ha="center", fontsize=10, color=col)
if len(frames) > 1:
ax.text(25, y - 6.6, "한 선을 둘이 나눠 써야 한다", ha="center", fontsize=10, color=ORANGE)
dev = "R" if device == "repeater" else "B"
box(ax, 42, 17, 5, 6, dev, color=PURPLE, fs=10)
ax.plot([44.5, 44.5], [23, 30], color=PURPLE, lw=1.2)
ax.plot([44.5, 44.5], [10, 17], color=PURPLE, lw=1.2)
save(fig, 2)
return result
if __name__ == "__main__":
f1 = fig1()
assert f1["t4"] == f1["t5"] == f1["t3"] == f1["t6"] == ["MAC-H", "LLC-H", "User data", "MAC-T"]
assert f1["t1"] == f1["t8"] == ["User data"] and f1["t2"] == f1["t7"] == ["LLC-H", "User data"]
f2 = fig2()
assert f2["repeater"] == {"A": ["1→3", "11→13"], "B": ["1→3", "11→13"]}
assert f2["bridge"] == {"A": ["1→3"], "B": ["11→13"]}
c2 = [(2, 7), (12, 15), (3, 18)]
assert carried("bridge", c2, LAN_OF_ALL) == {"A": ["2→7", "3→18"], "B": ["12→15", "3→18"]}
assert carried("repeater", c2, LAN_OF_ALL) == {"A": ["2→7", "12→15", "3→18"], "B": ["2→7", "12→15", "3→18"]}
print("카드 C2:", carried("bridge", c2, LAN_OF_ALL))
print("fig1: 브리지 전후(t4, t5) 프레임 같음 / fig2: 리피터는 두 LAN 모두 2개, 브리지는 1개씩")
print("ALL CHECKS PASSED")