CSMA/CD 계산 연습 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# CSMA/CD 계산 연습 문서의 그림을 만들고 문제 1, 2, 4의 답을 확인한다: 66_csma-cd-practice_fig1.svg
# fig1 문제 2: 1 km 버스 양 끝의 A, B. 가로는 위치, 세로는 시간(아래로 갈수록 나중)
# 약속: 신호 속도 2 x 10^8 m/s, 중계기 지연 없음
# 실행: ~/.venvs/vault-plots/bin/python -I 66_csma-cd-practice_plot.py (matplotlib 필요)
import os
from fractions import Fraction as F
import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "66_csma-cd-practice"
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, "font.size": 10.5, "axes.unicode_minus": False, "svg.fonttype": "path",
"svg.hashsalt": PREFIX, "text.color": INK,
"axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
"axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
"axes.spines.top": False, "axes.spines.right": False, "legend.frameon": False,
})
V = F(2 * 10**8) # 신호 속도 m/s
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 us(x):
return x * 10**6
# 문제 1: 최소 프레임 = 왕복 시간 x 전송률, 거리 = (최소 프레임 / 전송률) / 2 x 속도
def min_frame_bits(rate, diameter_m):
return 2 * F(diameter_m) / V * rate
def max_diameter_m(rate, frame_bits):
return F(frame_bits) / rate / 2 * V
# 문제 2
def problem2(length_m=1000, rate=10**7, b_start_us=4):
d = us(F(length_m) / V) # 편도 μs
b_detect = d # A의 첫 비트가 B에 닿는 시각
a_detect = b_start_us + d # B의 첫 비트가 A에 닿는 시각
bits_b = (b_detect - b_start_us) * rate / 10**6
bits_a = a_detect * rate / 10**6
return d, b_detect, a_detect, bits_b, bits_a
def fig1():
d, b_det, a_det, _, _ = problem2()
frame_end = F(72, 10) # 72비트 프레임은 7.2 μs에 끝난다
fig, ax = plt.subplots(figsize=(6.6, 4.2))
ax.set_xlim(-560, 1300)
ax.set_ylim(10.6, -0.9)
ax.set_ylabel("시간 (μs)")
ax.spines["bottom"].set_visible(False)
ax.set_xticks([])
for x, name in [(0, "A (0 m)"), (1000, "B (1,000 m)")]:
ax.plot([x, x], [0, 10.2], color=INK, lw=1)
ax.text(x, -0.45, name, ha="center", fontsize=10.5)
ax.plot([0, 1000], [0, float(d)], color=BLUE, lw=2)
ax.text(330, 1.15, "A의 첫 비트", color=BLUE, fontsize=10, rotation=-14)
ax.plot([1000, 0], [4, float(a_det)], color=ORANGE, lw=2)
ax.text(560, 7.55, "B의 첫 비트", color=ORANGE, fontsize=10, rotation=14)
ax.plot([1000], [float(b_det)], "o", color=ORANGE, ms=6)
ax.text(1030, float(b_det) + 0.1, "B가 충돌을 안다", color=ORANGE, fontsize=10, va="center")
ax.plot([1000], [4], "o", color=ORANGE, ms=4, mfc="none")
ax.text(1030, 3.9, "B가 보내기 시작", color=ORANGE, fontsize=10, va="center")
ax.plot([0], [float(a_det)], "o", color=BLUE, ms=6)
ax.text(-30, float(a_det), "A가 충돌을 안다", color=BLUE, fontsize=10, va="center", ha="right")
ax.plot([-40, 40], [float(frame_end)] * 2, color=GREEN, lw=2)
ax.text(-60, float(frame_end), "72비트 프레임이\n끝나는 때", color=GREEN, fontsize=10, va="center",
ha="right")
ax.set_yticks([0, 2, 4, 5, 7.2, 9, 10])
ax.set_yticklabels(["0", "2", "4", "5", "7.2", "9", "10"])
save(fig, 1)
if __name__ == "__main__":
fig1()
# 문제 1
assert min_frame_bits(10**8, 200) == 200 and min_frame_bits(10**8, 200) / 8 == 25
assert max_diameter_m(10**9, 512) == F(512, 10) # 51.2 m
assert max_diameter_m(10**9, 4096) == F(4096, 10) # 409.6 m
assert max_diameter_m(10**7, 512) == 5120 # 10 Mbps에서 순수 전파만 보면 5,120 m
# 문제 2
d, b_det, a_det, bits_b, bits_a = problem2()
assert (d, b_det, a_det, bits_b, bits_a) == (5, 5, 9, 10, 90)
assert F(72) / 10 < a_det # 72비트 프레임은 A가 충돌을 알기 전에 끝난다
assert min_frame_bits(10**7, 1000) == 100 # 이 버스에 필요한 최소 프레임은 100비트
# 문제 4: 10 Mbps. CD 없이 버리는 시간 = 프레임 전체, CD가 있으면 최악 51.2 + 잼 3.2
def waste_no_cd(nbytes):
return F(nbytes * 8, 10) # μs
worst_cd = F(512, 10) + F(32, 10)
assert waste_no_cd(1500) == 1200 and worst_cd == F(544, 10)
assert waste_no_cd(64) == F(512, 10) # 가장 짧은 프레임은 CD가 있어도 아낄 것이 없다
assert round(float(waste_no_cd(1500) / worst_cd), 1) == 22.1
assert waste_no_cd(1500) - worst_cd == F(11456, 10) # 1,145.6 μs를 아낀다
print("ALL CHECKS PASSED")