Skip to content

Latest commit

 

History

History
266 lines (210 loc) · 9.8 KB

File metadata and controls

266 lines (210 loc) · 9.8 KB

Continuous Wavelet Transform (CWT) From Scratch

An interactive Streamlit web application for performing Continuous Wavelet Transform (CWT) analysis and Fast Fourier Transform (FFT) on signal data, with a focus on Phonocardiogram (PCG) signal analysis.

Features

Signal Input

  • Upload Custom Data: Load 2-column .txt files (time and signal values)
  • Generate Synthetic Signals: Create sine waves with customizable parameters:
    • Two independent sine wave components
    • Adjustable frequency, amplitude, and noise levels
    • Configurable sampling frequency and duration

Signal Preprocessing

  • Signal Slicing: Select specific time ranges for focused analysis
  • FFT-Based Bandpass Filtering: 20-330 Hz frequency range filtering
  • Decimation: Automatic downsampling to ~2000 Hz if needed
  • Smoothing: Moving average noise reduction

Signal Analysis

  1. Time-Domain Analysis

    • Normalized signal visualization
    • Shannon Energy envelope computation with peak detection
    • Interactive plots with zoom capabilities
    • Configurable peak detection parameters:
      • Shannon peak threshold
      • Minimum peak distance
  2. Shannon Energy Timing Analysis

    • Systole & Diastole Calculation: Automatic interval classification based on Shannon Energy peaks
    • Component Intervals Table: Displays S1-S2 and S2-S1 intervals in seconds and milliseconds
    • Heart Rate Estimation: Calculated from systole and diastole intervals
    • Peak Visualization: Black markers on detected energy peaks
  3. Frequency-Domain Analysis (FFT)

    • Fast Fourier Transform using Radix-2 algorithm (implemented from scratch)
    • Frequency spectrum visualization
    • Magnitude analysis up to Nyquist frequency
  4. Time-Frequency Analysis (CWT)

    • Continuous Wavelet Transform using Morlet wavelet
    • Fast CWT Mode: Vectorized computation (significantly faster)
    • Interactive scalogram visualization (contour plot)
    • 3D surface plot of CWT coefficients
    • Configurable CWT parameters:
      • Morlet ω₀ parameter
      • Scale parameters (start, step, count)
      • Number of time translations

PCG Component Detection

  • Automated Feature Detection: Identify heart sound components (S1, S2, M1, T1, A2, P2)
  • Binary Thresholding: Adjustable amplitude threshold for region detection
  • Center of Gravity (CoG): Weight-based calculation for time, frequency, and amplitude of each detected component
  • Sub-segmentation: Split merged components using 1D time profile analysis
  • Adaptive Labeling: Frequency-based discrimination (S1: <60 Hz, S2: >60 Hz)
  • Manual Override: Force cycle type classification (S1 or S2)
  • Component Intervals: Calculate time differences between consecutive PCG components
  • Systole/Diastole Detection: Automatic S1-S2 and S2-S1 interval calculation
  • Component Visualization: Labels and markers displayed on scalogram

Installation

Prerequisites

  • Python 3.7 or higher
  • pip package manager

Dependencies

Install the required packages:

pip install streamlit numpy pandas scipy plotly

Or use the requirements file if available:

pip install -r requirements.txt

Usage

Running the Application

  1. Navigate to the project directory:
cd CWT-From-Scratch
  1. Launch the Streamlit app:
