Download plot_nf_vs_ff_beam.py from lmb12306/SIM_ISAC: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/lmb12306/SIM_ISAC/resolve/main/plot_nf_vs_ff_beam.py
- Command line
-
hf download hf://datasets/lmb12306/SIM_ISAC/plot_nf_vs_ff_beam.py
-
curl -L -o plot_nf_vs_ff_beam.py https://huggingface.co/datasets/lmb12306/SIM_ISAC/resolve/main/plot_nf_vs_ff_beam.py
12 kB
| #!/usr/bin/env python3 | |
| """ | |
| Near-field vs far-field beamforming comparison. | |
| Near-field user at 8 m (well within Fresnel distance) β focused SPOT | |
| Far-field user at 500 m (beyond Fresnel distance) β STRIP along angle | |
| Each beamformer uses the appropriate steering model for its user. | |
| Beam patterns are evaluated on a polar (range, azimuth) grid. | |
| Usage: | |
| python plot_nf_vs_ff_beam.py | |
| python plot_nf_vs_ff_beam.py --Nh 128 --Nv 64 --fc 12e9 | |
| """ | |
| import argparse | |
| import math | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # UPA geometry | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def make_upa(Nh, Nv, dx, dy): | |
| """Uniform Planar Array in x-z plane, centered at origin.""" | |
| x = (torch.arange(Nh, dtype=torch.float32) - (Nh - 1) / 2) * dx | |
| z = (torch.arange(Nv, dtype=torch.float32) - (Nv - 1) / 2) * dy | |
| X, Z = torch.meshgrid(x, z, indexing="ij") | |
| return torch.stack([X, torch.zeros_like(X), Z], dim=-1).reshape(-1, 3) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Steering vectors | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def nf_steering(p, r, az, k): | |
| """Near-field: a_n = exp(jk βp_target β p_nβ) (spherical wave)""" | |
| px = r * torch.sin(az) | |
| py = -r * torch.cos(az) | |
| dist = torch.sqrt( | |
| (px.unsqueeze(-1) - p[:, 0]) ** 2 | |
| + py.unsqueeze(-1) ** 2 | |
| + p[:, 2] ** 2 | |
| ) | |
| return torch.exp(1j * k * dist) | |
| def ff_steering(p, az, k): | |
| """Far-field: a_n = exp(βjk x_n sinΞΈ) (planar wave, angle only)""" | |
| return torch.exp(-1j * k * p[:, 0] * torch.sin(az).unsqueeze(-1)) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Beam pattern on polar (range, azimuth) grid | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def beam_pattern_polar(w, p, r_grid, az_grid, k, batch=2000): | |
| """P(r, ΞΈ) = |w^H a_nf(r, ΞΈ)|Β² normalised to peak = 1.""" | |
| R, AZ = torch.meshgrid(r_grid, az_grid, indexing="ij") | |
| Rf, AZf = R.reshape(-1), AZ.reshape(-1) | |
| wc = w.conj() | |
| parts = [] | |
| for i in range(0, Rf.shape[0], batch): | |
| a = nf_steering(p, Rf[i:i + batch], AZf[i:i + batch], k) | |
| parts.append((a @ wc).abs().square().cpu()) | |
| P = torch.cat(parts).reshape(len(r_grid), len(az_grid)) | |
| return P / P.max() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Plot: 2D heatmaps + 1D cuts + phase profiles | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def plot_comparison(P_nf_db, P_ff_db, | |
| r_nf, az_nf, r0_nf, az0_nf_deg, | |
| r_ff, az_ff, r0_ff, az0_ff_deg, | |
| w_nf, w_ff, p, info, path): | |
| """3-row figure: heatmaps, range cuts, phase profiles.""" | |
| fig, axes = plt.subplots(3, 2, figsize=(14, 15)) | |
| vmin = -40 | |
| # ββ Row 1: 2D heatmaps ββ | |
| for col, (Z, r_ax, az_ax, r0, az0, label) in enumerate([ | |
| (P_nf_db, r_nf, az_nf, r0_nf, az0_nf_deg, | |
| f"Near-Field BF β SPOT\n(target r={r0_nf:.0f} m, ΞΈ={az0_nf_deg}Β°)"), | |
| (P_ff_db, r_ff, az_ff, r0_ff, az0_ff_deg, | |
| f"Far-Field BF β STRIP\n(target r={r0_ff:.0f} m, ΞΈ={az0_ff_deg}Β°)"), | |
| ]): | |
| ax = axes[0, col] | |
| pcm = ax.pcolormesh( | |
| az_ax, r_ax, np.clip(Z, vmin, 0), | |
| cmap="jet", shading="auto", vmin=vmin, vmax=0) | |
| fig.colorbar(pcm, ax=ax, label="dB") | |
| ax.axhline(r0, color="w", ls="--", lw=0.8, alpha=0.7) | |
| ax.axvline(az0, color="w", ls="--", lw=0.8, alpha=0.7) | |
| ax.plot(az0, r0, "r*", ms=14, mec="white", mew=0.6) | |
| ax.set_xlabel("Azimuth (Β°)") | |
| ax.set_ylabel("Range (m)") | |
| ax.set_title(label, fontsize=11) | |
| # ββ Row 2: range cuts at target azimuth ββ | |
| az_nf_np = az_nf.numpy() if isinstance(az_nf, torch.Tensor) else az_nf | |
| az_ff_np = az_ff.numpy() if isinstance(az_ff, torch.Tensor) else az_ff | |
| r_nf_np = r_nf.numpy() if isinstance(r_nf, torch.Tensor) else r_nf | |
| r_ff_np = r_ff.numpy() if isinstance(r_ff, torch.Tensor) else r_ff | |
| idx_nf = np.argmin(np.abs(az_nf_np - az0_nf_deg)) | |
| idx_ff = np.argmin(np.abs(az_ff_np - az0_ff_deg)) | |
| for col, (Z, r_ax, idx, r0, label) in enumerate([ | |
| (P_nf_db, r_nf_np, idx_nf, r0_nf, | |
| f"NF range cut at ΞΈ={az0_nf_deg}Β°"), | |
| (P_ff_db, r_ff_np, idx_ff, r0_ff, | |
| f"FF range cut at ΞΈ={az0_ff_deg}Β°"), | |
| ]): | |
| ax = axes[1, col] | |
| ax.plot(r_ax, Z[:, idx], "b-", lw=1.5) | |
| ax.axvline(r0, color="r", ls="--", lw=1, label=f"target r={r0:.0f} m") | |
| ax.set_xlabel("Range (m)") | |
| ax.set_ylabel("Power (dB)") | |
| ax.set_title(label, fontsize=11) | |
| ax.set_ylim(vmin, 3) | |
| ax.legend(fontsize=9) | |
| ax.grid(True, ls=":", alpha=0.3) | |
| # ββ Row 3: weight phase profiles ββ | |
| p_np = p.numpy() | |
| x_elem = p_np[:, 0] | |
| sort_idx = np.argsort(x_elem) | |
| for col, (w, label) in enumerate([ | |
| (w_nf, "NF weight phase (curved = spherical)"), | |
| (w_ff, "FF weight phase (linear = planar)"), | |
| ]): | |
| ax = axes[2, col] | |
| phase = np.angle(w.numpy())[sort_idx] | |
| phase_unwrap = np.unwrap(phase) | |
| ax.plot(x_elem[sort_idx] * 1e3, phase_unwrap, "g-", lw=1) | |
| ax.set_xlabel("Element x-position (mm)") | |
| ax.set_ylabel("Phase (rad)") | |
| ax.set_title(label, fontsize=11) | |
| ax.grid(True, ls=":", alpha=0.3) | |
| fig.suptitle(info, fontsize=13, fontweight="bold") | |
| plt.tight_layout() | |
| plt.savefig(path, dpi=150, bbox_inches="tight") | |
| plt.close() | |
| print(f"Saved β {path}") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 3D surface plots | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def plot_3d(P_nf_db, P_ff_db, | |
| r_nf, az_nf, r0_nf, az0_nf_deg, | |
| r_ff, az_ff, r0_ff, az0_ff_deg, | |
| info, path): | |
| fig = plt.figure(figsize=(18, 8)) | |
| vmin = -40 | |
| for col, (Z, r_ax, az_ax, r0, az0, label) in enumerate([ | |
| (P_nf_db, r_nf, az_nf, r0_nf, az0_nf_deg, | |
| f"(a) Near-Field BF (target {r0_nf:.0f} m, {az0_nf_deg}Β°)"), | |
| (P_ff_db, r_ff, az_ff, r0_ff, az0_ff_deg, | |
| f"(b) Far-Field BF (target {r0_ff:.0f} m, {az0_ff_deg}Β°)"), | |
| ]): | |
| ax = fig.add_subplot(1, 2, col + 1, projection="3d") | |
| R, AZ = np.meshgrid(r_ax, az_ax, indexing="ij") | |
| Z_clip = np.clip(Z, vmin, 0) | |
| ax.plot_surface( | |
| AZ, R, Z_clip, | |
| cmap="jet", vmin=vmin, vmax=0, | |
| rstride=2, cstride=2, | |
| linewidth=0, antialiased=True, alpha=0.9, | |
| ) | |
| ax.scatter([az0], [r0], [3], | |
| color="red", marker="*", s=300, | |
| zorder=10, depthshade=False) | |
| ax.set_xlabel("Azimuth (Β°)", fontsize=10, labelpad=8) | |
| ax.set_ylabel("Range (m)", fontsize=10, labelpad=8) | |
| ax.set_zlabel("Power (dB)", fontsize=10, labelpad=6) | |
| ax.set_zlim(vmin, 5) | |
| ax.set_title(label, fontsize=12, fontweight="bold", y=-0.02) | |
| ax.view_init(elev=30, azim=-60) | |
| plt.tight_layout() | |
| plt.savefig(path, dpi=150, bbox_inches="tight") | |
| plt.close() | |
| print(f"Saved β {path}") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Main | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run(args): | |
| lam = 3e8 / args.fc | |
| k = 2 * math.pi / lam | |
| dx = dy = lam / 2 | |
| # If physical aperture is specified, override Nh/Nv to keep aperture fixed | |
| if args.aperture_h > 0: | |
| args.Nh = max(2, round(args.aperture_h / dx)) | |
| if args.aperture_v > 0: | |
| args.Nv = max(2, round(args.aperture_v / dy)) | |
| N = args.Nh * args.Nv | |
| D_h, D_v = args.Nh * dx, args.Nv * dy | |
| D = math.sqrt(D_h ** 2 + D_v ** 2) | |
| fresnel = 2 * D ** 2 / lam | |
| # NF user: well inside Fresnel distance | |
| r0_nf, az0_nf_deg = 3.0, 45.0 | |
| # FF user: beyond Fresnel distance | |
| r0_ff, az0_ff_deg = 500.0, 30.0 | |
| az0_nf_rad = az0_nf_deg * math.pi / 180 | |
| az0_ff_rad = az0_ff_deg * math.pi / 180 | |
| print(f"UPA {args.Nh}Γ{args.Nv} = {N} elements") | |
| print(f"Ξ» = {lam * 1e3:.1f} mm | dx = dy = {dx * 1e3:.2f} mm") | |
| print(f"Aperture {D_h:.3f} Γ {D_v:.3f} m | Fresnel {fresnel:.0f} m") | |
| print(f"NF user: r = {r0_nf} m, ΞΈ = {az0_nf_deg}Β° " | |
| f"(r/Fresnel = {r0_nf / fresnel:.4f})") | |
| print(f"FF user: r = {r0_ff} m, ΞΈ = {az0_ff_deg}Β° " | |
| f"(r/Fresnel = {r0_ff / fresnel:.2f})") | |
| p = make_upa(args.Nh, args.Nv, dx, dy) | |
| # Beamforming weights | |
| w_nf = nf_steering(p, torch.tensor([r0_nf]), | |
| torch.tensor([az0_nf_rad]), k).squeeze(0) | |
| w_ff = ff_steering(p, torch.tensor([az0_ff_rad]), k).squeeze(0) | |
| # Evaluation grids (polar: range Γ azimuth) | |
| ng = args.grid | |
| r_nf_grid = torch.linspace(0.5, 15.0, ng) | |
| az_nf_grid = torch.linspace(0.0, 90.0, ng) # degrees for display | |
| az_nf_rad_grid = az_nf_grid * math.pi / 180 | |
| r_ff_grid = torch.linspace(50.0, 1000.0, ng) | |
| az_ff_grid = torch.linspace(0.0, 90.0, ng) | |
| az_ff_rad_grid = az_ff_grid * math.pi / 180 | |
| # Smaller batches for large arrays | |
| bsz = max(200, 2000 // max(1, N // 8192)) | |
| print(f"\nComputing beam patterns ({ng}Γ{ng} polar grid, batch={bsz}) ...") | |
| P_nf = beam_pattern_polar(w_nf, p, r_nf_grid, az_nf_rad_grid, k, batch=bsz) | |
| print(" Near-field β") | |
| P_ff = beam_pattern_polar(w_ff, p, r_ff_grid, az_ff_rad_grid, k, batch=bsz) | |
| print(" Far-field β") | |
| P_nf_db = 10 * np.log10(P_nf.numpy() + 1e-15) | |
| P_ff_db = 10 * np.log10(P_ff.numpy() + 1e-15) | |
| info = (f"UPA {args.Nh}Γ{args.Nv} @ {args.fc / 1e9:.0f} GHz | " | |
| f"Fresnel = {fresnel:.0f} m") | |
| # 2D heatmaps + range cuts + phase profiles | |
| plot_comparison( | |
| P_nf_db, P_ff_db, | |
| r_nf_grid.numpy(), az_nf_grid.numpy(), r0_nf, az0_nf_deg, | |
| r_ff_grid.numpy(), az_ff_grid.numpy(), r0_ff, az0_ff_deg, | |
| w_nf, w_ff, p, info, args.output) | |
| # 3D surface plots | |
| path_3d = args.output.replace(".png", "_3d.png") | |
| plot_3d( | |
| P_nf_db, P_ff_db, | |
| r_nf_grid.numpy(), az_nf_grid.numpy(), r0_nf, az0_nf_deg, | |
| r_ff_grid.numpy(), az_ff_grid.numpy(), r0_ff, az0_ff_deg, | |
| info, path_3d) | |
| def main(): | |
| pa = argparse.ArgumentParser(description="NF vs FF beam comparison") | |
| pa.add_argument("--Nh", type=int, default=128) | |
| pa.add_argument("--Nv", type=int, default=64) | |
| pa.add_argument("--fc", type=float, default=12e9, help="Carrier freq (Hz)") | |
| pa.add_argument("--aperture_h", type=float, default=0, | |
| help="Fixed horizontal aperture (m). Overrides Nh.") | |
| pa.add_argument("--aperture_v", type=float, default=0, | |
| help="Fixed vertical aperture (m). Overrides Nv.") | |
| pa.add_argument("--grid", type=int, default=200, help="Grid points per axis") | |
| pa.add_argument("-o", "--output", default="nf_vs_ff_beam.png") | |
| args = pa.parse_args() | |
| run(args) | |
| if __name__ == "__main__": | |
| main() | |