| import argparse |
| import math |
| import os |
| from pathlib import Path |
| from types import SimpleNamespace |
|
|
| os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
| import torch |
|
|
| from updated_SIM_0410_add_library import make_layer_points |
| from updated_SIM_0413_multi_user import Config, MultiUserDownlinkOptimizer, build_point_propagation_vector |
|
|
|
|
| def default_user_positions(cfg: Config, device): |
| az_deg = torch.tensor([-38.0, -12.0, 18.0, 43.0], device=device) |
| r = torch.tensor([5.0, 9.0, 13.0, 17.0], device=device) |
| if cfg.n_users != 4: |
| az_deg = torch.linspace(cfg.az_min_deg + 12.0, cfg.az_max_deg - 12.0, cfg.n_users, device=device) |
| r = torch.linspace(cfg.r_min + 3.0, cfg.r_max - 3.0, cfg.n_users, device=device) |
| return r, az_deg * math.pi / 180.0 |
|
|
|
|
| def propagate_to_last_layer(optimizer: MultiUserDownlinkOptimizer, theta, a_raw, b_raw, device): |
| cfg = optimizer.cfg |
| pt_w = 10.0 ** (cfg.Pt_dBm / 10.0) / 1000.0 |
| u = optimizer.feeders.to(device) * math.sqrt(pt_w / optimizer.num_users) |
|
|
| for l_idx, layer_type in enumerate(optimizer.layout): |
| if layer_type == "L": |
| u = u * torch.exp(1j * theta[l_idx]).unsqueeze(0) |
| else: |
| u = optimizer.apply_nonlinear(u, a_raw[l_idx], b_raw[l_idx]) |
|
|
| if l_idx < optimizer.num_layers - 1: |
| h_mat = getattr(optimizer, f"H_{l_idx}").to(device) |
| u = torch.matmul(u, h_mat.T) |
| return u |
|
|
|
|
| def ideal_focus_to_targets(cfg: Config, geometry, r_users, az_users, device): |
| pt_w = 10.0 ** (cfg.Pt_dBm / 10.0) / 1000.0 |
| p_last = make_layer_points(cfg, geometry.num_layers, device) |
| p_users = torch.stack( |
| [ |
| r_users * torch.sin(az_users), |
| -r_users * torch.cos(az_users), |
| torch.zeros_like(r_users), |
| ], |
| dim=-1, |
| ) |
| h_targets = build_point_propagation_vector(cfg, p_last, p_users) |
| u = h_targets.conj() |
| u = u / u.norm(dim=1, keepdim=True).clamp_min(1e-30) |
| return u * math.sqrt(pt_w / geometry.num_users) |
|
|
|
|
| @torch.no_grad() |
| def beam_power_map( |
| cfg: Config, |
| geometry, |
| u_last, |
| n_r: int, |
| n_az: int, |
| chunk_size: int, |
| device, |
| plot_mode: str, |
| ): |
| |
| r_axis = torch.linspace(cfg.r_min, cfg.r_max, n_r, device=device) |
| az_axis = torch.linspace(cfg.az_min_deg, cfg.az_max_deg, n_az, device=device) * math.pi / 180.0 |
| |
| |
| r_grid, az_grid = torch.meshgrid(r_axis, az_axis, indexing="ij") |
| points = torch.stack( |
| [ |
| r_grid.reshape(-1) * torch.sin(az_grid.reshape(-1)), |
| -r_grid.reshape(-1) * torch.cos(az_grid.reshape(-1)), |
| torch.zeros_like(r_grid.reshape(-1)), |
| ], |
| dim=-1, |
| ) |
|
|
| p_last = make_layer_points(cfg, geometry.num_layers, device) |
| |
| powers = [] |
| for start in range(0, points.shape[0], chunk_size): |
| |
| h = build_point_propagation_vector(cfg, p_last, points[start : start + chunk_size]) |
|
|
| |
| |
| rx = torch.matmul(h, u_last.T) |
| power = rx.abs().square() |
| if plot_mode == "focus": |
| |
| |
| channel_power = h.abs().square().sum(dim=1, keepdim=True).clamp_min(1e-30) |
| power = power / channel_power |
| powers.append(power.cpu()) |
| |
| |
| power_map = torch.cat(powers, dim=0).reshape(n_r, n_az, cfg.n_users) |
| return r_axis.cpu(), az_axis.cpu() * 180.0 / math.pi, power_map |
|
|
|
|
| def to_relative_db(power: torch.Tensor): |
| return 10.0 * torch.log10(power / power.max().clamp_min(1e-30) + 1e-12) |
|
|
|
|
| def plot_beams(cfg, r_axis, az_axis_deg, powers, r_users, az_users, rates, output_path: Path, plot_mode: str, db_floor: float): |
| n_cols = min(3, cfg.n_users + 1) |
| n_rows = math.ceil((cfg.n_users + 1) / n_cols) |
| fig, axes = plt.subplots(n_rows, n_cols, figsize=(5.5 * n_cols, 4.5 * n_rows), constrained_layout=True) |
| axes = np.asarray(axes).reshape(-1).tolist() |
|
|
| az_np = az_axis_deg.numpy() |
| r_np = r_axis.numpy() |
| target_az = az_users.detach().cpu().numpy() * 180.0 / math.pi |
| target_r = r_users.detach().cpu().numpy() |
|
|
| |
| metric_name = "Focus Gain" if plot_mode == "focus" else "Received Power" |
| panels = [(f"Max {metric_name}", powers.max(dim=-1).values)] |
| panels.extend((f"Stream {idx + 1} {metric_name}", powers[:, :, idx]) for idx in range(cfg.n_users)) |
|
|
| for ax, (title, panel_power) in zip(axes, panels): |
| |
| db = to_relative_db(panel_power).numpy() |
| |
| image = ax.imshow( |
| db.T, |
| origin="lower", |
| aspect="auto", |
| extent=[r_np.min(), r_np.max(), az_np.min(), az_np.max()], |
| vmin=db_floor, |
| vmax=0.0, |
| cmap="magma", |
| ) |
| ax.contour(r_np, az_np, db.T, levels=[-10.0, -3.0], colors=["white", "cyan"], linewidths=[0.8, 1.0]) |
| |
| |
| ax.scatter(target_r, target_az, c="cyan", s=60, edgecolors="white", marker='x', linewidths=1.5, label='GT Positions') |
| |
| for user_idx, (az, rr) in enumerate(zip(target_az, target_r), start=1): |
| ax.text(rr + 0.2, az + 1.0, f"U{user_idx}", color="white", fontsize=10, weight="bold") |
| |
| ax.set_title(title) |
| ax.set_xlabel("Range (m)") |
| ax.set_ylabel("Azimuth (deg)") |
| fig.colorbar(image, ax=ax, label=f"Normalized {metric_name.lower()} (dB)") |
|
|
| for ax in axes[len(panels) :]: |
| ax.axis("off") |
|
|
| fig.suptitle(f"SIM Near-Field {metric_name}, Avg Rate: {rates.mean().item():.2f} bps/Hz/user", fontsize=14) |
| fig.savefig(output_path, dpi=200) |
| plt.close(fig) |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--n-users", type=int, default=4) |
| parser.add_argument("--nh", type=int, default=None, help="Override horizontal SIM elements for plotting.") |
| parser.add_argument("--nv", type=int, default=None, help="Override vertical SIM elements for plotting.") |
| parser.add_argument("--iters", type=int, default=60) |
| parser.add_argument("--lr", type=float, default=5e-2) |
| parser.add_argument("--n-r", type=int, default=200) |
| parser.add_argument("--n-az", type=int, default=200) |
| parser.add_argument("--chunk-size", type=int, default=1024) |
| parser.add_argument("--db-floor", type=float, default=-20.0, help="Lower dB limit for the plotted color scale.") |
| parser.add_argument( |
| "--plot-mode", |
| type=str, |
| default="focus", |
| choices=["focus", "received"], |
| help="focus removes channel/path-loss strength; received plots absolute received power.", |
| ) |
| parser.add_argument( |
| "--beam-source", |
| type=str, |
| default="ideal", |
| choices=["ideal", "optimizer"], |
| help="ideal uses conjugate near-field focusing weights; optimizer plots the current SIM optimizer output.", |
| ) |
| parser.add_argument("--device", type=str, default=None) |
| parser.add_argument("--output", type=str, default="sim_focusing_spectrum.png") |
| return parser.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| cfg = Config() |
| cfg.n_users = args.n_users |
| if args.nh is not None: |
| cfg.Nh = args.nh |
| if args.nv is not None: |
| cfg.Nv = args.nv |
| cfg.group_opt_iters = args.iters |
| cfg.group_opt_lr = args.lr |
| if args.device is not None: |
| cfg.device = args.device |
| device = torch.device(cfg.device) |
|
|
| geometry = SimpleNamespace(num_layers=4, num_users=cfg.n_users) |
| optimizer = None |
| if args.beam_source == "optimizer": |
| optimizer = MultiUserDownlinkOptimizer(cfg).to(device) |
| geometry = optimizer |
| r_users, az_users = default_user_positions(cfg, device) |
|
|
| pt_w = 10.0 ** (cfg.Pt_dBm / 10.0) / 1000.0 |
| noise_power = pt_w / (10.0 ** (cfg.snr_db / 10.0)) |
| if args.beam_source == "optimizer": |
| print(f"Optimizing SIM Focal Points for {cfg.n_users} users...") |
| theta, a_raw, b_raw = optimizer.optimize_group_action(r_users, az_users) |
| u_last = propagate_to_last_layer(optimizer, theta, a_raw, b_raw, device) |
| with torch.no_grad(): |
| gains = optimizer.propagate_streams(theta, a_raw, b_raw, r_users, az_users) |
| rates = optimizer.rates_from_gains(gains, noise_power) |
| else: |
| print(f"Drawing ideal near-field focal points for {cfg.n_users} users...") |
| u_last = ideal_focus_to_targets(cfg, geometry, r_users, az_users, device) |
| with torch.no_grad(): |
| p_last = make_layer_points(cfg, geometry.num_layers, device) |
| p_users = torch.stack( |
| [ |
| r_users * torch.sin(az_users), |
| -r_users * torch.cos(az_users), |
| torch.zeros_like(r_users), |
| ], |
| dim=-1, |
| ) |
| h_users = build_point_propagation_vector(cfg, p_last, p_users) |
| gains = torch.matmul(h_users, u_last.T).abs().square() |
| desired = torch.diagonal(gains) |
| interference = gains.sum(dim=1) - desired |
| rates = torch.log2(1.0 + desired / (interference + noise_power)) |
|
|
| print(f"Mean rate achieved: {rates.mean().item():.4f} bps/Hz/user") |
|
|
| |
| r_axis, az_axis_deg, powers = beam_power_map( |
| cfg, geometry, u_last, args.n_r, args.n_az, args.chunk_size, device, args.plot_mode |
| ) |
| |
| output_path = Path(args.output).resolve() |
| plot_beams(cfg, r_axis, az_axis_deg, powers, r_users, az_users, rates, output_path, args.plot_mode, args.db_floor) |
| print(f"Saved near-field spectrum plot to {output_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|