streamlit run cwt.py
  1. The application will open in your default web browser (typically at http://localhost:8501)

Using the Application

Option 1: Upload Signal Data

  1. Select "Upload File" in the sidebar
  2. Upload a .txt file with two columns: time and signal values
  3. The sampling frequency will be automatically calculated from the time data
  4. Adjust CWT parameters as needed

Option 2: Generate Synthetic Signal

  1. Select "Generate Sine Wave" in the sidebar
  2. Configure signal parameters:
    • Sampling frequency (Hz)
    • Duration (seconds)
    • Frequency and amplitude for two sine components
    • Noise level
  3. The signal will be generated automatically

Performing CWT Analysis

  1. Adjust CWT parameters in the sidebar:

    • ω₀: Morlet wavelet parameter (default: 2π × 0.849)
    • Start Scale (a): Initial scale value
    • Scale Step (da): Increment for scale values
    • Number of Scales: Resolution in frequency dimension
    • Number of Time-Shifts: Resolution in time dimension
    • Use Fast CWT: Enable vectorized computation for faster processing
  2. Optional: Signal Slicing

    • Enable signal slicing to analyze specific time ranges
    • Use the time range slider to select the region of interest
  3. Optional: Preprocessing

    • Apply preprocessing for PCG signals:
      • FFT-based bandpass filter (20-330 Hz)
      • Decimation to ~2000 Hz
      • Moving average smoothing
  4. Click "Compute CWT" to perform the analysis

  5. View results:

    • CWT scalogram (contour plot)
    • Binary mask with threshold adjustment
    • Detected PCG components with time, frequency, and amplitude
    • Optional 3D surface plot
    • Scale-to-frequency and translation-to-time mappings

Shannon Energy Analysis

  1. Adjust Shannon Energy parameters in the sidebar:

    • Shannon Peak Threshold: Minimum prominence for peak detection (0.0-1.0)
    • Min Peak Distance: Minimum time separation between peaks (0.05-0.5s)
  2. View Shannon Energy results:

    • Energy envelope overlay on signal plot
    • Detected peaks marked with black crosses
    • Component Intervals table showing S1-S2 and S2-S1 durations
    • Average Systole interval (S1-S2)
    • Average Diastole interval (S2-S1)
    • Estimated heart rate in BPM

PCG Component Detection

  1. After computing CWT, adjust the CWT Amplitude Threshold slider
  2. Optionally use Force Cycle Type to override automatic S1/S2 classification
  3. Enable/disable Sub-segmentation to split merged components
  4. View detection results:
    • Binary mask with labeled components
    • Detection Analysis showing frequency, energy, and duration for each group
    • PCG Components table with time, frequency, and weight
    • Component Intervals showing time between consecutive components
    • Systole (S1-S2) and Diastole (S2-S1) intervals
    • Estimated heart rate

Data Format

Input File Format

The application expects a 2-column space or tab-delimited .txt file:

0.0000    0.1234
0.0010    0.2345
0.0020    0.3456
...

Column 1: Time (seconds)
Column 2: Signal amplitude

Technical Details

Algorithms

CWT Implementation

  • Wavelet: Complex Morlet wavelet
  • Method: Direct convolution in time domain (standard mode) or vectorized computation (fast mode)
  • Normalization: Energy-preserving normalization
  • Output: Magnitude of complex CWT coefficients
  • Fast Mode: Vectorized time-domain computation using NumPy broadcasting

FFT Implementation

  • Algorithm: Radix-2 Cooley-Tukey FFT
  • Padding: Zero-padding to nearest power of 2
  • Scaling: Normalized magnitude spectrum

Shannon Energy

  • Formula: E(t) = -1/N × Σ(x²·log(x² + ε))
  • Parameters: Frame length (default: 0.02s) and hop size (frame_len/2) based on sampling rate
  • Output: Energy envelope with mean and standard deviation
  • Peak Detection: Simple peak finder with configurable prominence and minimum distance

Systole/Diastole Detection

  • Method: Adaptive threshold-based interval classification
  • Threshold: (min_interval + max_interval) / 2
  • Systole: Intervals ≤ threshold (typically S1-S2)
  • Diastole: Intervals > threshold (typically S2-S1)
  • Heart Rate: 60 / (avg_systole + avg_diastole)

Signal Preprocessing

  • FFT-Based Bandpass Filter:
    • Frequency range: 20-330 Hz
    • Smooth transitions to avoid ringing (5 Hz transition width)
  • Decimation: Downsample to target frequency (~2000 Hz)
  • Smoothing: 5-point moving average

PCG Component Labeling

  • Frequency-Based Discrimination:
    • S1 components: < 60 Hz (M1, T1)
    • S2 components: > 60 Hz (A2, P2)
  • Adaptive Grouping: Time-based clustering with dynamic threshold
  • Sub-segmentation: 1D time profile peak detection to split merged regions

Performance

  • Caching: CWT results are cached using Streamlit's caching mechanism
  • Progress Tracking: Real-time progress bar during CWT computation
  • Interactive Plots: Plotly-based visualizations with zoom and pan
  • Fast CWT: Vectorized computation significantly reduces processing time for large datasets
  • Adaptive Parameters: Signal slicing and preprocessing reduce computational load

Applications

This tool is particularly useful for:

  • Cardiac Signal Analysis: PCG (phonocardiogram) heart sound analysis with automated S1/S2 detection
  • Clinical Diagnostics: Systole and diastole interval measurement for cardiac assessment
  • Signal Processing Education: Understanding time-frequency analysis and wavelet transforms
  • Research: Exploring wavelet transform parameters and heart sound characteristics
  • Feature Extraction: Identifying signal components in time-frequency domain with weight-based CoG calculation

Algorithm Complexity

  • CWT Computation: O(N × M × K) where:
    • N = number of scales
    • M = number of translations
    • K = signal length
  • FFT Computation: O(N log N) where N is the padded signal length

Limitations

  • Large parameter combinations (high scale/translation counts) may result in long computation times
  • Memory usage scales with the product of scales and translations
  • CWT is computed in the time domain (not optimized with FFT-based convolution)

License

This project is open-source and available for educational and research purposes.

Author

Created as part of signal processing and biomedical engineering research.

Acknowledgments

  • Wavelet theory and Morlet wavelet implementation
  • PCG signal analysis methodology
  • Streamlit framework for interactive web applications