숨은 노드와 노출 노드 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 숨은 노드와 노출 노드 문서의 그림을 만든다: 72_hidden-exposed-node_fig1.svg, fig2.svg
# fig1: 한 줄에 놓인 A, B, C, D와 각 노드의 신호가 닿는 범위. (a) 숨은 노드 (b) 노출 노드
# fig2: 거리에 따라 약해지는 A와 C의 신호 세기(거리의 세제곱에 반비례하는 단순 모형)와 "들리는" 기준선
# 실행: ~/.venvs/vault-plots/bin/python 72_hidden-exposed-node_plot.py  (matplotlib, numpy 필요)
import math
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 Circle, FancyArrowPatch

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "72_hidden-exposed-node"
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.6, style="-|>", ms=12):
    ax.add_patch(FancyArrowPatch(p, q_, arrowstyle=style, mutation_scale=ms, color=color, lw=lw,
                                 shrinkA=9, shrinkB=9))


# ---------------------------------------------------------------------
# 모형: 노드 네 개가 50 m 간격으로 한 줄에 있다. 신호는 RANGE(m) 안에서만 "들린다".
# ---------------------------------------------------------------------
POS = {"A": 0.0, "B": 50.0, "C": 100.0, "D": 150.0}
RANGE = 68.0                                            # fig2의 기준선(-55 dB)에서 나오는 도달 거리와 같게 잡음


def hears(x, y):
    """x가 보낸 신호가 y에게 들리는가"""
    return x != y and abs(POS[x] - POS[y]) <= RANGE


def carrier_sense_idle(node, talking):
    """talking(지금 보내는 노드들) 중 하나라도 들리면 바쁨"""
    return not any(hears(t, node) for t in talking if t != node)


def collided_at(receiver, senders):
    """receiver에게 들리는 송신자가 둘 이상이면 receiver에서 신호가 겹친다"""
    return sum(hears(s, receiver) for s in senders) >= 2


def scenario_hidden():
    # A가 B에게 보내는 중이다. C도 B에게 보내려고 먼저 들어 본다.
    c_idle = carrier_sense_idle("C", ["A"])
    collision_at_b = collided_at("B", ["A", "C"])
    a_detects = hears("C", "A")                          # 보내는 동안 A가 C의 신호를 들을 수 있나(충돌 감지)
    c_detects = hears("A", "C")
    return dict(c_idle=c_idle, collision_at_b=collision_at_b, a_detects=a_detects, c_detects=c_detects)


def scenario_exposed():
    # B가 A에게 보내는 중이다. C는 D에게 보내려고 먼저 들어 본다.
    c_idle = carrier_sense_idle("C", ["B"])
    harm_at_a = collided_at("A", ["B", "C"])             # 동시에 보냈다면 A에서 겹치나
    harm_at_d = collided_at("D", ["B", "C"])             # 동시에 보냈다면 D에서 겹치나
    return dict(c_idle=c_idle, harm_at_a=harm_at_a, harm_at_d=harm_at_d)


def scenario_card_c3():
    # 확인 문제 C3: A가 B에게 보내는 중에 C가 B가 아닌 D에게 보내려 한다.
    c_idle = carrier_sense_idle("C", ["A"])
    collision_at_b = collided_at("B", ["A", "C"])
    d_ok = not collided_at("D", ["A", "C"])            # D에게는 C의 신호만 닿는다
    return dict(c_idle=c_idle, collision_at_b=collision_at_b, d_ok=d_ok)


# ---------------------------------------------------------------------
# fig1: 배치 그림 두 칸
# ---------------------------------------------------------------------

def draw_layout(ax, title, ranges, links, collision=None, notes=()):
    ax.set_xlim(-80, 230)
    ax.set_ylim(-78, 78)
    ax.set_aspect("equal")
    ax.axis("off")
    for name, color in ranges:
        ax.add_patch(Circle((POS[name], 0), RANGE, facecolor=color, alpha=0.13, edgecolor=color, lw=1.2,
                            ls="--"))
    for name, x in POS.items():
        ax.add_patch(Circle((x, 0), 7, facecolor="none", edgecolor=INK, lw=1.4))
        ax.text(x, 0, name, ha="center", va="center", fontsize=11)
    for (s, d, color, dy) in links:
        arrow(ax, (POS[s], dy), (POS[d], dy), color=color)
    if collision:
        ax.plot([POS[collision]], [20], marker="*", ms=17, color=ORANGE, ls="none")
        ax.text(POS[collision], 31, "충돌", ha="center", fontsize=10, color=ORANGE)
    for (x, y, text, color) in notes:
        ax.text(x, y, text, ha="left", va="center", fontsize=9.5, color=color)
    ax.text(-75, 70, title, ha="left", va="center", fontsize=10.5)


