Transforms

This section covers various signal transformation techniques provided by the VitalDSP library. These transformations are crucial for analyzing signals in different domains, such as time-frequency analysis and feature extraction.

Chroma STFT

Short-time Fourier transform (STFT) applied to chroma features, which is useful for analyzing pitch content in signals like audio.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations - SciPy integration for advanced signal processing

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.chroma_stft import ChromaStft
>>> signal = np.random.randn(1000)
>>> processor = ChromaStft(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.chroma_stft.ChromaSTFT(signal, sample_rate=16000, n_chroma=12, n_fft=2048, hop_length=512)[source]

Bases: object

A class to compute the Chroma Short-Time Fourier Transform (Chroma STFT) to analyze harmonic content in audio signals.

The Chroma STFT is useful for identifying the harmonic structure of a signal by projecting its frequency content onto a small number of pitch classes (chroma bins).

signal

The input audio signal.

Type:

numpy.ndarray

sample_rate

The sample rate of the signal.

Type:

int

n_chroma

The number of chroma bins (usually 12 for the 12 pitch classes).

Type:

int

n_fft

The FFT size, determining the frequency resolution of the STFT.

Type:

int

hop_length

The number of samples between successive frames.

Type:

int

compute_chroma_stft()[source]

Computes the Chroma STFT of the signal.

Example Usage
-------------
>>> signal = np.sin(2 * np.pi * 440 * np.linspace(0, 2, 16000))  # 2 seconds of A4 note (440Hz)
>>> chroma_stft = ChromaSTFT(signal, sample_rate=16000, n_chroma=12, n_fft=2048, hop_length=512)
>>> chroma_stft_result = chroma_stft.compute_chroma_stft()
>>> print(chroma_stft_result.shape)  # Output: (12, num_frames)
compute_chroma_stft()[source]

Compute the Chroma Short-Time Fourier Transform (Chroma STFT) of the signal.

This function applies the STFT to the signal and then projects the result onto chroma bins.

Returns:

chroma_stft – The Chroma STFT of the signal. Each row represents a chroma bin, and each column represents a time frame.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(2 * np.pi * 440 * np.linspace(0, 2, 16000))  # 2 seconds of A4 note (440Hz)
>>> chroma_stft = ChromaSTFT(signal, sample_rate=16000, n_chroma=12, n_fft=2048, hop_length=512)
>>> chroma_stft_result = chroma_stft.compute_chroma_stft()
>>> print(chroma_stft_result.shape)  # Output: (12, num_frames)

DCT Wavelet Fusion

Combining Discrete Cosine Transform (DCT) with wavelet transforms to extract meaningful features from signals, particularly in multi-resolution analysis.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.dct_wavelet_fusion import DctWaveletFusion
>>> signal = np.random.randn(1000)
>>> processor = DctWaveletFusion(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.dct_wavelet_fusion.DCTWaveletFusion(signal, wavelet_type='db', order=4, **kwargs)[source]

Bases: object

A class to perform fusion of Discrete Cosine Transform (DCT) and Wavelet Transform on a signal.

This class allows for the combination of DCT, which is effective for frequency-domain analysis, and Wavelet Transform, which excels at capturing both frequency and location information. The fusion of these two transforms can be particularly useful in signal processing tasks such as denoising, feature extraction, and data compression.

compute_fusion : method

Computes the fusion of DCT and Wavelet Transform for the given signal.

compute_fusion()[source]

Compute the fusion of Discrete Cosine Transform (DCT) and Wavelet Transform for the signal.

The fusion process involves computing the DCT of the signal, followed by a Wavelet Transform. The resulting coefficients from both transforms are then combined multiplicatively to achieve a fusion that incorporates features from both the frequency and time-frequency domains.

Returns:

The fused signal, combining DCT and Wavelet Transform coefficients.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 1000))
>>> fusion = DCTWaveletFusion(signal)
>>> fusion_result = fusion.compute_fusion()
>>> print(fusion_result)

Discrete Cosine Transform

