阵列信号处理研究的又一个三十年:优化与结构利用的视角

阵列信号处理——学习笔记 第6章 波束旁瓣设计 更重要的是,该框架具有高度通用性,可将多种传统方法纳入统一体系,采用规则化的数值求解手段,设计精度显著提升。此外,迭代过程未对主瓣宽度施加显式约束,可能导致主瓣非预期展宽,且最终解的加权向量范数可能较大,影响波束形成器的稳健性。干扰强度越大,凹槽越深。特别地,可在指定方位形成特定宽度与深度的凹槽,用于抑制已知方位的强干扰,同时保持其他区域的低旁瓣特性。将真实流形向量视为属于某一不确定集合的未知量,采用最差情况优化准则:在保证对所有可能的主瓣流形响应不低于归一化要求的前提下,最小化最坏情况下的旁瓣电平。 阅读详情

目录

第一部分:原理详解

1. 引言与数学预备

2. 稀疏贝叶斯学习阵列流形估计

2.1 层次概率模型与稀疏先验

2.2 证据最大化与超参数更新

2.3 离网细化与网格自适应

3. 结构化协方差矩阵重构

3.1 原子范数与半正定刻画

3.2 Vandermonde分解与Toeplitz结构

3.3 对偶多项式与谱峰定位

4. 交替方向乘子法鲁棒波束成形

4.1 分布式优化与变量分裂

4.2 谱约束投影与不确定性集

4.3 自适应惩罚参数调整

5. 张量CP分解多参数估计

5.1 多维接收数据张量模型

5.2 交替最小二乘与高维扩展

5.3 流形约束投影与耦合矩阵

6. 深度展开网络自适应波束成形

6.1 算法展开与可学习参数

6.2 模型驱动与数据驱动融合

6.3 梯度流与约束保持层

7. 离网连续压缩感知

7.1 无网格原子范数最小化

7.2 半正定规划与对偶理论

7.3 多项式求根与连续参数恢复

算法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)

python实现

第二部分:代码实现

脚本1: 稀疏贝叶斯学习阵列流形估计与DOA估计

脚本2: 结构化协方差矩阵原子范数重构

脚本3: ADMM鲁棒波束成形与分布式优化

脚本4: 张量CP分解多参数联合估计

脚本5: 深度展开网络自适应波束成形

脚本6: 离网连续压缩感知无网格DOA估计


第一部分:原理详解

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")
麦克风阵列信号处理实战:波束形成与声源定位算法解析 在语音交互和智能设备普及的今天,如何从复杂声学环境中提取目标语音成为核心挑战。麦克风阵列通过多个麦克风的空间分布捕捉声波相位差,实现空间维度的信号处理。其中,波束形成技术可以增强目标方向声音、抑制干扰,而声源定位则确定声音来源方向。延迟求和、MVDR和GSC等波束形成算法各有适用场景,SRP-PHAT等方法在混响环境下表现稳健。这些技术广泛应用于智能音箱、视频会议、车载语音等场景,能够显著提升语音识别和通信质量。本文从工程视角出发,结合8麦克风环形阵列的Python仿真代码,解析核心算法原理与实现细节,并分 阅读详情

相关推荐

Capon、MUSIC、Beamforming傻傻分不清?一张图讲透阵列信号处理中的空间谱估计

本文深入解析了阵列信号处理中Capon、MUSIC和波束形成三大核心算法的原理与应用。通过对比分析DOA估计技术的性能差异,帮助工程师理解空间谱估计的本质,并提供了技术选型的实用指南,适用于雷达、声纳和无线通信等领域。

weixin_30546189的博客 487

阵列信号处理的优化算法与结构创新

阵列信号处理是现代信号处理的核心技术,通过多个传感器协同工作实现空间信号采集与分析。其基本原理是利用波束形成和空间谱估计等技术,在雷达、通信和声学等领域实现目标检测与参数估计。随着5G和物联网发展,优化算法成为解决大规模阵列实时处理挑战的关键,其中凸优化和深度学习显著提升了系统性能。在工程实践中,稀疏阵列和可重构结构通过数学本质挖掘和硬件创新,大幅扩展了阵列处理能力。这些技术进步正推动着智能驾驶环境感知和6G太赫兹通信等前沿应用的发展,同时也面临着模型失配和实时性优化等工程挑战。

weixin_29191081的博客 14

dTOF激光雷达SPAD阵列部署:从TCSPC原理到192线雷达的3步信号处理

本文深入解析dTOF激光雷达SPAD阵列从光子计数到192线点云生成的完整信号处理链路,重点探讨SPAD(单光子雪崩二极管)阵列的单光子灵敏度、TCSPC原理及IMX459等典型阵列的像素合并策略。通过详细的技术实现视角,为算法工程师提供系统级部署方案,助力自动驾驶和机器人感知的环境建模精度提升。

