토큰링과 FDDI 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 토큰링과 FDDI 문서의 그림을 만든다: 68_token-ring_fig1.svg(토큰과 프레임이 링을 도는 세 순간),
# 68_token-ring_fig2.svg(토큰링 프레임과 이더넷 프레임의 칸 비교, 칸 폭은 비트 수에 비례하되 최소 폭을 둔다).
# 실행: ~/.venvs/vault-plots/bin/python -I 68_token-ring_plot.py (matplotlib, numpy 필요)
PREFIX = "68_token-ring"
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, Circle, Polygon
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.2, style="-|>", ls="-", ms=10):
ax.add_patch(FancyArrowPatch(p, q_, arrowstyle=style, mutation_scale=ms, color=color, lw=lw, ls=ls,
shrinkA=0, shrinkB=0))
def steps(ax, vals, y0, color, scale=0.35, lw=1.8):
"""칩(또는 비트) 값 목록을 계단 파형으로 그린다. 칸 하나의 폭은 1."""
xs, ys = [], []
for i, v in enumerate(vals):
xs += [i, i + 1]
ys += [y0 + v * scale, y0 + v * scale]
ax.plot(xs, ys, color=color, lw=lw, solid_joinstyle="miter")
ax.plot([0, len(vals)], [y0, y0], color=INK, lw=0.6, ls=":")
# 링 위의 지국: 반시계 방향으로 A(위) -> B(왼쪽) -> C(아래) -> D(오른쪽) -> A
ANG = {"A": 90, "B": 180, "C": 270, "D": 360}
ORDER = ["A", "B", "C", "D"]
def pos(deg, r=1.0):
t = np.deg2rad(deg)
return r * np.cos(t), r * np.sin(t)
def arc(ax, a0, a1, color, r=1.0, lw=3.0, head=True, label=None, lr=0.72):
ts = np.linspace(a0, a1, 60)
xs, ys = zip(*[pos(t, r) for t in ts])
ax.plot(xs, ys, color=color, lw=lw, solid_capstyle="round")
if head:
arrow(ax, pos(a1 - 6, r), pos(a1, r), color=color, lw=lw, ms=14)
if label:
x, y = pos((a0 + a1) / 2, lr)
ax.text(x, y, label, ha="center", va="center", fontsize=9.5, color=color)
def ring(ax, title, holder=None):
ax.add_patch(Circle((0, 0), 1.0, fill=False, ec=INK, lw=1.2))
for s in ORDER:
x, y = pos(ANG[s], 1.0)
ax.add_patch(Rectangle((x - 0.13, y - 0.13), 0.26, 0.26, color="#dddddd" if s != holder else GOLD,
ec=INK, lw=1, zorder=3))
lx, ly = pos(ANG[s], 1.33)
ax.text(lx, ly, s, ha="center", va="center", fontsize=11, fontweight="bold")
ax.set_xlim(-1.55, 1.55); ax.set_ylim(-1.6, 1.55)
ax.set_aspect("equal"); ax.axis("off")
ax.set_title(title, fontsize=10, color=INK)
def fig1():
fig, axs = plt.subplots(1, 3, figsize=(7.7, 3.0))
ring(axs[0], "(가) A는 보낼 것이 없어\n토큰을 B로 넘긴다")
arc(axs[0], 100, 170, PURPLE, label="토큰")
ring(axs[1], "(나) C가 토큰을 잡고\nA에게 프레임을 보낸다", holder="C")
arc(axs[1], 280, 440, BLUE, label="프레임", lr=0.6)
axs[1].text(0, 0.62, "A가 복사", ha="center", fontsize=9.5, color=BLUE)
ring(axs[2], "(다) 한 바퀴 돈 프레임을 C가 지우고\n토큰을 D로 넘긴다")
arc(axs[2], 190, 262, BLUE, label="프레임 복귀", lr=0.55)
arc(axs[2], 280, 350, PURPLE, label="토큰")
fig.tight_layout()
save(fig, 1)
TR = [("시작\n구분자", 8), ("접근\n제어", 8), ("프레임\n제어", 8), ("받는 쪽\n주소", 48), ("보낸 쪽\n주소", 48),
("데이터", 80), ("체크섬", 32), ("끝\n구분자", 8), ("프레임\n상태", 8)]
ETH = [("프리앰블", 64), ("받는 쪽\n주소", 48), ("보낸 쪽\n주소", 48), ("종류", 16), ("데이터", 80), ("CRC", 32)]
EXTRA = {"접근\n제어", "프레임\n제어", "프레임\n상태"}
COMMON = {"받는 쪽\n주소", "보낸 쪽\n주소", "체크섬", "CRC"}
def bar(ax, fields, y, scale):
x = 0.0
for name, bits in fields:
w = max(bits, 38) * scale # 8비트 칸도 글씨가 들어가게 최소 폭을 둔다
col = ORANGE if name in EXTRA else (BLUE if name in COMMON else "#bbbbbb")
ax.add_patch(Rectangle((x, y), w, 1, facecolor=col, alpha=0.55, ec=INK, lw=0.8))
ax.text(x + w / 2, y + 0.5, name, ha="center", va="center", fontsize=9.5)
ax.text(x + w / 2, y - 0.12, "가변" if name == "데이터" else str(bits), ha="center", va="top", fontsize=9.5)
x += w
return x
def fig2():
fig, ax = plt.subplots(figsize=(7.7, 2.9))
s = 0.02
w1 = bar(ax, TR, 2.0, s)
w2 = bar(ax, ETH, 0.0, s)
ax.text(-0.05, 2.5, "토큰링", ha="right", va="center", fontsize=10.5)
ax.text(-0.05, 0.5, "이더넷", ha="right", va="center", fontsize=10.5)
ax.text(0, 3.25, "주황: 토큰링에만 있는 칸 파랑: 둘 다 있는 칸 숫자: 비트 수", fontsize=9.5)
ax.set_xlim(-0.9, max(w1, w2) + 0.1); ax.set_ylim(-0.6, 3.5)
ax.axis("off")
save(fig, 2)
if __name__ == "__main__":
fig1()
fig2()
assert sum(b for n, b in TR if n != "데이터") == 168 # 데이터 밖의 칸: 8*6 + 48*2 + 32 = 168비트
assert sum(b for n, b in ETH if n not in ("데이터", "프리앰블")) == 144
assert [ORDER[(ORDER.index("A") + k) % 4] for k in range(5)] == ["A", "B", "C", "D", "A"]
print("ALL CHECKS PASSED")