Last active
August 16, 2025 09:54
-
-
Save tam17aki/70a9f5ff19c77f0516af7893df5aee84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """A demonstration of Frequency Estimation Based on WLS-SCDE for a dumped sinusoid. | |
| Copyright (C) 2025 by Akira TAMAMORI | |
| Permission is hereby granted, free of charge, to any person obtaining a copy | |
| of this software and associated documentation files (the "Software"), to deal | |
| in the Software without restriction, including without limitation the rights | |
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| copies of the Software, and to permit persons to whom the Software is | |
| furnished to do so, subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| SOFTWARE. | |
| """ | |
| import numpy as np | |
| import numpy.typing as npt | |
| from scipy.signal.windows import get_window | |
| def calculate_observables( | |
| frame: npt.NDArray[np.float64], fs: float | |
| ) -> tuple[ | |
| npt.NDArray[np.complex128], | |
| npt.NDArray[np.complex128], | |
| npt.NDArray[np.complex128], | |
| npt.NDArray[np.float64], | |
| ]: | |
| """Calculates the observables (gw, hw, kw) from a signal frame. | |
| These are Fourier coefficients weighted by a window function and its derivatives. | |
| """ | |
| n_samples = len(frame) | |
| fft_size = 1 << (n_samples - 1).bit_length() | |
| # Use a window function whose value and derivatives are zero at the boundaries. | |
| # The Blackman-Harris window has excellent properties for this purpose. | |
| p_t = get_window("blackmanharris", n_samples) | |
| dt = 1.0 / fs | |
| dp_t = np.gradient(p_t, dt) | |
| d2p_t = np.gradient(dp_t, dt) | |
| # Calculate Fourier coefficients for the signal weighted by p(t), p'(t), and p''(t). | |
| gwk_full = np.fft.rfft(frame * p_t, n=fft_size) | |
| hwk_full = np.fft.rfft(frame * dp_t, n=fft_size) | |
| kwk_full = np.fft.rfft(frame * d2p_t, n=fft_size) | |
| freq_bins_hz = np.fft.rfftfreq(fft_size, 1 / fs).astype(np.float64) | |
| omega_k_full = 2 * np.pi * freq_bins_hz | |
| return gwk_full, hwk_full, kwk_full, omega_k_full | |
| def select_bins_for_damped_scde( | |
| gwk_full: npt.NDArray[np.complex128], | |
| omega_k_full: npt.NDArray[np.float64], | |
| fs: float, | |
| num_bins: int = 7, | |
| ) -> npt.NDArray[np.int64]: | |
| """Selects a set of frequency bins around the spectral peak.""" | |
| freq_bins_hz = omega_k_full / (2 * np.pi) | |
| mag_spec = np.abs(gwk_full) | |
| search_range = (freq_bins_hz > 50) & (freq_bins_hz < fs / 2 * 0.95) | |
| if not np.any(search_range): | |
| return np.array([], dtype=int) | |
| search_indices = np.where(search_range)[0] | |
| mag_spec_searched = mag_spec[search_indices] | |
| center_peak_local_idx = np.argmax(mag_spec_searched) | |
| half_bins = num_bins // 2 | |
| start_local_idx = np.maximum(0, center_peak_local_idx - half_bins) | |
| end_local_idx = start_local_idx + num_bins | |
| if end_local_idx > len(mag_spec_searched): | |
| end_local_idx = len(mag_spec_searched) | |
| start_local_idx = max(0, end_local_idx - num_bins) | |
| selected_local_indices = np.arange(start_local_idx, end_local_idx) | |
| return search_indices[selected_local_indices] | |
| def solve_complex_a_sq_wls( | |
| gwk: npt.NDArray[np.complex128], | |
| hwk: npt.NDArray[np.complex128], | |
| kwk: npt.NDArray[np.complex128], | |
| omega_k: npt.NDArray[np.float64], | |
| ) -> np.complex128 | None: | |
| """Solves for the complex squared frequency using Weighted Least Squares.""" | |
| if len(gwk) < 3: | |
| return None | |
| # Equation: (gwk) * ã² = (ωk^2 * gwk + 2jωk * hwk - kwk) | |
| coeff = gwk | |
| b = omega_k**2 * gwk + 2j * omega_k * hwk - kwk | |
| # Weight W is the power |gwk|^2 | |
| w = np.abs(gwk) ** 2 | |
| # Solve the weighted normal equation: (A^{H}WA)x = (A^{H}Wb) | |
| coeff_h = coeff.conj() | |
| lhs = np.sum(coeff_h * w * coeff) | |
| rhs = np.sum(coeff_h * w * b) | |
| if np.abs(lhs) < 1e-12: | |
| return None | |
| complex_freq: np.complex128 = rhs / lhs | |
| return complex_freq | |
| def separate_params_from_complex_a_sq( | |
| complex_a_sq: np.complex128, peak_omega: np.float64 | |
| ) -> tuple[np.float64, np.float64]: | |
| """Separates frequency (a) and damping (ε) from the complex a^2.""" | |
| real_part = complex_a_sq.real | |
| imag_part = complex_a_sq.imag | |
| # Im(ã^2) ≈ 2ωε | |
| if peak_omega < 1e-6: | |
| epsilon = np.float64(0.0) | |
| else: | |
| epsilon = imag_part / (2 * peak_omega) | |
| # Re(ã^2) ≈ a^2 + ε^2 | |
| a_sq = real_part - epsilon**2 | |
| if a_sq < 0: | |
| return np.float64(np.float64(np.nan)), np.float64(np.float64(np.nan)) | |
| a: np.float64 = np.sqrt(a_sq) | |
| return a, epsilon | |
| def estimate_damped_sinusoid( | |
| frame: npt.NDArray[np.float64], fs: float | |
| ) -> tuple[np.float64, np.float64]: | |
| """Estimates the frequency (fo) and damping factor (ε) of a single damped sinusoid. | |
| This function is a refactored version with separated responsibilities. | |
| Args: | |
| frame (np.ndarray): The input signal frame. | |
| fs (int): The sampling frequency in Hz. | |
| Returns: | |
| tuple[float, float]: The estimated (fo, ε) pair. | |
| Returns (np.float64(np.nan), np.float64(np.nan)) | |
| if estimation fails. | |
| """ | |
| if len(frame) < 50 or np.var(frame) < 1e-10: | |
| return np.float64(np.nan), np.float64(np.nan) | |
| # Step 1: Calculate the necessary observables (gw, hw, kw) from the signal. | |
| gwk_full, hwk_full, kwk_full, omega_k_full = calculate_observables(frame, fs) | |
| # Step 2: Select the most informative frequency bins around the spectral peak. | |
| selected_indices = select_bins_for_damped_scde( | |
| gwk_full, omega_k_full, fs, num_bins=7 | |
| ) | |
| if selected_indices.size < 3: | |
| return np.float64(np.nan), np.float64(np.nan) | |
| # Step 3: Solve for the complex squared frequency using WLS. | |
| complex_a_sq = solve_complex_a_sq_wls( | |
| gwk=gwk_full[selected_indices], | |
| hwk=hwk_full[selected_indices], | |
| kwk=kwk_full[selected_indices], | |
| omega_k=omega_k_full[selected_indices], | |
| ) | |
| if complex_a_sq is None: | |
| return np.float64(np.nan), np.float64(np.nan) | |
| # Step 4: Separate the physical parameters (a, ε) from the complex solution. | |
| index: np.int64 = selected_indices[np.argmax(np.abs(gwk_full[selected_indices]))] | |
| peak_omega = omega_k_full[index] | |
| a, epsilon = separate_params_from_complex_a_sq(complex_a_sq, peak_omega) | |
| if np.isnan(a): | |
| return np.float64(np.nan), np.float64(np.nan) | |
| # Convert angular frequency to Hz and perform final validation. | |
| f0_hz = a / (2 * np.pi) | |
| if not 50 < f0_hz < fs / 2: | |
| return np.float64(np.nan), np.float64(np.nan) | |
| return f0_hz, epsilon | |
| def main() -> None: | |
| """Perform demonstration.""" | |
| fs = 44100 | |
| duration = 0.1 | |
| f0_true = 440.0 | |
| epsilon_true = 10.0 # damped coeff. | |
| noise_level = 0.05 | |
| t = np.arange(int(fs * duration)) / fs | |
| test_signal = np.exp(-epsilon_true * t) * np.cos(2 * np.pi * f0_true * t) | |
| f0_est, epsilon_est = estimate_damped_sinusoid(test_signal, fs) | |
| print("--- Damped Sinusoid Estimation (original) ---") | |
| print(f"True values: f0 = {f0_true:.2f} Hz, epsilon = {epsilon_true:.2f}") | |
| print(f"Estimated values: f0 = {f0_est:.2f} Hz, epsilon = {epsilon_est:.2f}") | |
| print("") | |
| test_signal += np.random.randn(len(test_signal)) * noise_level # add small noise | |
| f0_est, epsilon_est = estimate_damped_sinusoid(test_signal, fs) | |
| print("--- Damped Sinusoid Estimation (noise) ---") | |
| print(f"True values: f0 = {f0_true:.2f} Hz, epsilon = {epsilon_true:.2f}") | |
| print(f"Estimated values: f0 = {f0_est:.2f} Hz, epsilon = {epsilon_est:.2f}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment