순서 번호 공간 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 순서 번호 공간 문서의 그림을 만든다: 61_sequence-number-space_fig1.svg, fig2.svg
# fig1: 번호 0~3(N = 4), 창 3. 받는 쪽은 창 안의 순서 어긋난 프레임을 저장한다(RWS = 3).
# (가) ACK가 모두 사라져 옛 F0을 다시 보낸 경우, (나) ACK가 다 와서 새 프레임(실제 4번째, 번호 0)을 보낸 경우.
# 받는 쪽이 보는 사건은 두 경우가 똑같다.
# fig2: 번호 0~7(N = 8)을 원으로 놓고, 보낸 프레임을 모두 받았는데 ACK가 모두 사라진 순간에
# 보내는 쪽이 다시 보낼 수 있는 번호(안쪽 고리)와 받는 쪽 창(바깥 고리)을 겹쳐 본다. 왼쪽 창 7, 오른쪽 창 4.
# ACK 약속: 데이터 n까지 받으면 ACK n+1(60번 문서와 같다).
# 실행: ~/.venvs/vault-plots/bin/python -I 61_sequence-number-space_plot.py (matplotlib, numpy 필요)
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, Wedge
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "61_sequence-number-space"
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=10):
ax.add_patch(FancyArrowPatch(p, q_, arrowstyle="-|>", mutation_scale=ms, color=color, lw=lw, ls=ls,
shrinkA=0, shrinkB=0))
# ---------------------------------------------------------------------
# 받는 쪽 모형: 번호 mod N만 보고, 창(NFE..NFE+RWS-1) 안의 칸 중 그 번호와 맞는 칸의 프레임이라고 믿는다
# ---------------------------------------------------------------------
def believe(true_index, nfe, n, rws):
"""실제 일련번호 true_index인 프레임이 왔을 때 받는 쪽이 믿는 일련번호(창 밖이면 None)"""
pos = (true_index % n - nfe) % n
return nfe + pos if pos < rws else None
def window(nfe, n, rws):
return [(nfe + k) % n for k in range(rws)]
# fig1의 두 경우를 사건 목록으로 적는다. (시각, 종류, 번호표, 실제 일련번호, 사라짐)
N1, W1 = 4, 3
TP = 3 # 전파 시간(칸)
CASE_A = {"frames": [(0, 0, False), (1, 1, False), (2, 2, False), (10, 0, False)], # (보낸 시각, 실제 일련번호, 사라짐)
"acks_lost": True}
CASE_B = {"frames": [(0, 0, False), (1, 1, False), (2, 2, False), (6, 3, True), (7, 4, False)],
"acks_lost": False}
def receiver_view(case):
"""받는 쪽이 본 사건(번호표만)과, 마지막 프레임에 대해 믿은 일련번호를 돌려준다"""
nfe, seen, beliefs = 0, [], []
for t, a, lost in sorted(case["frames"], key=lambda x: x[0] + TP):
if lost:
continue
b = believe(a, nfe, N1, W1)
seen.append(("받음", a % N1))
beliefs.append((a, b))
if b == nfe:
nfe += 1
seen.append(("ACK", nfe % N1))
return seen, beliefs
def timeline(ax, case, title, tag):
XS, XR = 0.0, 3.0
T_END = 14
ax.plot([XS, XS], [0, -T_END], color=INK, lw=1.2)
ax.plot([XR, XR], [0, -T_END], color=INK, lw=1.2)
ax.text(XS, 0.9, "보내는 쪽", ha="center", va="bottom", fontsize=10.5, weight="bold")
ax.text(XR, 0.9, "받는 쪽", ha="center", va="bottom", fontsize=10.5, weight="bold")
ax.text((XS + XR) / 2, 2.2, title, ha="center", va="bottom", fontsize=10.5, linespacing=1.3)
nfe = 0
for t, a, lost in case["frames"]:
t1 = t + TP
lab = f"F{a % N1}"
if lost:
xm, ym = XS + (XR - XS) * 0.55, -(t + TP * 0.55)
ax.plot([XS, xm], [-t, ym], color=BLUE, lw=1.4)
ax.text(xm + 0.05, ym, "×", ha="left", va="center", fontsize=13, color=ORANGE, weight="bold")
ax.text(XS - 0.15, -t, lab, ha="right", va="center", fontsize=10, color=BLUE)
continue
col = PURPLE if (a, t) in [(0, 10), (4, 7)] else BLUE
arrow(ax, (XS, -t), (XR, -t1), color=col)
ax.text(XS - 0.15, -t, lab, ha="right", va="center", fontsize=10, color=col)
b = believe(a, nfe, N1, W1)
if b == nfe:
nfe += 1
# ACK: 받은 즉시 보낸다
if case["acks_lost"]:
xm, ym = XR - (XR - XS) * 0.45, -(t1 + TP * 0.45)
ax.plot([XR, xm], [-t1, ym], color=GREEN, lw=1.2, ls="--")
ax.text(xm - 0.05, ym, "×", ha="right", va="center", fontsize=13, color=ORANGE, weight="bold")
else:
arrow(ax, (XR, -t1), (XS, -(t1 + TP)), color=GREEN, lw=1.2, ls="--")
ax.text(XR + 0.15, -t1, f"ACK {nfe % N1}", ha="left", va="center", fontsize=9.5, color=GREEN)
if case["acks_lost"]:
ax.text(XS - 0.15, -8.8, "F0의\n타이머 끝", ha="right", va="center", fontsize=9.5, color=ORANGE,
linespacing=1.2)
# 받는 쪽 창: F2를 받은 뒤
win = window(3, N1, W1)
y = -5.9
for k, s in enumerate(win):
ax.add_patch(Rectangle((XR + 0.2 + k * 0.5, y - 0.95), 0.5, 0.9, fc=GREEN, alpha=0.35, ec=INK, lw=0.8))
ax.text(XR + 0.45 + k * 0.5, y - 0.5, str(s), ha="center", va="center", fontsize=10.5)
ax.text(XR + 0.2, y - 1.15, "F2 뒤의 받는 창", ha="left", va="top", fontsize=9.5)
ax.text(XR + 0.15, -13.0, tag, ha="left", va="center", fontsize=10, color=PURPLE, linespacing=1.3)
ax.set_xlim(-1.6, 5.4)
ax.set_ylim(-T_END - 0.6, 3.4)
ax.set_axis_off()
def fig1():
fig, axs = plt.subplots(1, 2, figsize=(7.6, 4.6))
timeline(axs[0], CASE_A, "(가) ACK가 모두 사라짐", "번호 0 도착:\n옛 F0을 다시\n보낸 것")
timeline(axs[1], CASE_B, "(나) ACK가 모두 도착", "번호 0 도착:\n새 프레임\n(실제 4번째)")
fig.subplots_adjust(wspace=0.05)
save(fig, 1)
# ---------------------------------------------------------------------
# fig2: 번호 원
# ---------------------------------------------------------------------
N2 = 8
def ring_case(w):
"""0..w-1을 보내 모두 받았고 ACK가 모두 사라진 순간: 다시 올 수 있는 번호, 받는 창, 겹친 번호"""
resend = {k % N2 for k in range(w)}
rwin = set(window(w, N2, w))
return resend, rwin, resend & rwin
def ring(ax, w, title):
resend, rwin, both = ring_case(w)
step = 360 / N2
for k in range(N2):
a0 = 90 - (k + 0.5) * step # 0번이 맨 위, 시계 방향
a1 = a0 + step
ax.add_patch(Wedge((0, 0), 1.0, a0, a1, width=0.32, fc=GREEN if k in rwin else "none",
alpha=0.45 if k in rwin else 1, ec=INK, lw=0.8))
ax.add_patch(Wedge((0, 0), 0.66, a0, a1, width=0.3, fc=BLUE if k in resend else "none",
alpha=0.45 if k in resend else 1, ec=INK, lw=0.8))
mid = np.deg2rad((a0 + a1) / 2)
col = ORANGE if k in both else INK
ax.text(1.2 * np.cos(mid), 1.2 * np.sin(mid), str(k), ha="center", va="center", fontsize=11,
color=col, weight="bold" if k in both else "normal")
ax.text(0, 0, f"창 {w}", ha="center", va="center", fontsize=10.5)
ax.text(0, -1.55, title, ha="center", va="top", fontsize=10, linespacing=1.3)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-2.35, 1.45)
ax.set_aspect("equal")
ax.set_axis_off()
def fig2():
fig, axs = plt.subplots(1, 2, figsize=(7.0, 4.0))
ring(axs[0], 7, "0~6을 다 받음, ACK 분실\n겹친 번호(주황): 0, 1, 2, 3, 4, 5")
ring(axs[1], 4, "0~3을 다 받음, ACK 분실\n겹친 번호: 없음")
fig.text(0.5, 0.99, "바깥 고리(초록): 받는 쪽 창 안쪽 고리(파랑): 보내는 쪽이 다시 보낼 수 있는 번호",
ha="center", va="top", fontsize=9.5, color=INK)
fig.subplots_adjust(wspace=0.1, top=0.9)
save(fig, 2)
if __name__ == "__main__":
fig1()
fig2()
# fig1: 두 경우 모두 받는 쪽이 본 사건이 같다
va, ba = receiver_view(CASE_A)
vb, bb = receiver_view(CASE_B)
assert va == vb == [("받음", 0), ("ACK", 1), ("받음", 1), ("ACK", 2), ("받음", 2), ("ACK", 3), ("받음", 0)], (va, vb)
assert ba[-1] == (0, 4) # (가): 실제 0번째를 4번째로 믿음 -> 오류
assert bb[-1] == (4, 4) # (나): 실제 4번째를 4번째로 믿음 -> 맞음
assert window(3, N1, W1) == [3, 0, 1]
# fig2: 창 7이면 0~5가 겹치고, 창 4면 겹치지 않는다
r7, w7, b7 = ring_case(7)
assert w7 == {7, 0, 1, 2, 3, 4, 5} and b7 == {0, 1, 2, 3, 4, 5}
r4, w4, b4 = ring_case(4)
assert w4 == {4, 5, 6, 7} and b4 == set()
# 겹침이 없는 가장 큰 창(SWS = RWS = w)은 N/2
assert max(w for w in range(1, N2 + 1) if not ring_case(w)[2]) == N2 // 2
print("ALL CHECKS PASSED")