weixin_28717939的博客 310

探索信号处理的卓越之作:《最优阵列处理技术》中文版

探索信号处理的卓越之作:《最优阵列处理技术》中文版 【下载地址】最优阵列处理技术中文版 《最优阵列处理技术》中文版是信号处理领域的经典著作,由Harry L. Van Trees撰写,详细阐述了最优阵列处理的理论与方法。本书内容涵盖阵列信号处理的基本原理、算法及其在雷达、声纳等领域的实际应用,结构清晰,深入浅出。无论是科...

gitblog_06746的博客 328

微软音频研究档案:从信号处理到AI的演进与工程启示

音频信号处理是计算机科学中连接物理世界与数字世界的关键领域,其核心原理在于通过数学变换与算法对声音信号进行采集、分析、增强与重建。从经典的自适应滤波、谱减法,到基于心理声学的感知编码,再到数据驱动的深度学习模型,技术的迭代始终围绕着提升音质、降低延迟与增强鲁棒性等核心工程目标。这些技术为实时通信、多媒体娱乐、智能语音交互等广泛场景提供了基础支撑。本文通过剖析微软内部长期积累的音频研究档案,揭示了包括**波束形成**、**回声消除**等关键技术从实验室原型到产品集成的完整演进路径,展现了技术决策背后的真实权衡

weixin_30715523的博客 546

通信原理视角下的MIMO系统信道容量提升策略研究

在平坦衰落信道下,MIMO系统的信道容量可表示为:C = \log_2 \det (I + \frac{\rho}{n_t} H H^H),其中C为信道容量,\rho为信噪比,n_t为发射天线数,H为信道矩阵,H^H为H的共轭转置。设置不同的仿真场景,包括不同的天线配置、信道条件和信号处理算法,对比分析各策略下MIMO系统的信道容量和误码率性能。1. 智能天线技术:采用智能天线技术,如自适应阵列天线,根据信道状态和用户位置动态调整天线方向图,增强有用信号强度,抑制干扰信号,提高信噪比,从而提升信道容量。

xiayan827的博客 691

阵列信号处理核心原理与工程实践:从波束形成到DOA估计

阵列信号处理是现代无线通信、雷达探测和智能感知领域的基础技术,其核心在于利用多个传感器构成阵列,通过空间采样获取信号的波达方向信息。其基本原理涉及空间维度扩展、阵列流形建模以及协方差矩阵分析。该技术的核心价值在于能够实现空间滤波,在强干扰背景下提取微弱信号,并突破传统分辨率限制。在工程实践中,波束形成与波达方向估计是两大核心任务,其中自适应波束形成算法能够动态抑制干扰,而子空间类算法可实现超分辨率测向。这些技术广泛应用于雷达目标跟踪、5G大规模MIMO通信、智能语音交互及医学成像等场景。本文深入探讨了阵列设

weixin_34347651的博客 419

天线罩对阵列性能的影响实测:基于FEKO的91单元偶极子阵列仿真分析

本文通过FEKO软件对91单元偶极子阵列进行仿真,实测分析了天线罩对阵列性能的关键影响。研究发现,单层介质天线罩会导致主瓣增益下降近2dB,副瓣电平抬升超过1.6dB,显著影响雷达或通信系统性能。文章深入剖析了其背后的电磁机理,并分享了使用MLFMM算法及SPAI预条件器进行高效精准仿真的参数调优实战经验,为天线罩的协同优化设计提供重要参考。

weixin_29092579的博客 481

最优阵列处理技术第2部分:阵列处理技术的优化之光

最优阵列处理技术第2部分:阵列处理技术的优化之光 项目介绍 在现代信号处理领域,阵列处理技术始终占据着举足轻重的地位。今天,我们要介绍的开源项目《最优阵列处理技术第2部分》正是汤俊先生的学术力作,为阵列处理技术的优化带来了全新的视角和解决方案。本书聚焦于阵列处理的后五章内容,通过深入剖析和详细解读,为相关领域的研究者和工程技术人员提供了宝贵的参考资源。 项目技术分析 《最优阵列处理技术第2部分》的...

gitblog_06776的博客 321

从理论到实践:深入浅出解析麦克风阵列声源定位背后的信号处理(STFT、波束形成与Python实现)

本文深入解析麦克风阵列声源定位的信号处理技术,涵盖STFT时频分析、波束形成算法及Python实现。通过Acoular库实战演示,展示从理论到工业级应用的完整流程,特别针对二维和三维声源定位场景提供优化方案,助力开发者突破调库阶段,掌握核心算法原理。

weixin_33694620的博客 567

【信息科学与工程学】信息科学工程领域 第三篇 信号与系统~04 阵列信号与AR/VR信号处理

