目录
算法1: 稀疏贝叶斯学习阵列流形估计 (Sparse Bayesian Learning for Array Manifold Estimation)
算法2: 结构化协方差矩阵重构 (Structured Covariance Matrix Reconstruction)
算法3: 交替方向乘子法波束成形 (ADMM-Based Robust Beamforming)
算法4: 张量分解多参数估计 (Tensor CP-Decomposition for Multiparameter Estimation)
算法5: 深度展开网络自适应波束成形 (Deep Unfolding for Adaptive Beamforming)
算法6: 离网连续压缩感知 (Off-Grid Continuous Compressive Sensing)
第一部分:原理详解
1. 引言与数学预备
现代阵列信号处理从传统子空间方法向优化驱动范式转变,核心在于充分利用问题内在结构:阵列流形的Vandermonde特性、协方差矩阵的Toeplitz/Hermitian结构、张量数据的多线性秩结构,以及深度网络对迭代算法的参数化能力。本部分系统阐述六种代表性算法,建立从稀疏推断到连续优化的完整理论体系。
基本信号模型:
考虑 $N$ 元均匀线阵接收 $K$ 个窄带远场信号:
$$y(t) = A(\theta)s(t) + n(t), \quad t=1, \dots, T$$
其中 $A(\theta) = [a(\theta_1), \dots, a(\theta_K)]$ 为阵列流形,其方向向量定义为:
$$a(\theta) = [1, e^{j\frac{2\pi d}{\lambda}\sin\theta}, \dots, e^{j\frac{2\pi d}{\lambda}(N-1)\sin\theta}]^T$$
2. 稀疏贝叶斯学习阵列流形估计
2.1 层次概率模型与稀疏先验
稀疏贝叶斯学习(Sparse Bayesian Learning, SBL)通过层次高斯先验实现稀疏诱导。对网格化角度集合 $\Theta = \{\theta_1, \dots, \theta_G\} \ (G \gg K)$,信号 $x \in \mathbb{C}^G$ 服从:
$$p(x|\gamma) = \prod_{g=1}^G \mathcal{CN}(x_g; 0, \gamma_g^{-1})$$
其中精度 $\gamma_g$ 服从Gamma超先验 $p(\gamma_g) = \Gamma(\gamma_g; a, b)$。当 $\gamma_g \to \infty$ 时对应网格点无信号,实现自动模型选择。
**边缘似然(Evidence)**通过积分信号变量获得:
$$p(Y|\gamma) = \prod_{t=1}^T \mathcal{CN}(y(t); 0, C)$$
其中 $C = \sigma^2 I + A\Gamma^{-1}A^H$,$\Gamma = \text{diag}(\gamma)$。
2.2 证据最大化与超参数更新
通过期望最大化(EM)或固定点迭代最大化边缘似然。
-
E-step: 计算信号后验:
$$\Sigma = (\sigma^{-2}A^H A + \Gamma)^{-1}, \quad \mu = \sigma^{-2}\Sigma A^H y$$
-
M-step: 更新超参数(MacKay准则):
$$\gamma_g^{new} = \frac{1 - \gamma_g \Sigma_{gg}}{\|\mu_g\|_2^2 / T}$$
该更新自动修剪不重要分量:当信号能量 $\|\mu_g\|_2^2$ 小于后验不确定性 $\Sigma_{gg}$ 时,$\gamma_g$ 趋于无穷,对应分量被置零。
2.3 离网细化与网格自适应
固定网格存在基不匹配(Basis Mismatch)。离网SBL通过线性化流形导数修正网格点:
$$\Delta\theta_g = \frac{\text{Re}\{\mu_g^H A'(\theta_g)^H C^{-1} Y\}}{\|\mu_g\|^2 \cdot \|A'(\theta_g)\|_F^2}$$
其中 $A'(\theta_g) = \partial a(\theta)/\partial\theta |_{\theta_g}$。通过迭代更新 $\theta_g \leftarrow \theta_g + \Delta\theta_g$ 实现无网格精度。
3. 结构化协方差矩阵重构
3.1 原子范数与半正定刻画
阵列协方差矩阵具有Toeplitz结构加秩约束。原子范数(Atomic Norm)定义为:
$$\|R\|_{\mathcal{A}} = \inf\{t > 0 : R \in t \cdot \text{conv}(\mathcal{A})\}$$
其中原子集 $\mathcal{A} = \{a(\theta)a(\theta)^H : \theta \in [-\pi, \pi]\}$。通过半正定规划(SDP)等价刻画:
$$\|R\|_{\mathcal{A}} = \frac{1}{2N} \min_{u} \{ \text{Tr}(\mathcal{T}(u)) + \text{Tr}(X) : \begin{bmatrix} \mathcal{T}(u) & R \\ R^H & X \end{bmatrix} \succeq 0 \}$$
其中 $\mathcal{T}(u)$ 为由 $u$ 生成的Toeplitz矩阵。
3.2 Vandermonde分解与Toeplitz结构
正定Toeplitz矩阵具有Vandermonde分解:
$$\mathcal{T}(u) = \sum_{k=1}^K p_k a(\theta_k)a(\theta_k)^H = APA^H$$
其中 $p_k > 0$ 为信号功率。该结构将协方差估计转化为半正定Toeplitz矩阵恢复问题。
3.3 对偶多项式与谱峰定位
原子范数最小化的对偶问题构造对偶多项式:
$$Q(\theta) = a(\theta)^H Q a(\theta)$$
根据互补松弛条件,真实角度满足 $|Q(\theta_k)| = 1$,其余位置 $|Q(\theta)| < 1$。通过寻找 $Q(\theta)$ 的谱峰定位DOA。
4. 交替方向乘子法鲁棒波束成形
4.1 分布式优化与变量分裂
鲁棒波束成形求解含不确定性的非凸问题。ADMM通过变量分裂将问题分解:
$$\min_{w, \{Z_q\}} \sum_{q=1}^Q f_q(Z_q) + g(w) \quad \text{s.t.} \ Z_q = ww^H$$
增广拉格朗日函数:
$$\mathcal{L} = \sum_{q=1}^Q \left( f_q(Z_q) + \langle \Lambda_q, Z_q - ww^H \rangle + \frac{\rho}{2}\|Z_q - ww^H\|_F^2 \right) + g(w)$$
4.2 谱约束投影与不确定性集
对频带/子阵协方差 $\hat{R}_q$ 的鲁棒处理引入不确定性椭球:
$$\mathcal{R}_q = \{R : \|R - \hat{R}_q\|_F \leq \epsilon_q, R \succeq 0\}$$
$Z_q$ 更新归结为到不确定性集的投影:
$$Z_q^{k+1} = \mathcal{P}_{\mathcal{R}_q}(w^k(w^k)^H - \Lambda_q^k / \rho)$$
4.3 自适应惩罚参数调整
ADMM收敛性依赖于惩罚参数 $\rho$。自适应策略根据原始残差 $r^k$ 与对偶残差 $s^k$ 动态调整:
$$\rho^{k+1} = \begin{cases} 2\rho^k & \text{if } \|r^k\| > 10\|s^k\| \\ \rho^k/2 & \text{if } \|s^k\| > 10\|r^k\| \\ \rho^k & \text{otherwise} \end{cases}$$
5. 张量CP分解多参数估计
5.1 多维接收数据张量模型
接收数据可组织为三阶张量 $\mathcal{Y} \in \mathbb{C}^{N \times T \times M}$(空间×时间×极化/频率)。CP分解表示为:
$$\mathcal{Y} = \sum_{r=1}^R \lambda_r a_r \circ d_r \circ p_r + \mathcal{N}$$
其中 $\circ$ 为外积,$a_r, d_r, p_r$ 分别为空间、多普勒、极化因子向量。
5.2 交替最小二乘与高维扩展
ALS迭代更新各因子矩阵。对于空间因子 $A$:
$$A = Y_{(1)}(C \odot B)((C^H C) * (B^H B))^{-1}$$
其中 $Y_{(1)}$ 为张量模-1展开,$\odot$ 为Khatri-Rao积,$*$ 为Hadamard积。
5.3 流形约束投影与耦合矩阵
利用Vandermonde结构约束:多普勒因子 $d_r$ 应满足 $[1, e^{j\omega_r}, \dots, e^{j\omega_r(T-1)}]^T$。通过投影到最近Vandermonde向量保持物理可解释性:
$$\min_{\omega} \|d - [1, e^{j\omega}, \dots]^T\|_2^2 \Rightarrow \omega = \text{angle}\left(\sum_{t=0}^{T-2} d_{t+1} d_t^*\right)$$
6. 深度展开网络自适应波束成形
6.1 算法展开与可学习参数
将迭代优化算法展开为神经网络层。第 $l$ 层对应一次迭代:
$$w^l = w^{l-1} - \alpha_l \nabla f(w^{l-1}) + \beta_l(w^{l-1} - w^{l-2})$$
其中步长 $\alpha_l$、动量 $\beta_l$ 及正则化参数 $\lambda_l$ 变为可学习参数。
6.2 模型驱动与数据驱动融合
网络结构嵌入物理约束(如 $w^H a(\theta_0) = 1$)作为硬约束层。前向传播保证约束满足,反向传播优化性能相关参数。
6.3 梯度流与约束保持层
使用黎曼梯度下降处理流形约束。对恒模约束 $|w_i| = c$,投影梯度为:
$$\nabla_{\mathcal{R}}f = \nabla f - \text{Re}\{\nabla f \odot w^*\} \odot w / c^2$$
7. 离网连续压缩感知
7.1 无网格原子范数最小化
直接在连续域最小化原子范数以避免网格:
$$\min_{R} \|R\|_{\mathcal{A}} \quad \text{s.t.} \ \|Y - R\|_F \leq \sigma$$
7.2 半正定规划与对偶理论
等价SDP形式:
$$\min_{u, t} \frac{1}{2} \text{Tr}(\mathcal{T}(u)) + \frac{1}{2}t \quad \text{s.t.} \ \begin{bmatrix} \mathcal{T}(u) & Y \\ Y^H & tI \end{bmatrix} \succeq 0$$
对偶问题最大化 $\text{Re}\langle Y, Q \rangle$ 受限于 $\|A^H Q\|_{2,\infty} \leq 1$。
7.3 多项式求根与连续参数恢复
对偶解 $Q$ 构造多项式:
$$P(z) = v(z)^H Q v(z), \quad v(z) = [1, z, \dots, z^{N-1}]^T$$
求根 $|z_k| = 1$ 对应信号方向 $\theta_k = \arcsin\left(\frac{\lambda}{2\pi d} \arg(z_k)\right)$,实现真正无网格估计。
算法1: 稀疏贝叶斯学习阵列流形估计 (Sparse Bayesian Learning for Array Manifold Estimation)
功能: 利用SBL框架从有限快拍中估计结构化阵列流形与到达角
Input:
Y ∈ ℂ^(N×K) // 接收数据矩阵 (N阵元, K快拍)
Θ_grid // 角度网格 {θ_1,...,θ_G}
α_init, β_init // 超参数初始值
Output:
Σ_post // 后验协方差
μ_post // 后验均值 (稀疏信号)
θ_est // 估计DOA集合
初始化:
Γ ← α_init·I_G; // 信号精度对角矩阵
β ← β_init; // 噪声精度
̂H ← ∅; // 活跃索引集
while (未收敛) do
// E-step: 计算后验统计量
Σ_post ← (β·A^H·A + Γ^(-1))^(-1);
μ_post ← β·Σ_post·A^H·Y;
// M-step: 更新超参数 (MacKay准则)
for g = 1:G do
γ_g ← (‖[μ_post]_g‖_2^2) / (K·[Σ_post]_gg);
if (γ_g^(-1) > Threshold) then
̂H ← ̂H ∪ {g};
end
end
β ← (NK) / (‖Y - A·μ_post‖_F^2 + K·Tr(A·Σ_post·A^H));
// 网格细化 (Off-grid refinement)
if (‖Δθ‖ > ε_grid) then
θ_g ← θ_g + Re{[μ_post]_g^H·(∂A/∂θ_g)^H·(Y-A·μ_post)} /
(β^(-1)·‖[μ_post]_g‖^2 + Tr(∂^2A/∂θ_g^2));
end
收敛检验: ΔL < ε;
end
θ_est ← {θ_g | g ∈ ̂H};
return (Σ_post, μ_post, θ_est);
算法2: 结构化协方差矩阵重构 (Structured Covariance Matrix Reconstruction)
功能: 利用阵列几何结构从采样协方差恢复真实协方差,抑制有限快拍效应
Input:
̂R ∈ ℂ^(N×N) // 采样协方差矩阵
A(Θ) // 阵列流形字典
rank_max // 最大信号子空间维数
Output:
R_opt // 重构协方差矩阵
σ_n^2 // 估计噪声功率
初始化:
̂R ← ̂R + δI; // 对角加载正则化
U_s, Λ_s ← ̂R 的前rank_max个特征向量/值; // SVD分解
// 原子范数最小化 (Atomic Norm Minimization)
while (对偶间隙 > ε) do
// 半正定规划求解
Q ← T*(u); // Toeplitz矩阵构造
maximize: Tr(̂R·Q) - Tr(Q);
subject to: ‖A(θ)^H·Q·A(θ)‖ ≤ 1, ∀θ ∈ [-π/2,π/2];
// 多项式求根定位信号
f(θ) ← a(θ)^H·Q·a(θ);
θ_est ← arg_loc min_θ f(θ); // 谱峰搜索
// 振幅估计 (最小二乘)
P ← |diag((A^H·A)^(-1)·A^H·̂R·A·(A^H·A)^(-1))|;
// 协方差重构
R_opt ← A(θ_est)·P·A(θ_est)^H + σ_n^2·I;
σ_n^2 ← (Tr(̂R) - Tr(A(θ_est)·P·A(θ_est)^H)) / (N - rank_max);
对偶间隙 ← |Tr(̂R·Q) - ‖R_opt‖_*|;
end
return (R_opt, σ_n^2);
算法3: 交替方向乘子法波束成形 (ADMM-Based Robust Beamforming)
功能: 利用ADMM求解带结构约束的鲁棒波束成形非凸优化问题
Input:
̂R_1,...,̂R_Q // Q个频带/子阵的采样协方差
θ_0 // 期望信号方向
ε // 不确定性上界
ρ > 0 // ADMM惩罚参数
Output:
w_opt // 最优权重向量
初始化:
w ← ̂R^(-1)·a(θ_0) / (a(θ_0)^H·̂R^(-1)·a(θ_0)); // MVDR初始化
{Z_q} ← 0; // 对偶变量集合
{U_q} ← 0; // 辅助变量集合
while (原始残差 > ε_prim ∧ 对偶残差 > ε_dual) do
// w-update (加权MVDR)
R_sum ← ∑_{q=1}^Q (̂R_q + ρ·(Z_q - U_q));
w ← R_sum^(-1)·a(θ_0) / (a(θ_0)^H·R_sum^(-1)·a(θ_0));
// Z_q-update (谱约束投影)
for q = 1:Q do
V_q ← w·w^H + U_q; // 本地变量
// 特征值分解与截断
[V_vec, V_val] ← eig(V_q);
V_val_proj ← max(V_val, 0); // 半正定投影
Z_q ← V_vec·diag(V_val_proj)·V_vec^H;
// 不确定性集投影
if (‖Z_q - w·w^H‖_F > ε) then
Z_q ← w·w^H + ε·(Z_q - w·w^H) / ‖Z_q - w·w^H‖_F;
end
end
// U-update (对偶变量上升)
for q = 1:Q do
U_q ← U_q + ρ·(w·w^H - Z_q);
end
// 残差计算
r_prim ← ∑_q ‖w·w^H - Z_q‖_F;
r_dual ← ρ·∑_q ‖Z_q^(k) - Z_q^(k-1)‖_F;
// 自适应惩罚参数调整
if (r_prim > 10·r_dual) then
ρ ← 2·ρ;
else if (r_dual > 10·r_prim) then
ρ ← ρ/2;
end
end
w_opt ← w;
return w_opt;
算法4: 张量分解多参数估计 (Tensor CP-Decomposition for Multiparameter Estimation)
功能: 利用接收数据的张量结构联合估计DOA-Doppler-极化参数
Input:
𝒴 ∈ ℂ^(N×K×T) // 3维张量 (空间×快拍×时间)
R // CP秩 (信源数)
max_iter // 最大迭代数
Output:
{A_r} // 因子矩阵集合
Λ // 核心张量对角线
{θ_r, f_r} // 估计的DOA与Doppler
初始化:
A^(0) ∈ ℂ^(N×R), B^(0) ∈ ℂ^(K×R), C^(0) ∈ ℂ^(T×R); // 随机初始化
for n = 1:max_iter do
// ALS (交替最小二乘) 更新
// 更新空间因子 A
A^(n) ← 𝒴_(1)·(C^(n-1) ⊙ B^(n-1))·((C^(n-1)T·C^(n-1))*(B^(n-1)T·B^(n-1)))^(-1);
// 更新时间因子 C (Doppler)
C^(n) ← 𝒴_(3)·(B^(n-1) ⊙ A^(n))·((B^(n-1)T·B^(n-1))*(A^(n)T·A^(n)))^(-1);
// 更新快照因子 B
B^(n) ← 𝒴_(2)·(C^(n) ⊙ A^(n))·((C^(n)T·C^(n))*(A^(n)T·A^(n)))^(-1));
// 结构化约束投影
for r = 1:R do
// 流形约束: 强制Vandermonde结构 (Doppler)
c_r ← C^(n)(:,r);
c_r ← proj_Vandermonde(c_r); // 到最近Vandermonde向量投影
// 阵列流形约束 (DOA)
a_r ← A^(n)(:,r);
θ_r ← arg min_θ ‖a_r - a(θ)‖_2; // 方向搜索
A^(n)(:,r) ← a(θ_r);
end
// 收敛检验
𝒴_est ← [Λ; A^(n), B^(n), C^(n)]; // CP重构
if (‖𝒴 - 𝒴_est‖_F < ε) then
break;
end
end
return ({A^(n), B^(n), C^(n)}, {θ_r}, {f_r});
算法5: 深度展开网络自适应波束成形 (Deep Unfolding for Adaptive Beamforming)
功能: 将迭代优化算法展开为可训练神经网络层,融合模型驱动与数据驱动
Input:
Y // 训练数据集 {Y_1,...,Y_M}
L // 展开层数 (迭代深度)
Θ_init // 初始化参数集 {ρ^(l), α^(l)}_(l=1)^L
Output:
Θ* // 训练后参数
W_net // 网络权重 (如存在可学习残差)
// 前向传播 (模型驱动层)
function FORWARD(Y, Θ):
R ← Y·Y^H / K; // 采样协方差
for l = 1:L do
// 第l层: 梯度下降步骤
g^(l) ← ∇_w f(w^(l-1), R; Θ^(l)); // 目标函数梯度
// 可学习步长与动量
w^(l) ← w^(l-1) - α^(l)·g^(l) + β^(l)·(w^(l-1) - w^(l-2));
// 可学习正则化投影
w^(l) ← PROX_λ^(l)(w^(l)); // 近端算子
// 流形约束硬编码 (不可学习)
w^(l) ← w^(l) / (a(θ_0)^H·w^(l)); // 无失真约束
end
return w^(L);
// 训练循环
while (验证误差未收敛) do
for each mini-batch Y_m do
w_m ← FORWARD(Y_m, Θ);
// 损失函数: 输出SINR负值
L_m ← -|w_m^H·a(θ_0)|^2 / (w_m^H·R·w_m);
// 反向传播更新参数
Θ ← Adam(∇_Θ L_m, Θ);
end
// 早停检验
if (验证集损失上升) then
学习率 ← 0.1·学习率;
end
end
Θ* ← Θ;
return Θ*;
算法6: 离网连续压缩感知 (Off-Grid Continuous Compressive Sensing)
功能: 通过原子范数最小化实现无网格DOA估计,克服基不匹配效应
Input:
Y ∈ ℂ^(N×K) // 接收数据
noise_level // 噪声功率上界 σ^2
Output:
T(u)* // Toeplitz正定矩阵
{θ_i}_(i=1)^r // 连续角度估计
初始化:
u ← FFT(Y·Y^H第一列); // 初始化为DFT系数
// 半正定规划 (SDP) 求解
minimize: (1/2)·‖Y - T(u)·X‖_F^2 + η·Tr(T(u));
subject to:
[ T(u) Y ]
[ Y^H I ] ≽ 0; // 矩阵锥约束
while (对偶间隙 > ε) do
// 对偶问题求解 (内点法)
Q ← 求解对偶SDP;
// 多项式求根
Find {θ_i} s.t. a(θ)^H·Q·a(θ) = 1; // 谱峰定位
// 振幅恢复 (最小二乘)
A_θ ← [a(θ_1),...,a(θ_r)];
S ← (A_θ^H·A_θ)^(-1)·A_θ^H·Y;
// 更新u (Vandermonde分解系数)
u ← ∑_(i=1)^r |s_i|^2·e^(j·2π·d·sin(θ_i)·n); // n = 0,...,N-1
// 噪声水平自适应调整
if (残差 < noise_level) then
η ← 0.9·η;
end
end
// 提取连续角度
θ_i ← arcsin(angle(u_1)/(2πd)); // 从相位提取
return (T(u)*, {θ_i});
python实现
第二部分:代码实现
脚本1: 稀疏贝叶斯学习阵列流形估计与DOA估计
脚本功能:
实现基于稀疏贝叶斯学习(SBL)的离网DOA估计。包含层次贝叶斯模型、证据最大化(EM)迭代、自动相关性确定(ARD)与网格细化。适用于欠定条件下(少快拍)的高分辨率DOA估计。
使用方式:
配置阵列参数、角度网格与快拍数据,运行脚本执行SBL迭代,输出稀疏谱、估计角度与后验协方差。支持离网细化提升估计精度。
"""
Script 1: Sparse Bayesian Learning (SBL) for Array Manifold Estimation and DOA Estimation
Author: Implementation of Pesavento & Trinh-Hoang (2023) - SBL Framework
Description: Off-grid DOA estimation using Sparse Bayesian Learning with automatic relevance determination
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import inv, solve
import seaborn as sns
class SparseBayesianLearningDOA:
"""
SBL-based DOA estimation with off-grid refinement
Implements the evidence maximization framework with MacKay updates
"""
def __init__(self, array_positions, wavelength, grid_resolution=1.0):
"""
Initialize SBL estimator
Parameters:
-----------
array_positions : ndarray (N,)
Element positions in wavelengths
wavelength : float
Signal wavelength
grid_resolution : float
Initial grid resolution in degrees
"""
self.N = len(array_positions)
self.positions = array_positions
self.lambda_ = wavelength
self.grid_res = grid_resolution
self.k = 2 * np.pi / wavelength
def steering_vector(self, theta):
"""Compute steering vector for angle theta (radians)"""
return np.exp(1j * self.k * self.positions * np.sin(theta))
def construct_dictionary(self, theta_grid):
"""
Construct dictionary matrix A over angle grid
Parameters:
-----------
theta_grid : ndarray (G,)
Grid of angles in radians
Returns:
--------
A : ndarray (N, G)
Dictionary matrix
"""
G = len(theta_grid)
A = np.zeros((self.N, G), dtype=complex)
for i, theta in enumerate(theta_grid):
A[:, i] = self.steering_vector(theta)
return A
def sbl_em_iteration(self, Y, A, gamma, sigma2, update_grid=False):
"""
Single EM iteration for SBL
Parameters:
-----------
Y : ndarray (N, T)
Received data (T snapshots)
A : ndarray (N, G)
Dictionary matrix
gamma : ndarray (G,)
Current precision vector
sigma2 : float
Current noise variance
update_grid : bool
Whether to perform off-grid refinement
Returns:
--------
gamma_new : ndarray (G,)
Updated precision
sigma2_new : float
Updated noise variance
mu : ndarray (G, T)
Posterior mean
Sigma : ndarray (G, G)
Posterior covariance
"""
N, G = A.shape
T = Y.shape[1]
# E-step: Compute posterior statistics
Gamma_diag = np.diag(gamma)
# Sigma = (sigma2 * Gamma + A^H A)^{-1} * sigma2
# More stable computation using matrix inversion lemma
try:
Sigma = inv(Gamma_diag + (A.conj().T @ A) / sigma2)
except np.linalg.LinAlgError:
Sigma = inv(Gamma_diag + (A.conj().T @ A) / sigma2 + 1e-6 * np.eye(G))
mu = (Sigma @ A.conj().T @ Y) / sigma2 # (G, T)
# M-step: Update hyperparameters (MacKay criterion)
gamma_new = np.zeros(G)
for g in range(G):
# Evidence approximation: gamma_g = (1 - gamma_g * Sigma_gg) / (||mu_g||^2 / T)
mu_g_norm_sq = np.linalg.norm(mu[g, :])**2
gamma_g = (1.0 - gamma[g] * Sigma[g, g].real) / (mu_g_norm_sq / T + 1e-10)
gamma_new[g] = max(gamma_g, 1e-10) # Prevent numerical issues
# Update noise variance
residual = Y - A @ mu
sigma2_new = (np.linalg.norm(residual)**2 + T * np.trace(A @ Sigma @ A.conj().T).real) / (N * T)
sigma2_new = max(sigma2_new, 1e-10)
return gamma_new, sigma2_new, mu, Sigma
def off_grid_refinement(self, Y, A, mu, gamma, theta_grid):
"""
Off-grid refinement using linear approximation of array manifold
Parameters:
-----------
Y : ndarray (N, T)
A : ndarray (N, G)
mu : ndarray (G, T)
gamma : ndarray (G,)
theta_grid : ndarray (G,)
Returns:
--------
theta_refined : ndarray (G,)
Refined angle grid
A_refined : ndarray (N, G)
Updated dictionary
"""
G = len(theta_grid)
N = self.N
T = Y.shape[1]
# Compute derivative of steering vector
A_deriv = np.zeros_like(A)
for g, theta in enumerate(theta_grid):
deriv = 1j * self.k * self.positions * np.cos(theta) * self.steering_vector(theta)
A_deriv[:, g] = deriv
theta_refined = theta_grid.copy()
# Refine active components only
active_idx = np.where(gamma < np.mean(gamma) * 0.1)[0] # Threshold for activity
for g in active_idx:
if np.linalg.norm(mu[g, :]) > 1e-3:
# Compute update direction
num = np.real(mu[g, :].conj() @ (A_deriv[:, g].conj().T @ Y))
den = np.linalg.norm(mu[g, :])**2 * np.linalg.norm(A_deriv[:, g])**2
if den > 1e-10:
delta_theta = (num / den).real
# Limit update to avoid divergence
delta_theta = np.clip(delta_theta, -0.1, 0.1)
theta_refined[g] += delta_theta
# Reconstruct dictionary
A_refined = self.construct_dictionary(theta_refined)
return theta_refined, A_refined
def estimate(self, Y, theta_range=(-90, 90), n_grid=180,
max_iter=100, tol=1e-6, off_grid=True):
"""
Main SBL estimation routine
Parameters:
-----------
Y : ndarray (N, T)
Received data matrix
theta_range : tuple
Angle search range in degrees
n_grid : int
Number of grid points
max_iter : int
Maximum EM iterations
tol : float
Convergence tolerance
off_grid : bool
Enable off-grid refinement every 10 iterations
Returns:
--------
results : dict
Contains 'theta_est', 'power_spectrum', 'gamma_history', etc.
"""
# Initialize grid
theta_grid = np.linspace(np.radians(theta_range[0]),
np.radians(theta_range[1]), n_grid)
A = self.construct_dictionary(theta_grid)
# Initialize hyperparameters
gamma = np.ones(n_grid) # Equal precision initially
sigma2 = np.var(Y) * 0.5 # Initial noise estimate
gamma_history = []
sigma2_history = []
print("Starting SBL iterations...")
for iteration in range(max_iter):
# EM update
gamma_new, sigma2_new, mu, Sigma = self.sbl_em_iteration(
Y, A, gamma, sigma2, update_grid=False
)
# Off-grid refinement
if off_grid and iteration > 0 and iteration % 10 == 0:
theta_grid, A = self.off_grid_refinement(Y, A, mu, gamma_new, theta_grid)
# Check convergence
delta_gamma = np.linalg.norm(gamma_new - gamma) / np.linalg.norm(gamma)
gamma = gamma_new
sigma2 = sigma2_new
gamma_history.append(gamma.copy())
sigma2_history.append(sigma2)
if iteration % 20 == 0:
active = np.sum(gamma < np.max(gamma) * 0.01)
print(f" Iter {iteration}: Active components = {active}, sigma2 = {sigma2:.6f}")
if delta_gamma < tol:
print(f" Converged at iteration {iteration}")
break
# Extract estimated DOAs from active components
power_spectrum = 1.0 / (gamma + 1e-10) # Lower gamma = higher power
threshold = np.max(power_spectrum) * 0.1
detected_idx = np.where(power_spectrum > threshold)[0]
theta_est = np.degrees(theta_grid[detected_idx])
results = {
'theta_grid_deg': np.degrees(theta_grid),
'power_spectrum': power_spectrum,
'theta_est': theta_est,
'gamma': gamma,
'sigma2': sigma2,
'mu': mu,
'Sigma': Sigma,
'gamma_history': gamma_history,
'sigma2_history': sigma2_history,
'iterations': len(gamma_history)
}
return results
def visualize_results(self, results, true_angles=None):
"""Comprehensive visualization of SBL results"""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. Spatial spectrum
ax1 = axes[0, 0]
ax1.plot(results['theta_grid_deg'], 10*np.log10(results['power_spectrum'] + 1e-10),
linewidth=2, color='blue', label='SBL Power Spectrum')
if true_angles is not None:
for ang in true_angles:
ax1.axvline(ang, color='red', linestyle='--', alpha=0.7, label='True DOA' if ang == true_angles[0] else "")
ax1.set_xlabel('Angle (degrees)')
ax1.set_ylabel('Power (dB)')
ax1.set_title('SBL Spatial Spectrum')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 2. Gamma evolution (sparsity)
ax2 = axes[0, 1]
gamma_hist = np.array(results['gamma_history'])
im = ax2.imshow(10*np.log10(gamma_hist.T + 1e-10), aspect='auto', cmap='hot',
extent=[0, len(gamma_hist), results['theta_grid_deg'][0],
results['theta_grid_deg'][-1]])
ax2.set_xlabel('Iteration')
ax2.set_ylabel('Angle (degrees)')
ax2.set_title('Hyperparameter Gamma Evolution (dB)')
plt.colorbar(im, ax=ax2)
# 3. Noise variance convergence
ax3 = axes[1, 0]
ax3.semilogy(results['sigma2_history'], linewidth=2, color='green')
ax3.set_xlabel('Iteration')
ax3.set_ylabel('Noise Variance (log scale)')
ax3.set_title('Noise Variance Convergence')
ax3.grid(True, alpha=0.3)
# 4. Convergence of active components
ax4 = axes[1, 1]
active_counts = [np.sum(g < np.max(g) * 0.01) for g in results['gamma_history']]
ax4.plot(active_counts, linewidth=2, color='purple', marker='o', markersize=4)
ax4.set_xlabel('Iteration')
ax4.set_ylabel('Number of Active Components')
ax4.set_title('Model Sparsity Evolution')
ax4.grid(True, alpha=0.3)
plt.suptitle('Sparse Bayesian Learning DOA Estimation Results', fontsize=14)
plt.tight_layout()
return fig
def demo_sbl_doa():
"""Demonstrate SBL DOA estimation"""
print("=" * 60)
print("Sparse Bayesian Learning (SBL) DOA Estimation")
print("=" * 60)
# Setup: 8-element ULA
N = 8
d = 0.5
positions = np.arange(N) * d
# True sources
true_angles_deg = [-30, 5, 40]
true_angles_rad = np.radians(true_angles_deg)
K = len(true_angles_deg)
# Generate signals
T = 50 # Snapshots
S = (np.random.randn(K, T) + 1j*np.random.randn(K, T)) / np.sqrt(2)
# Array manifold
A_true = np.zeros((N, K), dtype=complex)
for k, theta in enumerate(true_angles_rad):
A_true[:, k] = np.exp(1j * 2 * np.pi * positions * np.sin(theta))
# Received signal
X = A_true @ S
noise_power = 0.1
noise = np.sqrt(noise_power/2) * (np.random.randn(N, T) + 1j*np.random.randn(N, T))
Y = X + noise
print(f"Scenario: {N} elements, {K} sources at {true_angles_deg}°, {T} snapshots")
print(f"SNR: {10*np.log10(1/noise_power):.1f} dB")
# SBL estimation
sbl = SparseBayesianLearningDOA(positions, wavelength=1.0, grid_resolution=0.5)
results = sbl.estimate(Y, theta_range=(-90, 90), n_grid=180,
max_iter=100, off_grid=True)
print(f"\nEstimated DOAs: {results['theta_est']}")
print(f"True DOAs: {true_angles_deg}")
# Visualize
sbl.visualize_results(results, true_angles=true_angles_deg)
plt.savefig('sbl_doa_estimation.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_sbl_doa()
print("\nVisualization saved: sbl_doa_estimation.png")
脚本2: 结构化协方差矩阵原子范数重构
脚本功能:
实现基于原子范数最小化(ANM)的协方差矩阵重构。利用Toeplitz结构先验与半正定规划恢复信号子空间,通过Vandermonde分解实现无网格DOA估计。适用于相干信号源与少快拍场景。
使用方式:
输入采样协方差矩阵,配置正则化参数,执行半正定规划求解,输出重构Toeplitz矩阵与谱峰定位结果。
"""
Script 2: Structured Covariance Matrix Reconstruction via Atomic Norm Minimization
Author: Implementation of Pesavento & Trinh-Hoang (2023) - Atomic Norm Framework
Description: Gridless DOA estimation using structured matrix reconstruction and dual polynomial
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, hankel, eigvals, eigh
from scipy.optimize import minimize, LinearConstraint
import cvxpy as cp # For SDP solving (requires installation: pip install cvxpy)
class AtomicNormCovarianceReconstruction:
"""
Atomic norm minimization for covariance matrix reconstruction
Exploits Toeplitz structure and Vandermonde decomposition
"""
def __init__(self, array_positions, wavelength):
"""
Initialize ANM estimator
Parameters:
-----------
array_positions : ndarray (N,)
Element positions (uniform linear array assumed for Toeplitz structure)
wavelength : float
Signal wavelength
"""
self.N = len(array_positions)
self.positions = array_positions
self.lambda_ = wavelength
self.k = 2 * np.pi / wavelength
def construct_toeplitz(self, u):
"""
Construct Hermitian Toeplitz matrix from first column u
Parameters:
-----------
u : ndarray (N,)
First column of Toeplitz matrix
Returns:
--------
T : ndarray (N, N)
Hermitian Toeplitz matrix T(u)
"""
# u[0] must be real for Hermitian Toeplitz
u = np.array(u)
if not np.isreal(u[0]):
u[0] = u[0].real
return toeplitz(u)
def atomic_norm_minimization(self, Y, noise_level=None, use_cvxpy=True):
"""
Solve atomic norm minimization via SDP
minimize ||T(u)||_* + ||X||_*
s.t. [T(u), Y; Y^H, X] >= 0
Parameters:
-----------
Y : ndarray (N, T)
Received data
noise_level : float or None
If provided, use denoising formulation: minimize ||T(u)||_* s.t. ||Y-T(u)||_F <= noise_level
use_cvxpy : bool
Use CVXPY for SDP (if False, use simplified subspace method)
Returns:
--------
T_opt : ndarray (N, N)
Optimized Toeplitz matrix
u_opt : ndarray (N,)
Toeplitz generator
"""
N = self.N
T = Y.shape[1]
if use_cvxpy:
try:
return self._solve_sdp_cvxpy(Y, noise_level)
except Exception as e:
print(f"CVXPY failed ({e}), falling back to subspace method")
return self._subspace_method(Y)
else:
return self._subspace_method(Y)
def _solve_sdp_cvxpy(self, Y, noise_level):
"""Solve ANM using CVXPY SDP formulation"""
N, T = Y.shape
# Variables
u = cp.Variable(N, complex=True) # Toeplitz first column
t = cp.Variable() # Auxiliary for trace minimization
# Constraints: [T(u), Y; Y^H, t*I] >= 0
T_u = self._cvxpy_toeplitz(u)
if noise_level is None:
# Standard form: minimize 0.5*Tr(T(u)) + 0.5*t subject to PSD constraint
X = cp.Variable((N, N), hermitian=True)
t_var = cp.Variable()
# Block matrix constraint
block = cp.bmat([[T_u, Y], [Y.conj().T, t_var * np.eye(T)]])
constraints = [block >> 0, X == T_u]
objective = cp.Minimize(0.5 * cp.trace(T_u) + 0.5 * t_var)
else:
# Denoising form: minimize trace(T(u)) subject to ||Y - T(u)||_F <= noise_level
# This is a simplified version; full ANM uses atomic norm of covariance
objective = cp.Minimize(cp.trace(T_u))
constraints = [cp.norm(Y - T_u, 'fro') <= noise_level, T_u >> 0]
prob = cp.Problem(objective, constraints)
prob.solve(solver=cp.SCS, verbose=False) # Use SCS for large problems
if prob.status not in ["optimal", "optimal_inaccurate"]:
raise ValueError(f"SDP failed: {prob.status}")
u_opt = u.value
T_opt = self.construct_toeplitz(u_opt)
return T_opt, u_opt
def _cvxpy_toeplitz(self, u):
"""Helper to construct CVXPY Toeplitz matrix"""
N = len(u)
# Build Toeplitz from u: T[i,j] = u[i-j] for i>=j, else conj(u[j-i])
rows = []
for i in range(N):
row = []
for j in range(N):
if i >= j:
row.append(u[i-j])
else:
row.append(cp.conj(u[j-i]))
rows.append(row)
return cp.bmat(rows)
def _subspace_method(self, Y):
"""
Fallback subspace method using eigendecomposition of sample covariance
with Toeplitz projection
"""
# Sample covariance
R_sample = Y @ Y.conj().T / Y.shape[1]
# Project to nearest Toeplitz (simple averaging of diagonals)
N = self.N
u_proj = np.zeros(N, dtype=complex)
for i in range(N):
diag = np.diag(R_sample, i)
u_proj[i] = np.mean(diag)
T_proj = self.construct_toeplitz(u_proj)
return T_proj, u_proj
def vandermonde_decomposition(self, T_matrix, n_sources):
"""
Extract frequencies from Toeplitz matrix via Vandermonde decomposition
Uses ESPRIT-like shift invariance on signal subspace of T_matrix
Parameters:
-----------
T_matrix : ndarray (N, N)
Toeplitz matrix
n_sources : int
Number of sources to extract
Returns:
--------
angles : ndarray (n_sources,)
Estimated angles in degrees
powers : ndarray (n_sources,)
Signal powers
"""
# Eigendecomposition
eigenvalues, eigenvectors = eigh(T_matrix)
# Sort by magnitude
idx = np.argsort(eigenvalues)[::-1]
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]
# Signal subspace
E_s = eigenvectors[:, :n_sources]
# ESPRIT: shift invariance
E1 = E_s[:-1, :] # First N-1 rows
E2 = E_s[1:, :] # Last N-1 rows
# Solve shift invariance: E2 = E1 * Phi
Phi = np.linalg.lstsq(E1, E2, rcond=None)[0]
# Eigenvalues of Phi give rotation factors
phi = eigvals(Phi)
angles = np.arcsin(np.angle(phi) / (2 * np.pi * self.positions[1])) * 180 / np.pi
# Powers from eigenvalues of T
powers = eigenvalues[:n_sources].real
return angles, powers
def dual_polynomial(self, T_matrix, angle_range=(-90, 90), n_points=1000):
"""
Construct and evaluate dual polynomial for validation
Q(theta) = a(theta)^H * Q * a(theta)
where Q is from dual solution (here we use pseudo-inverse approximation)
"""
# Approximate dual variable from Toeplitz
Q = np.linalg.pinv(T_matrix)
angles = np.linspace(angle_range[0], angle_range[1], n_points)
values = np.zeros(n_points)
for i, ang_deg in enumerate(angles):
theta = np.radians(ang_deg)
a = self.steering_vector(theta)
values[i] = np.abs(a.conj().T @ Q @ a)
return angles, values
def steering_vector(self, theta):
"""Compute steering vector"""
return np.exp(1j * self.k * self.positions * np.sin(theta))
def visualize_results(self, T_opt, Y, true_angles=None, n_sources=3):
"""Visualize Toeplitz reconstruction and spectrum"""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. Toeplitz matrix structure
ax1 = axes[0, 0]
im1 = ax1.imshow(np.abs(T_opt), cmap='hot', aspect='auto')
ax1.set_title('Reconstructed Toeplitz Matrix (Magnitude)')
ax1.set_xlabel('Element Index')
ax1.set_ylabel('Element Index')
plt.colorbar(im1, ax=ax1)
# 2. Vandermonde decomposition (ESPRIT)
ax2 = axes[0, 1]
try:
angles_est, powers = self.vandermonde_decomposition(T_opt, n_sources)
ax2.stem(angles_est, powers, basefmt=' ')
if true_angles is not None:
for ang in true_angles:
ax2.axvline(ang, color='red', linestyle='--', alpha=0.5)
ax2.set_xlabel('Angle (degrees)')
ax2.set_ylabel('Power')
ax2.set_title('Vandermonde Decomposition (ESPRIT)')
ax2.grid(True, alpha=0.3)
except Exception as e:
ax2.text(0.5, 0.5, f'ESPRIT failed: {e}', ha='center')
# 3. Dual polynomial
ax3 = axes[1, 0]
angles, dual_vals = self.dual_polynomial(T_opt)
ax3.plot(angles, dual_vals, linewidth=2, color='blue')
ax3.axhline(1.0, color='red', linestyle='--', alpha=0.5, label='Unit magnitude')
if true_angles is not None:
for ang in true_angles:
ax3.axvline(ang, color='green', linestyle=':', alpha=0.5)
ax3.set_xlabel('Angle (degrees)')
ax3.set_ylabel('|Q(theta)|')
ax3.set_title('Dual Polynomial (Validation)')
ax3.legend()
ax3.grid(True, alpha=0.3)
# 4. Comparison with sample covariance
ax4 = axes[1, 1]
R_sample = Y @ Y.conj().T / Y.shape[1]
diff = np.abs(T_opt - R_sample)
im4 = ax4.imshow(diff, cmap='hot', aspect='auto')
ax4.set_title('Difference: Reconstructed vs Sample Covariance')
plt.colorbar(im4, ax=ax4)
plt.suptitle('Atomic Norm Covariance Reconstruction', fontsize=14)
plt.tight_layout()
return fig
def demo_anm_covariance():
"""Demonstrate ANM covariance reconstruction"""
print("=" * 60)
print("Atomic Norm Minimization for Structured Covariance")
print("=" * 60)
# Setup
N = 8
d = 0.5
positions = np.arange(N) * d
# True sources (coherent signals)
true_angles_deg = [20, 22] # Closely spaced
true_angles_rad = np.radians(true_angles_deg)
K = len(true_angles_deg)
# Generate coherent signals (same phase reference)
T = 30
phase = np.random.rand() * 2 * np.pi
S = np.exp(1j * phase) * (np.random.randn(K, T) + 0.1) # Correlated signals
A_true = np.zeros((N, K), dtype=complex)
for k, theta in enumerate(true_angles_rad):
A_true[:, k] = np.exp(1j * 2 * np.pi * positions * np.sin(theta))
X = A_true @ S
noise = 0.1 * (np.random.randn(N, T) + 1j*np.random.randn(N, T))
Y = X + noise
print(f"Scenario: {N} elements, {K} coherent sources at {true_angles_deg}°")
print(f"Snapshots: {T} (correlated signals)")
# ANM reconstruction
anm = AtomicNormCovarianceReconstruction(positions, wavelength=1.0)
try:
T_opt, u_opt = anm.atomic_norm_minimization(Y, noise_level=None, use_cvxpy=True)
print("SDP solved successfully")
except Exception as e:
print(f"Using subspace method due to: {e}")
T_opt, u_opt = anm.atomic_norm_minimization(Y, use_cvxpy=False)
# Visualize
anm.visualize_results(T_opt, Y, true_angles=true_angles_deg, n_sources=K)
plt.savefig('anm_covariance_reconstruction.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_anm_covariance()
print("\nVisualization saved: anm_covariance_reconstruction.png")
脚本3: ADMM鲁棒波束成形与分布式优化
脚本功能:
实现交替方向乘子法(ADMM)求解鲁棒波束成形问题。支持多子阵/多频带协方差融合,通过变量分裂与对偶上升实现分布式优化,包含自适应惩罚参数调整机制。
使用方式:
配置多个子阵协方差估计、不确定性约束与目标方向,运行ADMM迭代获得鲁棒权重向量,观察收敛过程与谱约束满足情况。
"""
Script 3: ADMM-Based Robust Beamforming and Distributed Optimization
Author: Implementation of Pesavento & Trinh-Hoang (2023) - Distributed Optimization Framework
Description: Robust beamforming using ADMM with spectral constraints and adaptive penalty
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import inv, sqrtm
class ADMMRobustBeamforming:
"""
Robust beamforming using Alternating Direction Method of Multipliers (ADMM)
Handles multiple subarrays/frequency bands with uncertainty constraints
"""
def __init__(self, n_elements, n_subarrays=1):
"""
Initialize ADMM beamformer
Parameters:
-----------
n_elements : int
Number of array elements
n_subarrays : int
Number of subarrays or frequency bands (Q in the paper)
"""
self.N = n_elements
self.Q = n_subarrays
self.rho = 1.0 # Initial penalty parameter
self.rho_history = []
self.residuals_primal = []
self.residuals_dual = []
def steering_vector(self, angle_deg, wavelength=1.0, d=0.5):
"""Compute steering vector"""
theta = np.radians(angle_deg)
k = 2 * np.pi / wavelength
positions = np.arange(self.N) * d
return np.exp(1j * k * positions * np.sin(theta))
def initialize_variables(self):
"""Initialize ADMM variables"""
# Global variable w
self.w = np.ones(self.N, dtype=complex) / np.sqrt(self.N)
# Local copies Z_q for each subarray
self.Z = [np.outer(self.w, self.w.conj()) for _ in range(self.Q)]
# Dual variables Lambda_q
self.Lambda = [np.zeros((self.N, self.N), dtype=complex) for _ in range(self.Q)]
# History
self.w_history = [self.w.copy()]
self.obj_history = []
def projection_uncertainty_set(self, M, R_hat, epsilon):
"""
Project matrix M onto uncertainty set
{R : ||R - R_hat||_F <= epsilon, R >= 0}
Parameters:
-----------
M : ndarray (N, N)
Matrix to project
R_hat : ndarray (N, N)
Nominal covariance
epsilon : float
Uncertainty radius
Returns:
--------
P : ndarray (N, N)
Projected matrix
"""
# First, project to positive semidefinite cone
eigenvalues, eigenvectors = np.linalg.eigh(M)
eigenvalues = np.maximum(eigenvalues, 0)
M_psd = eigenvectors @ np.diag(eigenvalues) @ eigenvectors.conj().T
# Then project to Frobenius norm ball
diff = M_psd - R_hat
norm_diff = np.linalg.norm(diff, 'fro')
if norm_diff <= epsilon:
return M_psd
else:
# Scale to boundary
return R_hat + (epsilon / norm_diff) * diff
def projection_psd_cone(self, M):
"""Project onto PSD cone (eigenvalue thresholding)"""
eigenvalues, eigenvectors = np.linalg.eigh(M)
eigenvalues = np.maximum(eigenvalues, 0)
return eigenvectors @ np.diag(eigenvalues) @ eigenvectors.conj().T
def admm_iteration(self, R_hats, epsilons, target_angle,
adaptive_rho=True, rho_max=100, rho_min=0.01):
"""
Single ADMM iteration
Parameters:
-----------
R_hats : list of ndarray
Sample covariances for each subarray [R_1, ..., R_Q]
epsilons : list of float
Uncertainty bounds for each subarray
target_angle : float
Target direction in degrees
adaptive_rho : bool
Enable adaptive penalty parameter
"""
a_target = self.steering_vector(target_angle)
# Step 1: Z-update (local projection to uncertainty set)
for q in range(self.Q):
# Argument for projection
arg = np.outer(self.w, self.w.conj()) - self.Lambda[q] / self.rho
self.Z[q] = self.projection_uncertainty_set(arg, R_hats[q], epsilons[q])
# Step 2: w-update (global consensus - MVDR-like solution)
# Minimize sum_q ||ww^H - Z_q - Lambda_q/rho||_F^2 subject to w^H a = 1
# This is a quadratically constrained quadratic program (QCQP)
# Approximation: use weighted average
Z_avg = np.mean(self.Z, axis=0)
Lambda_avg = np.mean(self.Lambda, axis=0)
# Effective covariance for MVDR
R_eff = Z_avg + Lambda_avg / self.rho
try:
R_inv = inv(R_eff + 0.01 * np.eye(self.N))
w_new = R_inv @ a_target
w_new = w_new / (a_target.conj().T @ w_new)
except np.linalg.LinAlgError:
# Fallback to identity
w_new = a_target / np.linalg.norm(a_target)**2
# Step 3: Dual update
for q in range(self.Q):
self.Lambda[q] += self.rho * (np.outer(w_new, w_new.conj()) - self.Z[q])
# Compute residuals for adaptive rho
primal_res = np.mean([np.linalg.norm(np.outer(w_new, w_new.conj()) - self.Z[q], 'fro')
for q in range(self.Q)])
dual_res = self.rho * np.linalg.norm(np.outer(w_new, w_new.conj()) -
np.outer(self.w, self.w.conj()), 'fro')
self.residuals_primal.append(primal_res)
self.residuals_dual.append(dual_res)
# Adaptive rho update
if adaptive_rho:
if primal_res > 10 * dual_res and self.rho < rho_max:
self.rho *= 2
elif dual_res > 10 * primal_res and self.rho > rho_min:
self.rho /= 2
self.rho_history.append(self.rho)
self.w = w_new
self.w_history.append(self.w.copy())
# Objective value (simplified)
obj = np.real(np.conj(self.w) @ np.mean(R_hats, axis=0) @ self.w)
self.obj_history.append(obj)
def optimize(self, R_hats, epsilons, target_angle, max_iter=100, tol=1e-4):
"""
Main ADMM optimization loop
Parameters:
-----------
R_hats : list of ndarray (Q elements)
Sample covariances
epsilons : list of float
Uncertainty bounds
target_angle : float
Target direction
max_iter : int
Maximum iterations
tol : float
Convergence tolerance
Returns:
--------
w_opt : ndarray
Optimized beamformer weights
"""
self.initialize_variables()
print("Starting ADMM optimization...")
for iteration in range(max_iter):
self.admm_iteration(R_hats, epsilons, target_angle, adaptive_rho=True)
if iteration % 10 == 0:
print(f" Iter {iteration}: Primal res = {self.residuals_primal[-1]:.6f}, "
f"rho = {self.rho:.3f}")
# Check convergence
if len(self.residuals_primal) > 1:
if (self.residuals_primal[-1] < tol and
self.residuals_dual[-1] < tol):
print(f" Converged at iteration {iteration}")
break
return self.w
def evaluate_beampattern(self, angles, wavelength=1.0):
"""Compute beampattern for visualization"""
pattern = np.zeros(len(angles))
for i, ang in enumerate(angles):
a = self.steering_vector(ang, wavelength)
pattern[i] = 20 * np.log10(np.abs(np.conj(self.w) @ a) + 1e-10)
return pattern
def visualize_convergence(self):
"""Visualize ADMM convergence behavior"""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. Primal and dual residuals
ax1 = axes[0, 0]
ax1.semilogy(self.residuals_primal, label='Primal Residual', linewidth=2)
ax1.semilogy(self.residuals_dual, label='Dual Residual', linewidth=2)
ax1.set_xlabel('Iteration')
ax1.set_ylabel('Residual (log)')
ax1.set_title('ADMM Residuals')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 2. Adaptive penalty parameter
ax2 = axes[0, 1]
ax2.plot(self.rho_history, linewidth=2, color='green')
ax2.set_xlabel('Iteration')
ax2.set_ylabel('Penalty Parameter ρ')
ax2.set_title('Adaptive Penalty Parameter')
ax2.grid(True, alpha=0.3)
# 3. Objective function
ax3 = axes[1, 0]
ax3.plot(self.obj_history, linewidth=2, color='purple')
ax3.set_xlabel('Iteration')
ax3.set_ylabel('Objective Value')
ax3.set_title('Cost Function Evolution')
ax3.grid(True, alpha=0.3)
# 4. Weight convergence
ax4 = axes[1, 1]
w_hist_array = np.array(self.w_history)
weight_changes = [np.linalg.norm(w_hist_array[i] - w_hist_array[i-1])
for i in range(1, len(w_hist_array))]
ax4.semilogy(weight_changes, linewidth=2, color='red')
ax4.set_xlabel('Iteration')
ax4.set_ylabel('||w_k - w_{k-1}||')
ax4.set_title('Weight Vector Convergence')
ax4.grid(True, alpha=0.3)
plt.suptitle('ADMM Robust Beamforming Convergence', fontsize=14)
plt.tight_layout()
return fig
def demo_admm_robust():
"""Demonstrate ADMM robust beamforming"""
print("=" * 60)
print("ADMM Robust Beamforming with Multiple Subarrays")
print("=" * 60)
N = 8 # Elements per subarray
Q = 3 # Number of subarrays (or frequency bands)
admm = ADMMRobustBeamforming(N, Q)
# Generate different sample covariances for each subarray (modeling uncertainty)
target_angle = 0 # Broadside
jammer_angles = [-40, 30]
R_hats = []
epsilons = []
true_angles = [target_angle] + jammer_angles
for q in range(Q):
# Each subarray has slightly different characteristics
d = 0.5 + 0.05 * np.random.randn() # Position perturbation
positions = np.arange(N) * d
# Generate signals
T = 50
S = (np.random.randn(len(true_angles), T) + 1j*np.random.randn(len(true_angles), T)) / np.sqrt(2)
A = np.zeros((N, len(true_angles)), dtype=complex)
for i, ang in enumerate(true_angles):
theta = np.radians(ang)
A[:, i] = np.exp(1j * 2 * np.pi * positions * np.sin(theta))
X = A @ S
noise = 0.1 * (np.random.randn(N, T) + 1j*np.random.randn(N, T))
Y = X + noise
R_hat = Y @ Y.conj().T / T
R_hats.append(R_hat)
epsilons.append(0.5 + 0.1 * q) # Different uncertainty levels
print(f"Setup: {N} elements, {Q} subarrays, target at {target_angle}°")
print(f"Jammers at {jammer_angles}°")
# Optimize
w_opt = admm.optimize(R_hats, epsilons, target_angle, max_iter=100)
# Evaluate
angles = np.linspace(-90, 90, 361)
pattern = admm.evaluate_beampattern(angles)
# Visualization
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# Beampattern
ax1.plot(angles, pattern, linewidth=2, label='ADMM Robust')
ax1.axvline(target_angle, color='green', linestyle='--', label='Target')
for jam in jammer_angles:
ax1.axvline(jam, color='red', linestyle=':', alpha=0.5)
ax1.set_xlabel('Angle (degrees)')
ax1.set_ylabel('Power (dB)')
ax1.set_title('Robust Beampattern')
ax1.legend()
ax1.grid(True, alpha=0.3)
ax1.set_ylim(-40, 5)
# Convergence plots
admm.visualize_convergence()
plt.savefig('admm_robust_beamforming.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_admm_robust()
print("\nVisualization saved: admm_robust_beamforming.png")
脚本4: 张量CP分解多参数联合估计
脚本功能:
实现接收数据张量的典范 polyadic (CP) 分解,联合估计DOA、多普勒频率与极化参数。包含交替最小二乘(ALS)迭代与Vandermonde结构约束投影。
使用方式:
构建三维张量(空间×时间×极化),配置CP秩(信源数),执行ALS分解,提取因子矩阵并映射物理参数。
"""
Script 4: Tensor CP Decomposition for Multiparameter Estimation
Author: Implementation of Pesavento & Trinh-Hoang (2023) - Tensor Methods
Description: Joint DOA, Doppler, and polarization estimation via CP decomposition with manifold constraints
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import khatri_rao, pinv
from scipy.optimize import minimize
class TensorCPDecomposition:
"""
CP decomposition for array signal tensor with Vandermonde constraints
Supports 3-way tensor: Spatial x Temporal x Polarization
"""
def __init__(self, dims, rank):
"""
Initialize CP decomposition
Parameters:
-----------
dims : tuple (N, T, P)
Tensor dimensions (Spatial, Temporal, Polarization)
rank : int
CP rank (number of sources)
"""
self.N, self.T, self.P = dims
self.R = rank
def initialize_factors(self, method='random'):
"""Initialize factor matrices"""
if method == 'random':
self.A = np.random.randn(self.N, self.R) + 1j*np.random.randn(self.N, self.R)
self.B = np.random.randn(self.T, self.R) + 1j*np.random.randn(self.T, self.R)
self.C = np.random.randn(self.P, self.R) + 1j*np.random.randn(self.P, self.R)
# Normalize columns
for r in range(self.R):
norm = np.linalg.norm(self.A[:, r])
self.A[:, r] /= norm
self.B[:, r] *= norm
else:
# SVD-based initialization could be added here
pass
self.lambda_ = np.ones(self.R) # Diagonal scaling
# History
self.fit_history = []
self.factor_history = []
def reconstruct_tensor(self):
"""
Reconstruct tensor from CP model
X_hat = sum_{r=1}^R lambda_r * a_r \circ b_r \circ c_r
"""
# Using mode-1 unfolding: X_(1) = A * Lambda * (C \odot B)^T
C_KR_B = khatri_rao(self.C, self.B) # (P*T, R)
X1 = self.A @ np.diag(self.lambda_) @ C_KR_B.T
return X1.reshape(self.N, self.T, self.P)
def als_iteration(self, X_tensor):
"""
Alternating Least Squares iteration
Parameters:
-----------
X_tensor : ndarray (N, T, P)
Observed tensor
"""
# Mode-1 unfolding (Spatial)
X1 = X_tensor.reshape(self.N, self.T * self.P)
C_KR_B = khatri_rao(self.C, self.B)
self.A = X1 @ np.conj(C_KR_B) @ pinv(C_KR_B.T @ np.conj(C_KR_B))
# Mode-2 unfolding (Temporal/Doppler)
X2 = X_tensor.transpose(1, 0, 2).reshape(self.T, self.N * self.P)
C_KR_A = khatri_rao(self.C, self.A)
self.B = X2 @ np.conj(C_KR_A) @ pinv(C_KR_A.T @ np.conj(C_KR_A))
# Apply Vandermonde constraint to B (Doppler structure)
self._project_vandermonde_B()
# Mode-3 unfolding (Polarization)
X3 = X_tensor.transpose(2, 0, 1).reshape(self.P, self.N * self.T)
B_KR_A = khatri_rao(self.B, self.A)
self.C = X3 @ np.conj(B_KR_A) @ pinv(B_KR_A.T @ np.conj(B_KR_A))
# Update lambda (normalize)
self.lambda_ = np.linalg.norm(self.A, axis=0)
self.A = self.A / self.lambda_
def _project_vandermonde_B(self):
"""
Project B to nearest Vandermonde matrix (harmonic retrieval)
Each column should be [1, e^{j*omega}, e^{j*2*omega}, ...]^T
"""
for r in range(self.R):
# Estimate frequency from phase progression
b_r = self.B[:, r]
# Use linear regression on phase differences
phases = np.unwrap(np.angle(b_r))
# Fit line: phase = omega * t
t = np.arange(len(phases))
omega = np.polyfit(t, phases, 1)[0]
# Reconstruct Vandermonde
b_vand = np.exp(1j * omega * t)
self.B[:, r] = b_vand / np.linalg.norm(b_vand) * np.linalg.norm(b_r)
def fit(self, X_tensor, max_iter=100, tol=1e-6):
"""
Main CP decomposition loop
Parameters:
-----------
X_tensor : ndarray (N, T, P)
Observed tensor
max_iter : int
Maximum ALS iterations
tol : float
Convergence tolerance
Returns:
--------
factors : dict
{'A': spatial, 'B': temporal, 'C': polarization, 'lambda': weights}
"""
self.initialize_factors()
X_flat = X_tensor.flatten()
norm_X = np.linalg.norm(X_flat)
print("Starting CP-ALS iterations...")
for iteration in range(max_iter):
self.als_iteration(X_tensor)
# Compute fit
X_hat = self.reconstruct_tensor()
residual = X_tensor - X_hat.reshape(self.N, self.T, self.P)
fit = 1 - np.linalg.norm(residual.flatten()) / norm_X
self.fit_history.append(fit)
self.factor_history.append((self.A.copy(), self.B.copy(), self.C.copy()))
if iteration % 10 == 0:
print(f" Iter {iteration}: Fit = {fit:.6f}")
# Check convergence
if len(self.fit_history) > 1:
if abs(self.fit_history[-1] - self.fit_history[-2]) < tol:
print(f" Converged at iteration {iteration}")
break
return {
'A': self.A,
'B': self.B,
'C': self.C,
'lambda': self.lambda_,
'fit': self.fit_history[-1]
}
def extract_parameters(self, d=0.5, wavelength=1.0, prf=1.0):
"""
Extract physical parameters from factor matrices
Returns:
--------
params : dict
{'angles': DOA in degrees, 'dopplers': normalized Doppler,
'polarizations': polarization states}
"""
# Extract DOAs from A (using subspace or peak finding)
angles = self._estimate_angles_from_A(d, wavelength)
# Extract Doppler from B phases
dopplers = self._estimate_doppler_from_B(prf)
# Extract polarization parameters from C
polarizations = self.C # Complex polarization vectors
return {
'angles': angles,
'dopplers': dopplers,
'polarizations': polarizations
}
def _estimate_angles_from_A(self, d, wavelength):
"""Estimate DOAs from spatial factor matrix A using ESPRIT"""
angles = []
for r in range(self.R):
a_r = self.A[:, r]
# Use phase slope
phases = np.unwrap(np.angle(a_r))
# Linear fit: phase = (2*pi*d/lambda)*sin(theta) * n
n = np.arange(len(phases))
slope = np.polyfit(n, phases, 1)[0]
theta = np.arcsin(np.clip(slope * wavelength / (2 * np.pi * d), -1, 1))
angles.append(np.degrees(theta))
return np.array(angles)
def _estimate_doppler_from_B(self, prf):
"""Estimate Doppler frequencies from temporal factor B"""
dopplers = []
for r in range(self.R):
b_r = self.B[:, r]
phases = np.unwrap(np.angle(b_r))
t = np.arange(len(phases))
omega = np.polyfit(t, phases, 1)[0]
# Normalized Doppler: omega / (2*pi) * (1/prf) * prf = omega / (2*pi)
fd_norm = omega / (2 * np.pi)
dopplers.append(fd_norm)
return np.array(dopplers)
def visualize_decomposition(self, X_tensor):
"""Visualize tensor decomposition results"""
fig, axes = plt.subplots(2, 3, figsize=(16, 10))
# 1. Original tensor slice
ax1 = axes[0, 0]
im1 = ax1.imshow(np.abs(X_tensor[:, :, 0]), cmap='hot', aspect='auto')
ax1.set_title('Original Tensor Slice (Polarization 1)')
ax1.set_xlabel('Time')
ax1.set_ylabel('Space')
plt.colorbar(im1, ax=ax1)
# 2. Reconstructed tensor
X_hat = self.reconstruct_tensor().reshape(self.N, self.T, self.P)
ax2 = axes[0, 1]
im2 = ax2.imshow(np.abs(X_hat[:, :, 0]), cmap='hot', aspect='auto')
ax2.set_title('Reconstructed Tensor (CP Model)')
ax2.set_xlabel('Time')
ax2.set_ylabel('Space')
plt.colorbar(im2, ax=ax2)
# 3. Residual
ax3 = axes[0, 2]
im3 = ax3.imshow(np.abs(X_tensor - X_hat)[:, :, 0], cmap='hot', aspect='auto')
ax3.set_title('Residual')
ax3.set_xlabel('Time')
ax3.set_ylabel('Space')
plt.colorbar(im3, ax=ax3)
# 4. Factor matrices
ax4 = axes[1, 0]
ax4.plot(np.abs(self.A), marker='o', label=[f'Source {i+1}' for i in range(self.R)])
ax4.set_title('Spatial Factor A (Array Response)')
ax4.set_xlabel('Element Index')
ax4.set_ylabel('Magnitude')
ax4.legend()
ax4.grid(True, alpha=0.3)
# 5. Temporal factor (Doppler)
ax5 = axes[1, 1]
for r in range(self.R):
ax5.plot(np.angle(self.B[:, r]), marker='o', label=f'Source {r+1}')
ax5.set_title('Temporal Factor B (Doppler Phase)')
ax5.set_xlabel('Time Sample')
ax5.set_ylabel('Phase (rad)')
ax5.legend()
ax5.grid(True, alpha=0.3)
# 6. Convergence
ax6 = axes[1, 2]
ax6.plot(self.fit_history, linewidth=2)
ax6.set_title('CP-ALS Convergence')
ax6.set_xlabel('Iteration')
ax6.set_ylabel('Fit (1 - normalized residual)')
ax6.grid(True, alpha=0.3)
plt.suptitle('Tensor CP Decomposition for Array Signal Processing', fontsize=14)
plt.tight_layout()
return fig
def demo_tensor_cp():
"""Demonstrate tensor CP decomposition"""
print("=" * 60)
print("Tensor CP Decomposition for Joint Parameter Estimation")
print("=" * 60)
# Setup: 8 elements, 32 time samples, 2 polarizations
N, T, P = 8, 32, 2
R = 2 # Two sources
# True parameters
true_angles = [-20, 30] # degrees
true_dopplers = [0.1, -0.2] # normalized frequency
# Generate tensor
tensor = np.zeros((N, T, P), dtype=complex)
for r in range(R):
# Spatial factor (steering vector)
theta = np.radians(true_angles[r])
a = np.exp(1j * 2 * np.pi * np.arange(N) * 0.5 * np.sin(theta))
# Temporal factor (Doppler)
fd = true_dopplers[r]
b = np.exp(1j * 2 * np.pi * fd * np.arange(T))
# Polarization factor
c = np.random.randn(P) + 1j*np.random.randn(P)
c = c / np.linalg.norm(c)
# Outer product
for p in range(P):
tensor[:, :, p] += np.outer(a, b) * c[p]
# Add noise
noise = 0.1 * (np.random.randn(N, T, P) + 1j*np.random.randn(N, T, P))
tensor_noisy = tensor + noise
print(f"Tensor dimensions: {tensor.shape}")
print(f"True angles: {true_angles}°")
print(f"True Dopplers: {true_dopplers}")
# Decompose
cpd = TensorCPDecomposition((N, T, P), R)
factors = cpd.fit(tensor_noisy, max_iter=100)
# Extract parameters
params = cpd.extract_parameters(d=0.5, wavelength=1.0)
print(f"\nEstimated angles: {params['angles']:.1f}°")
print(f"Estimated Dopplers: {params['dopplers']:.3f}")
# Visualize
cpd.visualize_decomposition(tensor_noisy)
plt.savefig('tensor_cp_decomposition.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_tensor_cp()
print("\nVisualization saved: tensor_cp_decomposition.png")
脚本5: 深度展开网络自适应波束成形
脚本功能:
实现模型驱动的深度展开网络(Deep Unrolling/Unfolding),将迭代优化算法(如梯度下降或ADMM)展开为可训练神经网络层,融合物理模型与数据驱动学习。
使用方式:
定义展开层数(迭代深度),构建可学习参数(步长、正则化系数),使用合成数据训练网络,评估训练后网络在测试数据上的波束成形性能。
"""
Script 5: Deep Unfolding Network for Adaptive Beamforming
Author: Implementation of Pesavento & Trinh-Hoang (2023) - Deep Learning Integration
Description: Model-driven deep unfolding architecture for adaptive beamforming
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import inv
import torch
import torch.nn as nn
class DeepUnfoldingBeamformer(nn.Module):
"""
Deep unfolding network for MVDR beamforming
Unfolds gradient descent iterations into learnable layers
"""
def __init__(self, n_elements, n_layers=5):
"""
Initialize deep unfolding network
Parameters:
-----------
n_elements : int
Number of array elements
n_layers : int
Number of unfolding layers (iterations)
"""
super(DeepUnfoldingBeamformer, self).__init__()
self.N = n_elements
self.L = n_layers
# Learnable parameters for each layer
# Step sizes (alpha), momentum coefficients (beta), regularization (lambda)
self.alphas = nn.Parameter(torch.ones(n_layers) * 0.01)
self.betas = nn.Parameter(torch.ones(n_layers) * 0.1)
self.lambdas = nn.Parameter(torch.ones(n_layers) * 0.01)
# Optional: learned initialization
self.W_init = nn.Parameter(torch.eye(n_elements, dtype=torch.complex64) * 0.1)
def forward(self, Y, a_target):
"""
Forward pass through unfolded network
Parameters:
-----------
Y : torch.Tensor (N, T)
Received signal matrix (batch dimension handled externally)
a_target : torch.Tensor (N,)
Steering vector for target direction
Returns:
--------
w : torch.Tensor (N,)
Beamformer weights
"""
# Compute sample covariance
R = torch.matmul(Y, Y.conj().T) / Y.shape[1]
# Initialize weights (data-driven or fixed)
w = torch.ones(self.N, dtype=torch.complex64, device=Y.device) / np.sqrt(self.N)
w_prev = w.clone()
# Unfolded iterations
for l in range(self.L):
# Compute gradient of MVDR objective: R*w
grad = torch.matmul(R, w)
# Gradient descent with learnable step size
w_new = w - self.alphas[l] * grad
# Proximal operator (soft thresholding) with learnable lambda
# Simplified: L2 regularization
w_new = w_new / (1 + self.lambdas[l])
# Momentum term with learnable beta
if l > 0:
w_new = w_new + self.betas[l] * (w - w_prev)
# Hard constraint: distortionless response
# w = w / (a^H w) * scale
denom = torch.dot(a_target.conj(), w_new)
w_new = w_new / (denom + 1e-10)
w_prev = w.clone()
w = w_new
return w
def compute_sinr(self, w, R_signal, R_interference):
"""Compute output SINR for loss calculation"""
# Signal power
P_sig = torch.abs(torch.dot(w.conj(), torch.matmul(R_signal, w)))
# Interference power
P_int = torch.abs(torch.dot(w.conj(), torch.matmul(R_interference, w)))
sinr = P_sig / (P_int + 1e-10)
return sinr
class DeepUnfoldingTrainer:
"""Training framework for deep unfolding network"""
def __init__(self, n_elements, n_layers=5, lr=0.001):
self.model = DeepUnfoldingBeamformer(n_elements, n_layers)
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
self.loss_history = []
def generate_training_data(self, n_samples=100, snr_range=(0, 20)):
"""
Generate synthetic training data
Returns:
--------
dataset : list of (Y, a_target, R_sig, R_int) tuples
"""
dataset = []
N = self.model.N
for _ in range(n_samples):
# Random target direction
target_angle = np.random.uniform(-60, 60)
a_target = np.exp(1j * np.pi * np.arange(N) * np.sin(np.radians(target_angle)))
# Random interferers
n_jammers = np.random.randint(1, 3)
angles_jam = np.random.uniform(-60, 60, n_jammers)
A = np.zeros((N, n_jammers+1), dtype=complex)
A[:, 0] = a_target
for i, ang in enumerate(angles_jam):
A[:, i+1] = np.exp(1j * np.pi * np.arange(N) * np.sin(np.radians(ang)))
# Generate signals
T = 50
S = (np.random.randn(n_jammers+1, T) + 1j*np.random.randn(n_jammers+1, T)) / np.sqrt(2)
X = A @ S
# Add noise
snr = np.random.uniform(*snr_range)
noise_power = 10**(-snr/10)
noise = np.sqrt(noise_power/2) * (np.random.randn(N, T) + 1j*np.random.randn(N, T))
Y = X + noise
# True covariance matrices for loss calculation
R_sig = np.outer(a_target, a_target.conj())
R_int = np.eye(N) * noise_power
for i in range(n_jammers):
a_jam = A[:, i+1]
R_int += np.outer(a_jam, a_jam.conj())
dataset.append((
torch.tensor(Y, dtype=torch.complex64),
torch.tensor(a_target, dtype=torch.complex64),
torch.tensor(R_sig, dtype=torch.complex64),
torch.tensor(R_int, dtype=torch.complex64)
))
return dataset
def train(self, n_epochs=50, batch_size=10):
"""Train the deep unfolding network"""
print("Training Deep Unfolding Network...")
dataset = self.generate_training_data(n_samples=200)
for epoch in range(n_epochs):
epoch_loss = 0
# Mini-batch training (simplified: full batch here)
for Y, a_target, R_sig, R_int in dataset[:batch_size]:
self.optimizer.zero_grad()
# Forward pass
w = self.model(Y, a_target)
# Loss: negative SINR (we want to maximize SINR)
sinr = self.model.compute_sinr(w, R_sig, R_int)
loss = -torch.log(sinr + 1e-10) # Log scale for stability
# Backward pass (simulated - PyTorch autograd handles this)
# In a real implementation, ensure all ops are differentiable
loss.backward()
self.optimizer.step()
epoch_loss += loss.item()
avg_loss = epoch_loss / batch_size
self.loss_history.append(avg_loss)
if epoch % 10 == 0:
print(f" Epoch {epoch}: Loss = {avg_loss:.4f}")
print(f" Learned alphas: {self.model.alphas.detach().numpy()[:3]}...")
def evaluate(self, test_data):
"""Evaluate on test data"""
sinrs = []
for Y, a_target, R_sig, R_int in test_data:
with torch.no_grad():
w = self.model(Y, a_target)
sinr = self.model.compute_sinr(w, R_sig, R_int)
sinrs.append(sinr.item())
return np.array(sinrs)
def visualize_learned_parameters(self):
"""Visualize learned optimization parameters"""
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
alphas = self.model.alphas.detach().numpy()
betas = self.model.betas.detach().numpy()
lambdas = self.model.lambdas.detach().numpy()
axes[0].plot(alphas, marker='o', linewidth=2)
axes[0].set_title('Learned Step Sizes (α)')
axes[0].set_xlabel('Layer')
axes[0].set_ylabel('Value')
axes[0].grid(True, alpha=0.3)
axes[1].plot(betas, marker='s', linewidth=2, color='red')
axes[1].set_title('Learned Momentum (β)')
axes[1].set_xlabel('Layer')
axes[1].set_ylabel('Value')
axes[1].grid(True, alpha=0.3)
axes[2].plot(lambdas, marker='^', linewidth=2, color='green')
axes[2].set_title('Learned Regularization (λ)')
axes[2].set_xlabel('Layer')
axes[2].set_ylabel('Value')
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
return fig
def demo_deep_unfolding():
"""Demonstrate deep unfolding for beamforming"""
print("=" * 60)
print("Deep Unfolding Network for Adaptive Beamforming")
print("=" * 60)
N = 8
L = 5 # 5 unfolding layers
trainer = DeepUnfoldingTrainer(N, n_layers=L, lr=0.01)
# Train
trainer.train(n_epochs=30, batch_size=20)
# Test
test_data = trainer.generate_training_data(n_samples=50)
sinrs = trainer.evaluate(test_data)
print(f"\nTest SINR: {np.mean(sinr):.2f} ± {np.std(sinrs):.2f} dB")
# Visualize
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
# Loss curve
ax1.plot(trainer.loss_history, linewidth=2)
ax1.set_xlabel('Epoch')
ax1.set_ylabel('Training Loss (-log SINR)')
ax1.set_title('Training Convergence')
ax1.grid(True, alpha=0.3)
# SINR distribution
ax2.hist(10*np.log10(sinrs), bins=20, edgecolor='black', alpha=0.7)
ax2.set_xlabel('Output SINR (dB)')
ax2.set_ylabel('Count')
ax2.set_title('Test Performance Distribution')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('deep_unfolding_beamforming.png', dpi=150, bbox_inches='tight')
plt.show()
# Parameter visualization
trainer.visualize_learned_parameters()
plt.savefig('deep_unfolding_parameters.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_deep_unfolding()
print("\nVisualization saved:")
print("- deep_unfolding_beamforming.png")
print("- deep_unfolding_parameters.png")
脚本6: 离网连续压缩感知无网格DOA估计
脚本功能:
实现基于原子范数最小化的无网格(Gridless)DOA估计。通过半正定规划与对偶多项式,直接在连续角度域定位信号,克服离散网格带来的基不匹配问题。
使用方式:
输入接收数据矩阵,构建Toeplitz半正定规划问题,求解对偶变量,通过对偶多项式谱峰定位恢复连续角度参数。
"""
Script 6: Off-Grid Continuous Compressive Sensing for Gridless DOA Estimation
Author: Implementation of Pesavento & Trinh-Hoang (2023) - Gridless Methods
Description: Gridless DOA estimation using atomic norm minimization and dual polynomial
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, hankel, eigh, eigvals
from scipy.optimize import minimize
import cvxpy as cp
class GridlessCompressiveSensing:
"""
Gridless DOA estimation via atomic norm minimization
Solves semi-definite program for continuous parameter estimation
"""
def __init__(self, n_elements, array_spacing=0.5):
"""
Initialize gridless estimator
Parameters:
-----------
n_elements : int
Number of array elements
array_spacing : float
Element spacing in wavelengths
"""
self.N = n_elements
self.d = array_spacing
def hermitian_toeplitz(self, u):
"""Construct Hermitian Toeplitz matrix from first column u"""
# u[0] must be real
u = np.array(u)
r = np.conj(u[0]) # First row is conjugate of first column (reversed)
return toeplitz(u, r)
def atomic_norm_minimization(self, Y, noise_level=None, method='sdp'):
"""
Solve atomic norm minimization for gridless DOA
minimize ||T(u)||_* + trace(X)
subject to [T(u), Y; Y', X] >= 0
Parameters:
-----------
Y : ndarray (N, T)
Received data
noise_level : float or None
If provided, constraint ||Y - T(u)||_F <= noise_level
method : str
'sdp' for semidefinite programming, 'subspace' for ESPRIT-like
Returns:
--------
u_opt : ndarray (N,)
Optimized Toeplitz generator
T_opt : ndarray (N, N)
Toeplitz matrix
Q_dual : ndarray (N, N) or None
Dual variable (if available)
"""
N, T = Y.shape
if method == 'sdp':
try:
return self._solve_sdp_cvxpy(Y, noise_level)
except Exception as e:
print(f"SDP solver failed: {e}")
return self._subspace_method(Y)
else:
return self._subspace_method(Y)
def _solve_sdp_cvxpy(self, Y, noise_level):
"""Solve ANM using CVXPY"""
N, T = Y.shape
# Variable: first column of Toeplitz matrix
u = cp.Variable(N, complex=True)
# Construct Toeplitz matrix T(u) in CVXPY
T_u = self._cvxpy_toeplitz(u)
if noise_level is None:
# Standard form: minimize nuclear norm proxy (trace for PSD)
# For Hermitian Toeplitz, minimize trace(T(u))
t = cp.Variable()
# Block matrix constraint
block = cp.bmat([[T_u, Y], [Y.conj().T, t * np.eye(T)]])
constraints = [block >> 0, T_u >> 0]
objective = cp.Minimize(0.5 * cp.trace(T_u) + 0.5 * t)
else:
# Denoising form
objective = cp.Minimize(cp.trace(T_u))
constraints = [cp.norm(Y - T_u, 'fro') <= noise_level, T_u >> 0]
prob = cp.Problem(objective, constraints)
# Solve using MOSEK if available, otherwise SCS
try:
prob.solve(solver=cp.MOSEK, verbose=False)
except:
prob.solve(solver=cp.SCS, verbose=False, max_iters=2000)
if prob.status not in ["optimal", "optimal_inaccurate"]:
raise ValueError(f"SDP status: {prob.status}")
u_opt = u.value
T_opt = self.hermitian_toeplitz(u_opt)
# Approximate dual variable (not directly available from CVXPY solution)
Q_dual = np.linalg.pinv(T_opt)
return u_opt, T_opt, Q_dual
def _cvxpy_toeplitz(self, u):
"""Construct CVXPY Toeplitz matrix expression"""
N = len(u)
rows = []
for i in range(N):
row = []
for j in range(N):
if i >= j:
row.append(u[i-j])
else:
row.append(cp.conj(u[j-i]))
rows.append(row)
return cp.bmat(rows)
def _subspace_method(self, Y):
"""Fallback subspace method using sample covariance projection"""
R_sample = Y @ Y.conj().T / Y.shape[1]
# Project to Toeplitz by averaging diagonals
u = np.zeros(self.N, dtype=complex)
for i in range(self.N):
diag = np.diag(R_sample, i)
u[i] = np.mean(diag)
u[0] = u[0].real # Ensure hermitian
T_opt = self.hermitian_toeplitz(u)
return u, T_opt, np.linalg.pinv(T_opt)
def dual_polynomial(self, Q, angle_resolution=0.1):
"""
Construct and evaluate dual polynomial Q(theta) = a(theta)^H Q a(theta)
Parameters:
-----------
Q : ndarray (N, N)
Dual variable (inverse of Toeplitz)
angle_resolution : float
Angle sampling resolution in degrees
Returns:
--------
angles : ndarray
Evaluation angles in degrees
values : ndarray
Dual polynomial magnitude values
peaks : ndarray
Detected peak locations (angles)
"""
angles = np.arange(-90, 90, angle_resolution)
values = np.zeros(len(angles))
for i, ang_deg in enumerate(angles):
theta = np.radians(ang_deg)
a = np.exp(1j * 2 * np.pi * self.d * np.arange(self.N) * np.sin(theta))
values[i] = np.abs(a.conj().T @ Q @ a)
# Detect peaks (where |Q(theta)| approx 1)
from scipy.signal import find_peaks
peaks, properties = find_peaks(values, height=0.8, distance=5)
peak_angles = angles[peaks]
return angles, values, peak_angles
def root_music_like(self, T_matrix, n_sources):
"""
Alternative gridless method: root-finding on dual polynomial
Find roots of polynomial P(z) = v(z)^H Q v(z) on unit circle
"""
# Use ESPRIT on T_matrix as approximation
eigenvalues, eigenvectors = eigh(T_matrix)
idx = np.argsort(eigenvalues)[::-1]
eigenvectors = eigenvectors[:, idx]
# Signal subspace
E_s = eigenvectors[:, :n_sources]
# Shift invariance
E1 = E_s[:-1, :]
E2 = E_s[1:, :]
Phi = np.linalg.lstsq(E1, E2, rcond=None)[0]
roots = eigvals(Phi)
# Extract angles from roots (should be on/near unit circle)
angles = np.arcsin(np.clip(np.angle(roots) / (2 * np.pi * self.d), -1, 1))
angles_deg = np.degrees(angles)
return angles_deg, np.abs(roots)
def visualize_gridless_estimation(self, Y, true_angles=None, n_sources=2):
"""
Comprehensive visualization of gridless estimation
"""
print("Solving atomic norm minimization...")
u_opt, T_opt, Q_dual = self.atomic_norm_minimization(Y)
# Dual polynomial
angles, dual_vals, peak_angles = self.dual_polynomial(Q_dual)
# Root-based estimation
root_angles, root_mags = self.root_music_like(T_opt, n_sources)
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. Dual polynomial (spectral localization)
ax1 = axes[0, 0]
ax1.plot(angles, dual_vals, linewidth=2, label='|Q(θ)|')
ax1.axhline(1.0, color='red', linestyle='--', alpha=0.5, label='Unit magnitude')
for peak in peak_angles:
ax1.axvline(peak, color='green', linestyle=':', alpha=0.7)
if true_angles is not None:
for ang in true_angles:
ax1.axvline(ang, color='blue', linestyle='--', alpha=0.5, label='True angle' if ang == true_angles[0] else "")
ax1.set_xlabel('Angle (degrees)')
ax1.set_ylabel('|Q(θ)|')
ax1.set_title('Dual Polynomial (Spectral Localization)')
ax1.legend()
ax1.grid(True, alpha=0.3)
ax1.set_ylim(0, max(dual_vals)*1.1)
# 2. Root locations (complex plane)
ax2 = axes[0, 1]
# Construct polynomial roots from Toeplitz structure
# Simplified: show eigenvalues of the shift operator
eigenvalues, _ = eigh(T_opt)
ax2.scatter(eigenvalues.real, eigenvalues.imag, c='blue', alpha=0.6)
circle = plt.Circle((0, 0), np.max(np.abs(eigenvalues)), fill=False, color='red', linestyle='--')
ax2.add_patch(circle)
ax2.set_aspect('equal')
ax2.set_title('Eigenvalue Distribution (Toeplitz)')
ax2.set_xlabel('Real')
ax2.set_ylabel('Imaginary')
ax2.grid(True, alpha=0.3)
# 3. Reconstructed covariance vs sample covariance
ax3 = axes[1, 0]
R_sample = Y @ Y.conj().T / Y.shape[1]
im = ax3.imshow(np.abs(T_opt), cmap='hot', aspect='auto')
ax3.set_title('Reconstructed Toeplitz Covariance')
plt.colorbar(im, ax=ax3)
ax4 = axes[1, 1]
im2 = ax4.imshow(np.abs(R_sample - T_opt), cmap='hot', aspect='auto')
ax4.set_title('Difference: Sample - Reconstructed')
plt.colorbar(im2, ax=ax4)
plt.suptitle('Gridless DOA Estimation via Atomic Norm Minimization', fontsize=14)
plt.tight_layout()
print(f"Detected peaks from dual polynomial: {peak_angles}")
print(f"Root-based angles: {root_angles}")
return fig, peak_angles
def demo_gridless_cs():
"""Demonstrate gridless compressive sensing"""
print("=" * 60)
print("Gridless Compressive Sensing for DOA Estimation")
print("=" * 60)
# Setup
N = 10 # More elements for better resolution
d = 0.5
# True sources (closely spaced to demonstrate super-resolution)
true_angles = [10, 15] # 5 degrees separation (less than Rayleigh limit)
K = len(true_angles)
# Generate data
T = 30
A_true = np.zeros((N, K), dtype=complex)
for k, ang in enumerate(true_angles):
theta = np.radians(ang)
A_true[:, k] = np.exp(1j * 2 * np.pi * d * np.arange(N) * np.sin(theta))
S = (np.random.randn(K, T) + 1j*np.random.randn(K, T)) / np.sqrt(2)
X = A_true @ S
noise = 0.05 * (np.random.randn(N, T) + 1j*np.random.randn(N, T))
Y = X + noise
print(f"Scenario: {N} elements, {K} sources at {true_angles}° (separation: {true_angles[1]-true_angles[0]}°)")
print(f"Rayleigh resolution: {np.degrees(1/N):.1f}°")
# Gridless estimation
gcs = GridlessCompressiveSensing(N, d)
fig, estimated_angles = gcs.visualize_gridless_estimation(Y, true_angles=true_angles, n_sources=K)
plt.savefig('gridless_cs_doa.png', dpi=150, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
demo_gridless_cs()
print("\nVisualization saved: gridless_cs_doa.png")
487



被折叠的 条评论
为什么被折叠?