def fig1():
    fig, axes = plt.subplots(2, 1, figsize=(7.4, 5.6))
    draw_layout(axes[0], "(a) 숨은 노드: A와 C가 함께 B에게 보낸다",
                ranges=[("A", BLUE), ("C", GREEN)],
                links=[("A", "B", BLUE, -14), ("C", "B", GREEN, -14)],
                collision="B",
                notes=[(162, -40, "A의 범위(파랑)에 C가 없고", INK), (162, -56, "C의 범위(초록)에 A가 없다", INK)])
    draw_layout(axes[1], "(b) 노출 노드: B는 A에게, C는 D에게 보낸다",
                ranges=[("B", BLUE), ("C", GREEN)],
                links=[("B", "A", BLUE, -14), ("C", "D", GREEN, -14)],
                notes=[(162, -40, "C는 B의 범위 안이라 B가 들린다", INK),
                       (162, -56, "A에는 C가, D에는 B가 안 닿는다", INK)])
    save(fig, 1)


# ---------------------------------------------------------------------
# fig2: 신호 세기 그림. 1 m에서 0 dB, 세기는 거리의 세제곱에 반비례(10·3·log10 d dB씩 줄어듦)
# ---------------------------------------------------------------------
EXP = 3
THRESH = -55.0                                          # 이보다 세면 "들린다"고 본다


def power_db(src, x):
    d = max(abs(x - POS[src]), 1.0)
    return -10 * EXP * math.log10(d)


def fig2():
    xs = np.linspace(-20, 120, 701)
    fig, ax = plt.subplots(figsize=(7.4, 3.6))
    pa = [power_db("A", x) for x in xs]
    pc = [power_db("C", x) for x in xs]
    ax.plot(xs, pa, color=BLUE, lw=1.8)
    ax.plot(xs, pc, color=GREEN, lw=1.8)
    ax.axhline(THRESH, color=ORANGE, lw=1.2, ls="--")
    ax.text(121, THRESH + 1.2, "들리는 기준", ha="right", va="bottom", fontsize=9.5, color=ORANGE)
    ax.text(8, -8, "A의 신호", color=BLUE, fontsize=10)
    ax.text(70, -8, "C의 신호", color=GREEN, fontsize=10)
    for name in ["A", "B", "C"]:
        ax.axvline(POS[name], color=INK, lw=0.8, ls=":")
        ax.text(POS[name], 3, name, ha="center", va="bottom", fontsize=11)
    pb_a, pb_c = power_db("A", POS["B"]), power_db("C", POS["B"])
    pa_c = power_db("C", POS["A"])
    ax.plot([POS["B"], POS["B"]], [pb_a, pb_c], "o", color=INK, ms=4)
    ax.annotate(f"B에서 둘 다 {pb_a:.0f} dB: 겹친다", (POS["B"], pb_a), (55, -38), fontsize=9.5,
                arrowprops=dict(arrowstyle="-", color=INK, lw=0.8))
    ax.plot([POS["A"]], [pa_c], "o", color=GREEN, ms=4)
    ax.annotate(f"A에서 C의 신호 {pa_c:.0f} dB: 안 들린다", (POS["A"], pa_c), (4, -70), fontsize=9.5,
                arrowprops=dict(arrowstyle="-", color=INK, lw=0.8))
    ax.set_xlim(-20, 122)
    ax.set_ylim(-75, 6)
    ax.set_xlabel("위치 (m)")
    ax.set_ylabel("받는 세기 (dB, 1 m 기준)")
    save(fig, 2)


if __name__ == "__main__":
    h = scenario_hidden()
    assert h["c_idle"], "숨은 노드: C는 A의 신호를 못 들어 매체가 비었다고 판단해야 한다"
    assert h["collision_at_b"], "숨은 노드: B에서 A와 C의 신호가 겹쳐야 한다"
    assert not h["a_detects"] and not h["c_detects"], "숨은 노드: A와 C 모두 충돌을 감지하지 못해야 한다"
    e = scenario_exposed()
    assert not e["c_idle"], "노출 노드: C는 B의 신호를 들어 매체가 바쁘다고 판단해야 한다"
    assert not e["harm_at_a"] and not e["harm_at_d"], "노출 노드: 동시에 보내도 A와 D에서는 겹치지 않아야 한다"
    c3 = scenario_card_c3()
    assert c3["c_idle"] and c3["collision_at_b"] and c3["d_ok"], "C3: C는 비었다고 보고 보내며, B에서 겹치고 D는 잘 받는다"
    # fig2의 숫자
    assert round(power_db("A", 50)) == -51 and round(power_db("C", 0)) == -60
    assert abs(10 ** (-THRESH / (10 * EXP)) - RANGE) < 0.2, "기준선과 RANGE가 맞아야 한다"
    own = power_db("A", POS["A"] + 1)                    # A 자신의 신호(1 m 거리에서 0 dB)
    ratio = 10 ** ((own - power_db("C", POS["A"])) / 10)
    assert abs(ratio - 1e6) < 1, "A에게 자기 신호는 C의 신호보다 100만 배 세다"
    fig1()
    fig2()
    print(f"hidden={h} exposed={e} ratio={ratio:.0f}")
    print("ALL CHECKS PASSED")