File size: 6,959 Bytes
1b70a0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | """Plot CDF + RMSE comparison for the 4 SIM physical-axis ckpts.
Output:
research_paper/sensing_cdf_compare.png (CDF curves)
research_paper/sensing_rmse_bars.png (per-axis RMSE bar chart)
"""
import math, os, torch
import matplotlib.pyplot as plt
import numpy as np
from joint_dual_sim import (
JointDualSIM, PortReadout, PerBinPort, LinearReadout,
soft_position_estimate, make_range_edges,
)
from rate_aware_gen import make_config
from updated_SIM_0413_multi_user import hadamard_matrix
CKPTS = [
("baseline (5λ, 4L+3N)", "experiments_v2/checkpoints/sense_port_LLNLNLN_S64Q10_Pt10_SNR20.pt"),
("thick=0.10m (9.3λ)", "experiments_v2/checkpoints/phys_thick0p10.pt"),
("thick=0.20m (18.7λ)", "experiments_v2/checkpoints/phys_thick0p20.pt"),
("6L+5N (default 5λ)", "experiments_v2/checkpoints/phys_layout6L5N.pt"),
]
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
CACHE = "experiments_v2/caches/v2_K2_15k.pt"
def argmax_position(logits, cfg, device):
idx = logits.argmax(dim=-1)
s = idx % cfg.S
q = idx // cfg.S
az_edges = torch.linspace(cfg.az_min_deg, cfg.az_max_deg, cfg.S + 1, device=device)
r_edges = make_range_edges(cfg, device)
az_hat = (az_edges[:-1] + az_edges[1:]) / 2.0 * math.pi / 180.0
r_hat = (r_edges[:-1] + r_edges[1:]) / 2.0
return r_hat[q], az_hat[s]
def eval_one(ckpt_path):
ckpt = torch.load(ckpt_path, weights_only=False, map_location="cpu")
cfg_dict = ckpt['cfg']
d = torch.load(CACHE, weights_only=False, map_location="cpu")
geos = d['geos']
M = geos.shape[0]; K = geos.shape[1] // 2
cfg = make_config("large", K)
cfg.range_grid = ckpt['range_grid']
for k, v in cfg_dict.items():
setattr(cfg, k, v)
Pt_dBm = getattr(cfg, 'Pt_UE_dBm', cfg.Pt_dBm)
pt_w = 10 ** (Pt_dBm / 10) / 1000
sqrt_pt = math.sqrt(pt_w)
r_all = geos[:, ::2] * cfg.r_max
az_all = geos[:, 1::2] * math.pi
g = torch.Generator().manual_seed(2027)
perm = torch.randperm(M, generator=g)
n_tr = int(0.8 * M); te = perm[n_tr:]
sim = JointDualSIM(cfg, layout=ckpt['layout'],
share_mask=tuple(int(c) == 1 for c in ckpt['share_mask'])).to(DEVICE)
sim.load_state_dict(ckpt['sim']); sim.eval()
n_bins = cfg.S * cfg.Q
if ckpt['readout'] == "port":
head = PortReadout(n_bins).to(DEVICE)
elif ckpt['readout'] == "perbin":
head = PerBinPort(n_bins).to(DEVICE)
else:
head = LinearReadout(n_bins).to(DEVICE)
head.load_state_dict(ckpt['head']); head.eval()
pilot_H = hadamard_matrix(max(cfg.T, K), DEVICE)
pilot = pilot_H[:K, :cfg.T].to(torch.float32) * sqrt_pt
rt, at, rs, as_, ra, aa = [], [], [], [], [], []
bs = 64
with torch.no_grad():
for s_ in range(0, len(te), bs):
idx = te[s_:s_+bs]
r_b = r_all[idx].to(DEVICE); az_b = az_all[idx].to(DEVICE)
B = r_b.shape[0]
for k in range(K):
x_pilot = pilot[k:k+1].expand(B, -1)
y = sim.forward_ul_signal(r_b[:, k], az_b[:, k], x_pilot)
logits = head(y.abs())
r_s, az_s = soft_position_estimate(logits, cfg)
r_a, az_a = argmax_position(logits, cfg, DEVICE)
rt.append(r_b[:, k]); at.append(az_b[:, k])
rs.append(r_s); as_.append(az_s)
ra.append(r_a); aa.append(az_a)
r_true = torch.cat(rt); az_true = torch.cat(at)
r_s = torch.cat(rs); az_s = torch.cat(as_)
r_a = torch.cat(ra); az_a = torch.cat(aa)
def err_xy(r_hat, az_hat):
x_t, y_t = r_true*torch.cos(az_true), r_true*torch.sin(az_true)
x_h, y_h = r_hat *torch.cos(az_hat), r_hat *torch.sin(az_hat)
return torch.sqrt((x_t-x_h)**2 + (y_t-y_h)**2).cpu().numpy()
return {
"argmax": err_xy(r_a, az_a),
"soft": err_xy(r_s, az_s),
"r_rmse_arg": float((r_true-r_a).pow(2).mean().sqrt()),
"r_rmse_soft": float((r_true-r_s).pow(2).mean().sqrt()),
"az_rmse_arg": float(((az_true-az_a)*180/math.pi).pow(2).mean().sqrt()),
"az_rmse_soft": float(((az_true-az_s)*180/math.pi).pow(2).mean().sqrt()),
}
def main():
os.makedirs("research_paper", exist_ok=True)
results = {}
for label, ck in CKPTS:
print(f"Eval: {label}")
results[label] = eval_one(ck)
# ── CDF figure ────────────────────────────────────────────────
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
colors = ["#888888", "#1f77b4", "#2ca02c", "#d62728"]
for (label, _), col in zip(CKPTS, colors):
for ax, key, sub in zip(axes, ["argmax", "soft"],
["argmax (hard)", "soft expected"]):
err = np.sort(results[label][key])
cdf = np.arange(1, len(err)+1) / len(err)
ax.plot(err, cdf, label=label, color=col, lw=1.8)
for ax, sub in zip(axes, ["argmax (hard)", "soft expected"]):
ax.axhline(0.5, ls=":", c="k", alpha=0.4)
ax.axhline(0.9, ls=":", c="k", alpha=0.4)
ax.set_xlabel("Position error (m)")
ax.set_ylabel("CDF")
ax.set_xlim(0, 6); ax.set_ylim(0, 1)
ax.set_title(f"Position error CDF — {sub} estimator")
ax.grid(alpha=0.3); ax.legend(loc="lower right", fontsize=8)
plt.tight_layout()
out1 = "research_paper/sensing_cdf_compare.png"
plt.savefig(out1, dpi=150); plt.close()
print(f"saved {out1}")
# ── RMSE bar chart (best-of-{argmax,soft} per ckpt) ───────────
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
labels = [l for l, _ in CKPTS]
short = ["baseline", "thick=0.10", "thick=0.20", "6L+5N"]
range_rmse = []; az_rmse = []; pos_rmse = []
for label, _ in CKPTS:
r = results[label]
# pick the better of arg/soft per-axis
range_rmse.append(min(r["r_rmse_arg"], r["r_rmse_soft"]))
az_rmse.append(min(r["az_rmse_arg"], r["az_rmse_soft"]))
# for pos, take best-estimator p_rmse derived from CDF
pos_rmse.append(min(np.sqrt((r["argmax"]**2).mean()),
np.sqrt((r["soft"]**2).mean())))
for ax, vals, name, unit in zip(
axes, [range_rmse, az_rmse, pos_rmse],
["Range RMSE", "Azimuth RMSE", "Position RMSE"],
["m", "deg", "m"]):
bars = ax.bar(short, vals, color=colors)
for b, v in zip(bars, vals):
ax.text(b.get_x()+b.get_width()/2, v+0.02,
f"{v:.2f}", ha="center", fontsize=9)
ax.set_ylabel(f"{name} ({unit})")
ax.set_title(name)
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
out2 = "research_paper/sensing_rmse_bars.png"
plt.savefig(out2, dpi=150); plt.close()
print(f"saved {out2}")
if __name__ == "__main__":
main()
|