The Discrete Cosine Transform (DCT) is used to convert signals into a sum of cosine functions at different frequencies. This is particularly useful in signal compression and feature extraction.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations - SciPy integration for advanced signal processing - Signal transformation methods

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.discrete_cosine_transform import DiscreteCosineTransform
>>> signal = np.random.randn(1000)
>>> processor = DiscreteCosineTransform(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.discrete_cosine_transform.DiscreteCosineTransform(signal)[source]

Bases: object

A class to perform Discrete Cosine Transform (DCT) and its inverse (IDCT).

The DCT is widely used in signal processing, particularly for data compression (such as JPEG image compression) and feature extraction. It transforms a signal from the time domain into the frequency domain, where most of the signal information is compacted into a few coefficients. The inverse DCT (IDCT) reconstructs the signal from its DCT coefficients.

compute_dct : method

Computes the DCT of the signal.

compute_idct : method

Computes the Inverse DCT to reconstruct the signal.

compress_signal(threshold=0.1)[source]

Compress the signal by zeroing out small DCT coefficients.

This method removes high-frequency components that are below the threshold, which often represent noise, improving the signal’s reconstruction quality and reducing its size.

Parameters:

threshold (float, optional) – The threshold below which DCT coefficients are set to zero. Default is 0.1.

Returns:

The compressed DCT coefficients.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> dct = DiscreteCosineTransform(signal)
>>> compressed_coefficients = dct.compress_signal(threshold=0.05)
>>> print(compressed_coefficients)
compute_dct(norm='ortho')[source]

Compute the Discrete Cosine Transform (DCT) of the signal.

The DCT converts the input signal from the time domain to the frequency domain, emphasizing the low-frequency components of the signal. It is particularly effective for compressing signals because it tends to concentrate most of the signal’s energy into a few low-frequency components.

Parameters:

norm (str, optional) – Normalization type. Default is ‘ortho’ for orthogonal DCT, which is usually recommended.

Returns:

The DCT coefficients of the signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> dct = DiscreteCosineTransform(signal)
>>> dct_coefficients = dct.compute_dct()
>>> print(dct_coefficients)
compute_idct(dct_coefficients, norm='ortho')[source]

Compute the Inverse Discrete Cosine Transform (IDCT) to reconstruct the signal.

The IDCT converts the DCT coefficients back into the time domain, reconstructing the original signal. This process is essential in applications like image compression, where the signal is compressed using DCT and then decompressed back to its original form using IDCT.

Parameters:
  • dct_coefficients (numpy.ndarray) – The DCT coefficients of the signal.

  • norm (str, optional) – Normalization type. Default is ‘ortho’ for orthogonal DCT.

Returns:

The time-domain signal reconstructed from its DCT coefficients.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> dct = DiscreteCosineTransform(signal)
>>> dct_coefficients = dct.compute_dct()
>>> reconstructed_signal = dct.compute_idct(dct_coefficients)
>>> print(reconstructed_signal)

Fourier Transform

The Fourier Transform decomposes signals into their constituent frequencies, making it a powerful tool for frequency-domain analysis.

Fourier Transform Module for Physiological Signal Processing

This module provides comprehensive Fourier Transform capabilities for analyzing the frequency content of physiological signals such as ECG, EEG, and PPG. It implements both Discrete Fourier Transform (DFT) and Inverse Discrete Fourier Transform (IDFT) with signal validation and error handling.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Discrete Fourier Transform (DFT) computation - Inverse Discrete Fourier Transform (IDFT) reconstruction - Signal validation and error handling - Frequency domain analysis capabilities - Signal reconstruction from frequency components

Examples:

Basic frequency analysis:
>>> import numpy as np
>>> from vitalDSP.transforms.fourier_transform import FourierTransform
>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ft = FourierTransform(signal)
>>> frequency_spectrum = ft.compute_dft()
>>> print(f"Spectrum shape: {frequency_spectrum.shape}")
Signal reconstruction:
>>> reconstructed_signal = ft.compute_idft(frequency_spectrum)
>>> print(f"Reconstruction error: {np.mean((signal - reconstructed_signal)**2):.6f}")
Frequency domain filtering:
>>> # Zero out high frequencies
>>> filtered_spectrum = frequency_spectrum.copy()
>>> filtered_spectrum[20:] = 0
>>> filtered_signal = ft.compute_idft(filtered_spectrum)
class vitalDSP.transforms.fourier_transform.FourierTransform(signal)[source]

Bases: object

A class to perform Fourier Transform for analyzing the frequency content in signals such as ECG/EEG.

The Fourier Transform is a mathematical technique that transforms a time-domain signal into its constituent frequencies, providing insights into the signal’s frequency content. This class allows for both the computation of the Discrete Fourier Transform (DFT) and the Inverse Discrete Fourier Transform (IDFT), making it possible to analyze and reconstruct signals.

compute_dft : method

Computes the Discrete Fourier Transform (DFT) of the signal.

compute_idft : method

Computes the Inverse Discrete Fourier Transform (IDFT) to reconstruct the signal.

compute_dft()[source]

Compute the Discrete Fourier Transform (DFT) of the input signal.

The DFT converts the time-domain signal into the frequency domain, allowing for the analysis of its frequency components. This is particularly useful in identifying periodicities, filtering, and spectral analysis of biomedical signals like ECG and EEG.

Returns:

The frequency domain representation of the signal, where each element corresponds to a specific frequency component.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ft = FourierTransform(signal)
>>> frequency_content = ft.compute_dft()
>>> print(frequency_content)
compute_idft(frequency_content)[source]

Compute the Inverse Discrete Fourier Transform (IDFT) to reconstruct the time-domain signal.

The IDFT converts the frequency-domain data back into the time domain, reconstructing the original signal from its frequency components. This is useful for understanding how different frequency components contribute to the overall signal and for signal reconstruction after processing in the frequency domain.

Parameters:

frequency_content (numpy.ndarray) – The frequency domain representation of the signal, as obtained from the DFT.

Returns:

The time-domain signal reconstructed from its frequency components.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ft = FourierTransform(signal)
>>> frequency_content = ft.compute_dft()
>>> reconstructed_signal = ft.compute_idft(frequency_content)
>>> print(reconstructed_signal)
filter_frequencies(low_cutoff=None, high_cutoff=None, fs=1.0)[source]

Apply a bandpass filter in the frequency domain.

Parameters:
  • low_cutoff (float, optional) – The low cutoff frequency. Frequencies below this will be zeroed out.

  • high_cutoff (float, optional) – The high cutoff frequency. Frequencies above this will be zeroed out.

  • fs (float, optional) – The sampling frequency of the signal. Default is 1.0.

Returns:

The filtered signal in the time domain.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ft = FourierTransform(signal)
>>> filtered_signal = ft.filter_frequencies(low_cutoff=0.5, high_cutoff=2.0, fs=10)
>>> print(filtered_signal)

Hilbert Transform

The Hilbert Transform is used to derive the analytical signal, useful for envelope detection and instantaneous frequency analysis.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations - Signal transformation methods

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.hilbert_transform import HilbertTransform
>>> signal = np.random.randn(1000)
>>> processor = HilbertTransform(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.hilbert_transform.HilbertTransform(signal)[source]

Bases: object

A class to perform the Hilbert Transform, which is used to generate analytic signals.

The Hilbert Transform is a key tool in signal processing, particularly for generating the analytic signal from a real-valued signal. The analytic signal is complex, with the original signal as the real part and the Hilbert transform as the imaginary part. This is particularly useful in applications like QRS detection in ECG signals, where phase and amplitude information are crucial.

compute_hilbert : method

Computes the Hilbert Transform of the signal to obtain the analytic signal.

compute_hilbert()[source]

Compute the Hilbert Transform to obtain the analytic signal.

The Hilbert Transform is applied in the frequency domain by first taking the Fourier transform of the input signal, modifying the Fourier coefficients to zero out the negative frequencies, and then applying the inverse Fourier transform. This process effectively shifts the signal in such a way that the imaginary part represents the phase information, while the real part remains the original signal.

Returns:

The analytic signal with both real and imaginary components, where the real part is the original signal and the imaginary part is the Hilbert transform.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ht = HilbertTransform(signal)
>>> analytic_signal = ht.compute_hilbert()
>>> print(analytic_signal)

Notes

The analytic signal is often used in applications where the instantaneous amplitude and phase of the signal are required, such as in the detection of QRS complexes in ECG signals, modulation, and demodulation in communications, and envelope detection in various signal processing tasks.

envelope()[source]

Compute the envelope of the signal using the Hilbert Transform.

The envelope is the magnitude of the analytic signal and represents the instantaneous amplitude of the signal. This is particularly useful in applications such as PPG signal analysis, where the envelope can be used to assess pulse amplitude variations.

Returns:

The envelope of the input signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ht = HilbertTransform(signal)
>>> envelope = ht.envelope()
>>> print(envelope)
instantaneous_phase()[source]

Compute the instantaneous phase of the signal using the Hilbert Transform.

The instantaneous phase is the phase angle of the analytic signal and is useful in applications such as ECG analysis, where phase information can help in detecting the QRS complex or other waveform characteristics.

Returns:

The instantaneous phase of the input signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> ht = HilbertTransform(signal)
>>> phase = ht.instantaneous_phase()
>>> print(phase)

MFCC (Mel Frequency Cepstral Coefficients)

MFCC is widely used in audio signal processing for feature extraction, particularly in speech recognition systems.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.mfcc import Mfcc
>>> signal = np.random.randn(1000)
>>> processor = Mfcc(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.mfcc.MFCC(signal, sample_rate=16000, num_filters=40, num_coefficients=13)[source]

Bases: object

A class to compute Mel-Frequency Cepstral Coefficients (MFCC) for audio signals.

MFCCs are widely used in audio processing tasks, particularly in speech recognition. This class provides methods to preprocess an audio signal and compute its MFCCs, which represent the short-term power spectrum of a sound.

dct : method

Computes the Discrete Cosine Transform (DCT) of the filter bank energies.

compute_mfcc : method

Computes the MFCCs of the input signal.

compute_mfcc()[source]

Compute the Mel-Frequency Cepstral Coefficients (MFCC) of the input signal.

This method processes the input audio signal by applying pre-emphasis, framing, windowing, FFT, and filter banks, followed by the DCT to extract the MFCCs.

Returns:

  • numpy.ndarray – A 2D array where each row contains the MFCCs for a frame of the signal.

  • Steps

  • —–

  • 1. Pre-emphasis (Emphasizes higher frequencies in the signal.)

  • 2. Framing (Divides the signal into overlapping frames.)

  • 3. Windowing (Applies a Hamming window to each frame to reduce spectral leakage.)

  • 4. FFT and Power Spectrum (Converts each frame to the frequency domain and computes the power spectrum.)

  • 5. Mel Filter Banks (Applies a set of filters to the power spectrum to obtain Mel frequency bands.)

  • 6. DCT (Computes the DCT of the log filter bank energies to obtain the MFCCs.)

Examples

>>> signal = np.sin(np.linspace(0, 10, 1000))
>>> mfcc = MFCC(signal)
>>> mfcc_result = mfcc.compute_mfcc()
>>> print(mfcc_result)
dct(signal)[source]

Compute the Discrete Cosine Transform (DCT) of the input signal.

The DCT is applied to the filter bank energies to reduce the dimensionality and decorrelate the filter bank coefficients, producing the MFCCs.

Parameters:

signal (numpy.ndarray) – The input signal or filter banks matrix from which DCT is computed.

Returns:

The DCT coefficients representing the MFCCs.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([[1, 2, 3], [4, 5, 6]])
>>> mfcc = MFCC(signal)
>>> dct_result = mfcc.dct(signal)
>>> print(dct_result)

PCA and ICA Signal Decomposition

Principal Component Analysis (PCA) and Independent Component Analysis (ICA) are used for signal decomposition, particularly in separating mixed signals into independent sources.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.pca_ica_signal_decomposition import PcaIcaSignalDecomposition
>>> signal = np.random.randn(1000)
>>> processor = PcaIcaSignalDecomposition(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.pca_ica_signal_decomposition.ICASignalDecomposition(signals, max_iter=1000, tolerance=1e-06)[source]

Bases: object

A class to perform Independent Component Analysis (ICA) for signal decomposition.

ICA is a computational technique for separating a multivariate signal into additive, independent components. It is commonly used in fields like biomedical signal processing (e.g., EEG data) to isolate underlying sources.

compute_ica : method

Computes ICA on the signals and returns the independent components.

compute_ica()[source]

Compute Independent Component Analysis (ICA) on the signals.

This method performs the following steps: 1. Centers and whitens the data to prepare it for ICA. 2. Initializes random weights and iteratively updates them using the FastICA algorithm. 3. Checks for convergence based on the specified tolerance. 4. Returns the independent components of the signals.

Returns:

The independent components of the signals, where each column represents an independent component.

Return type:

numpy.ndarray

Examples

>>> signals = np.random.rand(5, 100)
>>> ica = ICASignalDecomposition(signals)
>>> ica_result = ica.compute_ica()
>>> print(ica_result)
class vitalDSP.transforms.pca_ica_signal_decomposition.PCASignalDecomposition(signals, n_components=None)[source]

Bases: object

A class to perform Principal Component Analysis (PCA) for signal decomposition.

PCA is a dimensionality reduction technique that transforms the original signals into a set of linearly uncorrelated components, known as principal components. These components capture the maximum variance in the data and are ordered by the amount of variance they explain.

compute_pca : method

Computes PCA on the signals and returns the principal components.

compute_pca()[source]

Compute Principal Component Analysis (PCA) on the signals.

This method performs the following steps: 1. Centers the data by subtracting the mean signal from each signal. 2. Computes the covariance matrix of the centered signals. 3. Computes the eigenvalues and eigenvectors of the covariance matrix. 4. Sorts the eigenvectors by their corresponding eigenvalues in descending order. 5. Selects the top n_components eigenvectors to form the principal components.

Returns:

The principal components of the signals, where each column represents a principal component.

Return type:

numpy.ndarray

Examples

>>> signals = np.random.rand(5, 100)
>>> pca = PCASignalDecomposition(signals, n_components=2)
>>> pca_result = pca.compute_pca()
>>> print(pca_result)

STFT (Short-Time Fourier Transform)

The Short-Time Fourier Transform is used for analyzing signals whose frequency content changes over time, providing a time-frequency representation of the signal.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations - Performance optimization

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.stft import Stft
>>> signal = np.random.randn(1000)
>>> processor = Stft(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.stft.STFT(signal, window_size=256, hop_size=128, n_fft=512)[source]

Bases: object

A class to perform Short-Time Fourier Transform (STFT) for analyzing time-varying signals.

The STFT is used to understand how the frequency content of a signal evolves over time by dividing the signal into overlapping segments, applying a Fourier Transform to each segment, and assembling the results into a time-frequency representation.

compute_stft : method

Computes the STFT of the signal.

compute_stft()[source]

OPTIMIZED: Compute the Short-Time Fourier Transform (STFT) of the signal using vectorized operations.

The STFT splits the signal into overlapping windows, applies a Hanning window function to reduce spectral leakage, and computes the FFT for each windowed segment. The result is a matrix representing the magnitude and phase of the signal’s frequency components over time.

Returns:

stft_matrix – A 2D complex-valued array where rows correspond to frequency bins and columns correspond to time frames.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(2 * np.pi * 5 * np.linspace(0, 1, 500)) + np.sin(2 * np.pi * 20 * np.linspace(0, 1, 500))
>>> stft = STFT(signal, window_size=100, hop_size=50, n_fft=128)
>>> stft_result = stft.compute_stft()
>>> print(stft_result.shape)
(65, 9)

Time-Frequency Representation

This module covers various methods for representing signals in both time and frequency domains simultaneously.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.time_freq_representation import TimeFreqRepresentation
>>> signal = np.random.randn(1000)
>>> processor = TimeFreqRepresentation(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.time_freq_representation.TimeFreqRepresentation(signal, method='stft', **kwargs)[source]

Bases: object

A class to generate Time-Frequency Representations (TFR) of signals for machine learning and signal analysis.

This class supports multiple methods for computing the TFR, including Short-Time Fourier Transform (STFT) and Wavelet Transform. These representations are useful in analyzing the frequency content of signals as it changes over time, which is particularly valuable in tasks like speech processing, biomedical signal analysis, and other time-series data applications.

compute_tfr : method

Computes the time-frequency representation of the signal using the specified method.

compute_tfr()[source]

Compute the Time-Frequency Representation (TFR) of the signal.

Depending on the chosen method, this function computes either the Short-Time Fourier Transform (STFT) or the Wavelet Transform to represent the signal in both time and frequency domains.

Returns:

The time-frequency representation of the signal. The output format depends on the method: - For STFT: A 2D array where rows correspond to time segments and columns to frequency bins. - For Wavelet Transform: A 2D array where rows correspond to time segments and columns to scales or frequencies.

Return type:

numpy.ndarray

Raises:

ValueError – If an unsupported method is specified.

Examples

>>> signal = np.sin(np.linspace(0, 10, 1000))
>>> tfr = TimeFreqRepresentation(signal, method='wavelet', wavelet_name='db', level=4)
>>> tfr_result = tfr.compute_tfr()
>>> print(tfr_result)

Vital Transformation

This module covers perform comprehensive signal processing on ECG and PPG signals using advanced filtering and artifact removal techniques.

A series of transformations aimed at enhancing the quality of ECG and PPG signals by eliminating noise, detrending, normalizing, and enhancing critical points for easier detection. Each transformation step is modular and customizable.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations - SciPy integration for advanced signal processing - Performance optimization

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.vital_transformation import VitalTransformation
>>> signal = np.random.randn(1000)
>>> processor = VitalTransformation(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.vital_transformation.VitalTransformation(signal, fs=256, signal_type='ECG')[source]

Bases: object

A class to perform comprehensive signal processing on ECG and PPG signals using advanced filtering and artifact removal techniques.

This class provides a series of transformations aimed at enhancing the quality of ECG and PPG signals by eliminating noise, detrending, normalizing, and enhancing critical points for easier detection. Each transformation step is modular and customizable.

Parameters:
  • signal (numpy.ndarray) – The input ECG or PPG signal to be transformed.

  • fs (int, optional) – Sampling frequency of the signal. Default is 256 Hz.

  • signal_type (str, optional) – Type of signal. Options: ‘ECG’, ‘PPG’, ‘EEG’. Default is ‘ECG’.

apply_transformations(options=None, method_order=None)[source]

Apply a sequence of transformations to process the signal, with options for customization.

apply_artifact_removal(method='baseline_correction', options=None)[source]

Apply artifact removal using various techniques such as mean subtraction, baseline correction, or wavelet denoising.

apply_bandpass_filter(options=None)[source]

Apply bandpass filtering with customizable filter type, cutoff frequencies, and order.

apply_detrending(options=None)[source]

Detrend the signal with customizable options.

apply_normalization(options=None)[source]

Normalize the signal to a specified range.

apply_smoothing(options=None)[source]

Smooth the signal using different methods such as moving average or Gaussian.

apply_enhancement(options=None)[source]

Enhance critical points in the signal using methods such as squaring or absolute value.

apply_advanced_filtering(options=None)[source]

Apply advanced signal filtering techniques using the AdvancedSignalFiltering class.

Examples

>>> import numpy as np
>>> from vitalDSP.transforms.vital_transformation import VitalTransformation
>>>
>>> # Example 1: Basic ECG signal transformation
>>> ecg_signal = np.random.randn(1000)  # Simulated ECG signal
>>> transformer = VitalTransformation(ecg_signal, fs=256, signal_type="ECG")
>>> transformed_signal = transformer.apply_transformations()
>>> print(f"Transformed signal shape: {transformed_signal.shape}")
>>>
>>> # Example 2: PPG signal with custom options
>>> ppg_signal = np.random.randn(2000)  # Simulated PPG signal
>>> transformer_ppg = VitalTransformation(ppg_signal, fs=128, signal_type="PPG")
>>> options = {
...     'artifact_removal': 'baseline_correction',
...     'artifact_removal_options': {'cutoff': 0.5},
...     'bandpass_filter': {'lowcut': 0.5, 'highcut': 8.0, 'filter_order': 4, 'filter_type': 'butter'},
...     'detrending': {'detrend_type': 'linear'},
...     'normalization': {'normalization_range': (0, 1)}
... }
>>> transformed_ppg = transformer_ppg.apply_transformations(options=options)
>>> print(f"Transformed PPG shape: {transformed_ppg.shape}")
>>>
>>> # Example 3: Individual transformation methods
>>> transformer = VitalTransformation(ecg_signal, fs=256, signal_type="ECG")
>>> detrended = transformer.apply_detrending(method='linear')
>>> normalized = transformer.apply_normalization(normalization_range=(0, 1))
>>> filtered = transformer.apply_bandpass_filter(options={'lowcut': 0.5, 'highcut': 40, 'order': 4})
>>> print(f"Detrended signal range: [{detrended.min():.3f}, {detrended.max():.3f}]")
>>> print(f"Normalized signal range: [{normalized.min():.3f}, {normalized.max():.3f}]")
apply_advanced_filtering(options=None)[source]

Apply advanced signal filtering using the AdvancedSignalFiltering class.

Parameters:

options (dict, optional) – Options to customize the advanced filtering process.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_advanced_filtering(options={'filter_type': 'kalman_filter', 'R': 0.1, 'Q': 0.01})
>>> print(transformer.signal)
apply_artifact_removal(method='baseline_correction', options=None)[source]

Apply artifact removal to the signal.

Parameters:
  • method (str, optional) – The artifact removal method to use. Default is ‘baseline_correction’.

  • options (dict, optional) – Additional options specific to the selected method.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_artifact_removal(method='baseline_correction', options={'cutoff': 0.5})
>>> print(transformer.signal)
apply_bandpass_filter(options=None)[source]

Apply bandpass filtering with customizable filter type, cutoff frequencies, and order.

Parameters:

options (dict, optional) – A dictionary of filter options.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_bandpass_filter(options={'lowcut': 0.5, 'highcut': 30, 'filter_order': 4, 'filter_type': 'butter'})
>>> print(transformer.signal)
apply_detrending(options=None)[source]

Detrend the signal with customizable options using pure NumPy implementation.

This method removes trends from the signal, which is crucial for physiological signal processing. Detrending eliminates baseline wander and drift that can interfere with feature extraction and analysis.

Parameters:

options (dict, optional) –

A dictionary of options for detrending. Default options: {

’detrend_type’: ‘linear’, # ‘linear’, ‘constant’, or ‘polynomial’ ‘polynomial_order’: 3, # Used when detrend_type=’polynomial’ ‘break_points’: None, # For piecewise detrending

}

Returns:

Modifies self.signal in place.

Return type:

None

Notes

Detrending Types: - linear: Removes linear trend using least squares fitting - constant: Removes DC component (mean value) - polynomial: Removes polynomial trend of specified order

The implementation uses pure NumPy for better performance and removes the scipy dependency.

Clinical Applications: - ECG: Removes baseline wander due to respiration or movement - PPG: Eliminates DC shifts and slow baseline drift - General: Ensures zero-mean signal for accurate feature extraction

Examples

>>> import numpy as np
>>> from vitalDSP.transforms.vital_transformation import VitalTransformation
>>>
>>> # Example 1: Linear detrending (default)
>>> signal_with_drift = np.random.randn(1000) + np.linspace(0, 10, 1000)
>>> transformer = VitalTransformation(signal_with_drift, fs=256, signal_type='ECG')
>>> transformer.apply_detrending(options={'detrend_type': 'linear'})
>>> print(f"Signal mean after detrending: {np.mean(transformer.signal):.6f}")
>>>
>>> # Example 2: Constant (mean) detrending
>>> ecg_signal = np.random.randn(1000) + 5.0  # Signal with DC offset
>>> transformer2 = VitalTransformation(ecg_signal, fs=256, signal_type='ECG')
>>> transformer2.apply_detrending(options={'detrend_type': 'constant'})
>>> print(f"Signal mean after constant detrend: {np.mean(transformer2.signal):.6f}")
>>>
>>> # Example 3: Polynomial detrending
>>> ppg_signal = np.random.randn(1000) + 0.001 * np.arange(1000)**2
>>> transformer3 = VitalTransformation(ppg_signal, fs=128, signal_type='PPG')
>>> transformer3.apply_detrending(options={
...     'detrend_type': 'polynomial',
...     'polynomial_order': 2
... })
>>> print(f"Detrended PPG signal length: {len(transformer3.signal)}")
apply_enhancement(options=None)[source]

Enhance critical points in the signal using methods such as squaring or absolute value.

Parameters:

options (dict, optional) – Options to customize the enhancement process.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_enhancement(options={'enhance_method': 'square'})
>>> print(transformer.signal)
apply_normalization(options=None)[source]

Normalize the signal to a specified range.

Parameters:

options (dict, optional) – A dictionary of normalization options.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_normalization(options={'normalization_range': (0, 1)})
>>> print(transformer.signal)
apply_smoothing(options=None)[source]

Smooth the signal using different methods such as moving average or Gaussian.

Parameters:

options (dict, optional) – Options to customize the smoothing process.

Return type:

None

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformer.apply_smoothing(options={'smoothing_method': 'moving_average', 'window_size': 5, 'iterations': 2})
>>> print(transformer.signal)
apply_transformations(options=None, method_order=None)[source]

Apply a sequence of transformations to process the signal.

Parameters:
  • options (dict, optional) – A dictionary of options to customize each step in the transformation process. Default options will be used if not provided.

  • method_order (list, optional) – A list specifying the order in which to apply the methods. Default is the order defined in the class.

Returns:

transformed_signal – The fully transformed signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.random.randn(1000)  # Example signal
>>> options = {
>>>     'artifact_removal': 'baseline_correction',
>>>     'artifact_removal_options': {'cutoff': 0.5},
>>>     'bandpass_filter': {'lowcut': 0.5, 'highcut': 30, 'filter_order': 4, 'filter_type': 'butter'},
>>>     'detrending': {'detrend_type': 'linear'},
>>>     'normalization': {'normalization_range': (0, 1)},
>>>     'smoothing': {'smoothing_method': 'moving_average', 'window_size': 5, 'iterations': 2},
>>>     'enhancement': {'enhance_method': 'square'},
>>>     'advanced_filtering': {'filter_type': 'kalman_filter', 'options': {'R': 0.1, 'Q': 0.01}},
>>> }
>>> method_order = ['artifact_removal', 'bandpass_filter', 'detrending', 'normalization', 'smoothing', 'enhancement', 'advanced_filtering']
>>> transformer = ECG_PPG_Transformation(signal, fs=256, signal_type='ECG')
>>> transformed_signal = transformer.apply_transformations(options, method_order)
>>> print(transformed_signal)

Wavelet FFT Fusion

Combining Wavelet Transform with FFT (Fast Fourier Transform) to exploit the strengths of both in analyzing different aspects of the signal.

Signal Transforms Module for Physiological Signal Processing

This module provides comprehensive capabilities for physiological signal processing including ECG, PPG, EEG, and other vital signs.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Object-oriented design with comprehensive classes - Multiple processing methods and functions - NumPy integration for numerical computations

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.transforms.wavelet_fft_fusion import WaveletFftFusion
>>> signal = np.random.randn(1000)
>>> processor = WaveletFftFusion(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.transforms.wavelet_fft_fusion.WaveletFFTfusion(signal, wavelet_type='db', order=4, **kwargs)[source]

Bases: object

A class to perform the fusion of Wavelet Transform and FFT on a signal.

This fusion technique combines the time-frequency localization capability of wavelet transforms with the frequency domain analysis provided by the Fast Fourier Transform (FFT). This method is particularly useful for signals that require both time-domain and frequency-domain analysis.

compute_fusion : method

Computes the fusion of wavelet transform and FFT for the signal.

compute_fusion()[source]

Compute the fusion of Wavelet Transform and FFT for the signal.

This method first applies the discrete wavelet transform (DWT) to the signal to obtain wavelet coefficients. Then, it computes the FFT of the original signal. The fusion is performed by multiplying corresponding wavelet and FFT coefficients.

Returns:

The fusion of wavelet coefficients and FFT coefficients.

Return type:

numpy.ndarray

Example

>>> import numpy as np
>>> signal = np.sin(np.linspace(0, 10, 1000))
>>> fusion = WaveletFFTfusion(signal, wavelet_type='db', order=4)
>>> fusion_result = fusion.compute_fusion()
>>> print(fusion_result)

Wavelet Transform

Wavelet Transform is a powerful tool for multi-resolution analysis of signals, offering both time and frequency localization.

Wavelet Transform Module for Physiological Signal Processing

This module provides comprehensive wavelet transform capabilities for physiological signals including ECG, PPG, EEG, and other vital signs. It implements Discrete Wavelet Transform (DWT) with multiple mother wavelets and inverse transform capabilities for signal analysis and reconstruction.

Author: vitalDSP Team Date: 2025-01-27 Version: 1.0.0

Key Features: - Discrete Wavelet Transform (DWT) implementation - Multiple mother wavelets (Haar, Daubechies, Coiflets, etc.) - Inverse Wavelet Transform for signal reconstruction - Multi-level decomposition capabilities - Signal length preservation options - Integration with mother wavelet utilities

Examples:

Basic wavelet transform:
>>> import numpy as np
>>> from vitalDSP.transforms.wavelet_transform import WaveletTransform
>>> signal = np.sin(np.linspace(0, 10, 1000)) + np.random.normal(0, 0.1, 1000)
>>> wt = WaveletTransform(signal, wavelet_name="haar")
>>> coefficients = wt.perform_wavelet_transform()
>>> print(f"Coefficients shape: {len(coefficients)}")
Signal reconstruction:
>>> reconstructed = wt.perform_inverse_wavelet_transform(coefficients)
>>> print(f"Reconstruction error: {np.mean((signal - reconstructed)**2):.6f}")
Different wavelets:
>>> wt_db4 = WaveletTransform(signal, wavelet_name="db4")
>>> wt_coif2 = WaveletTransform(signal, wavelet_name="coif2")
>>> db4_coeffs = wt_db4.perform_wavelet_transform()
>>> coif2_coeffs = wt_coif2.perform_wavelet_transform()
class vitalDSP.transforms.wavelet_transform.WaveletTransform(signal, wavelet_name='haar', same_length=True)[source]

Bases: object

A class to perform Discrete Wavelet Transform (DWT) on signals using different mother wavelets.

perform_wavelet_transform : method

Computes the DWT of the signal.

perform_inverse_wavelet_transform : method

Reconstructs the signal using the inverse DWT.

perform_inverse_wavelet_transform(coeffs)[source]

Perform the Inverse Discrete Wavelet Transform (IDWT) to reconstruct the signal.

Parameters:

coeffs (list) – Wavelet coefficients from the wavelet transform.

Returns:

Reconstructed signal from the wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> wavelet_transform = WaveletTransform(signal, wavelet_name='db')
>>> coeffs = wavelet_transform.perform_wavelet_transform(level=3)
>>> reconstructed_signal = wavelet_transform.perform_inverse_wavelet_transform(coeffs)
>>> print(reconstructed_signal)
perform_wavelet_transform(level=1)[source]

Perform the Discrete Wavelet Transform (DWT) on the signal.

Parameters:

level (int, optional) – The number of decomposition levels (default is 1).

Returns:

Wavelet coefficients as a list of arrays. coeffs[0] through coeffs[-2] are detail coefficient arrays (one per level, in order from finest to coarsest). coeffs[-1] is the final approximation array.

Return type:

list

Examples

>>> signal = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100)
>>> wavelet_transform = WaveletTransform(signal, wavelet_name='db')
>>> coeffs = wavelet_transform.perform_wavelet_transform(level=3)
>>> print(coeffs)