Certainly! Below is the PyTorch equivalent of the given MATLAB r_music function. This implementation closely follows the steps of the original function, utilizing PyTorch for tensor operations and NumPy for polynomial root finding, as PyTorch does not have a built-in function for finding polynomial roots.
python
import torch
import numpy as np
def r_music(R: torch.Tensor, K: int) -> torch.Tensor:
"""
PyTorch equivalent of the MATLAB r_music function.
This function performs the MUSIC (Multiple Signal Classification) algorithm
to estimate the frequencies or directions of arrival from the covariance matrix R.
Args:
R (torch.Tensor): Covariance matrix of size (M, M). Should be a Hermitian matrix.
K (int): Number of signal sources to estimate.
Returns:
torch.Tensor: Estimated frequencies as a tensor of size (K,).
"""
# Ensure R is a square matrix
M = R.shape[0]
assert R.shape[0] == R.shape[1], "Covariance matrix R must be square."
# Eigen-decomposition: Since R is Hermitian, use eigh for efficiency
eigval, eigvec = torch.linalg.eigh(R)
# Sort eigenvalues by descending magnitude and sort eigenvectors accordingly
eigval_abs = torch.abs(eigval)
sorted_indices = torch.argsort(eigval_abs, descending=True)
eigval_sorted = eigval[sorted_indices]
eigvec_sorted = eigvec[:, sorted_indices]
# Noise subspace: eigenvectors corresponding to the smallest M-K eigenvalues
Un = eigvec_sorted[:, K:M]
# Compute the projection matrix onto the noise subspace
G = Un @ Un.conj().transpose(-2, -1)
# Initialize the d vector for the polynomial coefficients
d = torch.zeros(2 * M - 1, dtype=G.dtype, device=G.device)
# Sum of the diagonals of G for offsets from -(M-1) to (M-1)
for p in range(-M + 1, M):
diag_sum = torch.diagonal(G, offset=p).sum()
d[p + M - 1] = diag_sum
# Flip the d vector to match the polynomial coefficient order (highest degree first)
d_flipped = torch.flip(d, dims=[0])
# Convert the flipped d vector to a NumPy array for root finding
d_flipped_np = d_flipped.detach().cpu().numpy()
# Remove leading zeros to avoid issues with np.roots
d_flipped_np = np.trim_zeros(d_flipped_np, 'f')
if len(d_flipped_np) == 0:
raise ValueError("The polynomial coefficients are all zeros. Cannot find roots.")
# Find the roots of the polynomial
roots = np.roots(d_flipped_np)
# Filter roots inside the unit circle
roots_inside = roots[np.abs(roots) < 1]
if len(roots_inside) < K:
raise ValueError(f"Not enough roots inside the unit circle. Expected {K}, got {len(roots_inside)}.")
# Sort the roots by descending magnitude
sorted_indices = np.argsort(-np.abs(roots_inside))
sorted_roots = roots_inside[sorted_indices]
# Select the first K roots
selected_roots = sorted_roots[:K]
# Compute the angles of the roots and normalize by 2*pi to get frequencies
frequencies = np.angle(selected_roots) / (2 * np.pi)
# Convert the frequencies back to a PyTorch tensor
f_tensor = torch.tensor(frequencies, dtype=R.dtype, device=R.device)
return f_tensor
Explanation of the Implementation
Eigen-Decomposition:
PyTorch: Uses torch.linalg.eigh which is optimized for Hermitian (symmetric if real) matrices.
Sorting: Eigenvalues are sorted in descending order based on their magnitudes. The corresponding eigenvectors are rearranged accordingly.
Noise Subspace:
The noise subspace Un consists of the eigenvectors associated with the smallest M-K eigenvalues.
Projection Matrix:
The projection matrix G is computed as Un * Un'.
Polynomial Coefficients (d):
The d vector is constructed by summing the diagonals of G for offsets ranging from -(M-1) to M-1.
This vector is then flipped to align with the polynomial coefficients' order required by np.roots, where the first element is the coefficient of the highest degree term.
Root Finding:
Since PyTorch does not have a built-in root-finding function for polynomials, the flipped d vector is converted to a NumPy array.
np.roots is used to find all roots of the polynomial.
Only roots inside the unit circle (|F| < 1) are considered, as per the original MATLAB function.
Roots are sorted based on their magnitudes, and the top K roots are selected.
Frequency Estimation:
The angles of the selected roots are calculated and normalized by 2π to obtain the frequency estimates.
The resulting frequencies are converted back to a PyTorch tensor for consistency.
Usage Example
python
# Example usage of the r_music function
# Define parameters
M = 8 # Size of the covariance matrix
K = 2 # Number of signal sources
# Create a random Hermitian covariance matrix for demonstration
torch.manual_seed(0)
A = torch.randn(M, K) + 1j * torch.randn(M, K)
R = A @ A.conj().transpose(-2, -1)
# Estimate frequencies using the MUSIC algorithm
frequencies = r_music(R, K)
print("Estimated Frequencies:", frequencies)
Notes
Error Handling: The function includes error checks to ensure that the covariance matrix R is square and that enough roots are found inside the unit circle.
Device Compatibility: The function preserves the device (CPU or GPU) and data type of the input tensor R in the output frequencies tensor.
Performance: While most operations are performed using PyTorch for efficiency, the root-finding step relies on NumPy, which may not be GPU-accelerated. For large-scale applications or real-time requirements, consider implementing a custom root-finding algorithm compatible with PyTorch's GPU tensors.
This implementation should provide a seamless replacement for the MATLAB r_music function within a PyTorch-based workflow.