相关函数数学定义物理意义适用场景自相关函数​信号自身在不同时刻的相似性信号周期检测、特征提取互相关函数​两信号在不同时延下的相似性时延估计、信号对齐循环相关​针对循环平稳信号通信信号处理高阶相关​捕捉非高斯、非线性特征非线性系统、高阶统计量分析AR/VR语音信号处理与生成是一个快速发展的跨学科领域,涉及信号处理、机器学习、声学、心理学、人机交互等多个方面。全面理解:深入理解用户需求、技术可能性和限制平衡取舍:在音质、延迟、计算资源、功耗、成本间取得平衡迭代优化。

weixin_49199313的博客 849

麦克风阵列信号处理——目录

《麦克风阵列信号处理》目录

weixin_44218363的博客 327

阵列信号处理实战:从数学模型到可复现Matlab代码

阵列信号处理是雷达、声呐与5G通信系统的核心基础,其本质在于将物理约束(如阵元几何、互耦效应、校准误差)精准建模为数学优化问题。理解导向矢量、协方差矩阵特征结构与鲁棒约束设计,是实现高精度DOA估计和稳定波束形成的关键原理。技术价值体现在将抽象公式转化为可验证、可调试、可复现的数值实现,显著提升算法在有限快拍、非理想硬件条件下的工程鲁棒性。典型应用场景包括相控阵雷达角度分辨、水下声呐目标定位及大规模MIMO波束管理。本文聚焦Matlab代码实现路径,深度融合阵列信号处理与优化建模两大热词,提供从理论推导到实

weixin_33404102的博客 327

从DSP视角看Cleer Arc5音频信号处理流程

本文深入解析Cleer Arc5耳机中数字信号处理器(DSP)的核心作用,涵盖主动降噪、空间音频、低频补偿与自适应算法的技术实现,揭示其如何通过实时信号处理打造沉浸式听觉体验。

weixin_42497762的博客 364

共形阵列天线多波束赋形关键技术深度研究

共形阵列与多波束赋形技术,正在悄然改变我们看待天线的方式。它不再是一个孤立的部件,而是集成了感知、决策、执行于一体的智能电磁系统。🧠📡从球面共形阵的方向图建模,到MMSE算法的动态调节,再到FPGA驱动的硬件闭环,这条技术路径不仅适用于军用雷达,也为6G太赫兹通信、空天地一体化网络提供了坚实基础。未来的天线,不再是被动的“喇叭”,而是主动的“眼睛”和“耳朵”。而这,才刚刚开始。🔥本文还有配套的精品资源,点击获取。

weixin_29859471的博客 1092

基于凸优化的线性阵列波束综合MATLAB实战项目

该错误占 CVX 调试时间的 68%,但 92% 的案例可通过系统化排查解决。以下是按发生概率降序排列的五层诊断路径:层级根因类别典型表现检测命令/方法修复方案L1角度定义域冲突主瓣中心 θ_c 与零点 θ₀ 距离 < HPBW/2,物理不可实现调整零点位置或放宽 HPBWL2约束过强(SLL + 零点 + 增益)与同时存在,t 过大导致无解cvx_status返回 ‘Infeasible’;检查。

weixin_36299472的博客 291

信号处理方法概述

语音信号处理流程示例 本示例展示语音信号从生成到识别的完整处理流程,包含以下关键步骤: 信号生成:模拟500Hz和1500Hz双音调语音,添加高斯噪声 时频分析:通过FFT和STFT观察信号频谱特征 滤波去噪:设计带通滤波器(300-2000Hz)消除噪声 特征提取:计算MFCC系数作为语音特征 模式识别:使用简单分类器进行音调识别 # 核心代码片段 import numpy as np import librosa # 1. 信号生成 t = np.linspace(0, 1, 16000) signal

金石软件 1223

优化阵列信号处理:凸优化与原子范数实战

阵列信号处理是雷达、通信和声呐等领域的关键技术,其核心是将物理阵列的接收数据转化为数学模型,进而通过优化求解波达方向、波束权值等参数。在众多数学工具中,凸优化因其全局收敛性和高效求解算法成为主流选择。通过将MVDR波束形成、DOA估计等经典问题建模为二次规划或半定规划,不仅可获得闭式解,还能灵活加入正则化约束以提升稳健性。针对传统网格方法在角度失配时的性能下降,原子范数最小化利用Toeplitz结构实现连续参数估计,进一步突破了分辨率瓶颈。本文基于CVXPY工具,系统演示从协方差拟合SDP到原子范数松弛的完

weixin_42519781的博客 62
上一篇: 自适应波束成形方法提升海洋和风电场杂波中被动雷达性能
下一篇: 稀疏阵列深度学习优化波束成形技术手册
VectorShift
博客等级 码龄1年 1896粉丝 1127原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VectorShift

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址