This section covers the comprehensive respiratory analysis techniques provided by the VitalDSP library. These methods are designed to estimate respiratory rates, perform multimodal analysis, preprocess signals, and detect sleep apnea from various physiological signals.
Techniques for analyzing respiratory patterns in physiological signals (e.g., PPG, ECG), with built-in preprocessing, filtering, and noise reduction options.
Respiratory Analysis Module for Physiological Signal Processing
This module provides comprehensive respiratory analysis capabilities for physiological
signals including PPG, ECG, and other vital signs. It implements multiple methods
for respiratory rate estimation including time-domain counting, frequency-domain
analysis, and advanced signal processing techniques.
Author: vitalDSP Team
Date: 2025-01-27
Version: 1.0.0
A class for analyzing respiratory patterns in physiological signals (e.g., PPG, ECG),
with built-in preprocessing, filtering, and noise reduction options.
Computes the respiratory rate from the signal after applying preprocessing,
using peak detection or zero-crossing methods.
Parameters:
method (str, optional) – Method used for breath detection. Options: ‘peaks’, ‘zero_crossing’, ‘time_domain’, ‘frequency_domain’, ‘fft_based’, ‘counting’. Default is ‘counting’.
correction_method (str, optional) – Method for correcting false detections. Options: ‘interpolation’, ‘adaptive_threshold’. Default is None.
min_breath_duration (float, optional) – Minimum breath duration in seconds. Default is 0.5s (30 breaths/min).
max_breath_duration (float, optional) – Maximum breath duration in seconds. Default is 6s (10 breaths/min).
preprocess_config (PreprocessConfig, optional) – Configuration for signal preprocessing (filtering and noise reduction). Default is None, and a default PreprocessConfig will be used.
Returns:
The estimated respiratory rate in breaths per minute.
Compute respiratory rate using multiple methods and return consensus estimate.
This method runs multiple RR estimation algorithms in parallel and combines
their results using median consensus, providing a more robust estimate than
any single method. It also returns quality metrics including standard deviation
and confidence scores.
Parameters:
preprocess_config (PreprocessConfig, optional) – Configuration for signal preprocessing. If None, uses default configuration.
methods (list of str, optional) – List of methods to use for ensemble estimation.
Default: [‘counting’, ‘fft_based’, ‘frequency_domain’, ‘time_domain’]
Available methods:
- ‘counting’: Peak detection with interval analysis (peak_detection_rr)
- ‘fft_based’: Fast Fourier Transform based estimation
- ‘frequency_domain’: Welch PSD based estimation
- ‘time_domain’: Autocorrelation based estimation
- ‘peaks’: Peak detection (old method, uses _detect_breaths_by_peaks)
- ‘zero_crossing’: Zero-crossing detection
Returns:
Dictionary containing:
- ‘respiratory_rate’: float, consensus RR estimate (median of valid methods)
- ‘individual_estimates’: dict, per-method estimates (method_name: rr_value)
- ‘std’: float, standard deviation across methods (measure of agreement)
- ‘confidence’: float, confidence score (0-1 scale, higher = more agreement)
- ‘n_methods’: int, number of methods that returned valid estimates
- ‘quality’: str, quality rating (‘high’, ‘medium’, ‘low’)
>>> # Use specific methods only>>> result=resp.compute_respiratory_rate_ensemble(methods=['fft_based','frequency_domain'])
Notes
The ensemble approach provides several advantages:
1. More robust to method-specific failures
2. Automatic outlier rejection (methods with implausible results)
3. Quality/confidence metrics for result interpretation
4. Better performance on noisy or challenging signals
Confidence scoring:
- confidence > 0.8: High agreement (std < 1 BPM) - Very reliable
- confidence 0.5-0.8: Medium agreement (std 1-3 BPM) - Reliable
- confidence < 0.5: Low agreement (std > 3 BPM) - Use with caution
If fewer than 2 methods return valid estimates, confidence is automatically
set to 0.3 (low) as consensus requires multiple opinions.
Estimate respiratory rate using the FFT (Fast Fourier Transform) method
with respiratory band filtering.
This method computes the FFT power spectrum and identifies the dominant
frequency within the physiological respiratory range (0.1-0.5 Hz or 6-30 BPM).
The respiratory band filtering prevents false detection of cardiac frequencies
or high-frequency noise artifacts.
Parameters:
signal (numpy.ndarray) – The input respiratory signal.
sampling_rate (float) – The sampling rate of the signal in Hz.
preprocess (str, optional) – The preprocessing method to apply before estimation (e.g., “bandpass”, “wavelet”).
freq_min (float, optional (default=0.1)) – Minimum respiratory frequency in Hz (6 BPM). Can be adjusted for different
populations (e.g., 0.05 Hz for very slow breathing).
freq_max (float, optional (default=0.5)) – Maximum respiratory frequency in Hz (30 BPM). Can be increased to 0.67 Hz
(40 BPM) for tachypnea or exercise conditions.
preprocess_kwargs (dict, optional) – Additional arguments for the preprocessing function.
Returns:
rr – Estimated respiratory rate in breaths per minute.
>>> # For exercise/tachypnea (up to 40 BPM)>>> rr=fft_based_rr(signal,sampling_rate=100,freq_max=0.67)
Notes
This implementation fixes the critical bug in the original version that searched
the entire frequency spectrum, often picking cardiac frequencies (1-2 Hz / 60-120 BPM)
instead of respiratory frequencies. The corrected version restricts the search to
the physiological respiratory band.
The method includes SNR validation to warn if the detected peak has low prominence,
which may indicate poor signal quality or unreliable estimation.
References
[charlton2018]
Charlton, P.H., et al. (2018). Breathing rate estimation from the
electrocardiogram and photoplethysmogram: A review. IEEE Reviews in
Biomedical Engineering, 11, 2-20.
### Frequency Domain Respiratory Rate Estimation
Estimate respiratory rate in the frequency domain, leveraging spectral analysis techniques.
Respiratory Analysis 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:
- Multiple processing methods and functions
- NumPy integration for numerical computations
- SciPy integration for advanced signal processing
Estimate respiratory rate using frequency-domain Welch method with
respiratory band filtering.
This method computes the power spectral density (PSD) using Welch’s method,
which provides better noise reduction than standard FFT through averaging of
overlapping segments. The search is restricted to the physiological respiratory
frequency range (0.1-0.5 Hz or 6-30 BPM).
Parameters:
signal (numpy.ndarray) – The input respiratory signal.
sampling_rate (float) – The sampling rate of the signal in Hz.
preprocess (str, optional) – The preprocessing method to apply before estimation (e.g., “bandpass”, “wavelet”).
nperseg (int, optional) – Length of each segment for Welch method. If None, automatically computed to
achieve ~0.05 Hz frequency resolution (3 BPM discrimination). Larger nperseg
provides better frequency resolution but requires longer signals.
freq_min (float, optional (default=0.1)) – Minimum respiratory frequency in Hz (6 BPM).
freq_max (float, optional (default=0.5)) – Maximum respiratory frequency in Hz (30 BPM). Can be increased to 0.67 Hz
(40 BPM) for tachypnea or exercise.
preprocess_kwargs (dict, optional) – Additional arguments for the preprocessing function.
Returns:
rr – Estimated respiratory rate in breaths per minute.
>>> # Specify custom nperseg for better frequency resolution>>> rr=frequency_domain_rr(signal,sampling_rate=100,nperseg=512)
Notes
This implementation fixes two critical bugs in the original version:
1. Missing respiratory band filtering (searched entire spectrum, could pick cardiac)
2. Inappropriate nperseg default (256 samples → only 0.5 Hz resolution at 128 Hz sampling)
The corrected version:
- Automatically sets nperseg to achieve 0.05 Hz resolution (3 BPM discrimination)
- Restricts search to respiratory frequency band
- Includes SNR validation for quality assessment
- Provides comprehensive warnings for edge cases
Frequency Resolution:
Δf = sampling_rate / nperseg
For respiratory analysis, we need Δf ≤ 0.05 Hz to discriminate between different
breathing rates (e.g., 12 BPM vs 15 BPM = 0.2 Hz vs 0.25 Hz).
References
### Peak Detection Respiratory Rate Estimation
Estimate respiratory rate using peak detection algorithms, focusing on identifying inhalation and exhalation peaks in the signal.
Respiratory Analysis 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:
- Multiple processing methods and functions
- NumPy integration for numerical computations
- SciPy integration for advanced signal processing
- Configurable parameters and settings
- Pattern and anomaly detection
Estimate respiratory rate using peak detection with interval-based analysis.
This method detects breathing peaks in the respiratory signal and calculates
the rate based on the median interval between peaks, which is more robust than
simple peak counting. Peaks are validated against physiological constraints
(1.5-10 seconds between breaths).
Parameters:
signal (numpy.ndarray) – The input respiratory signal.
sampling_rate (float) – The sampling rate of the signal in Hz.
preprocess (str, optional) – The preprocessing method to apply before estimation (e.g., “bandpass”, “wavelet”).
min_peak_distance (float, optional (default=1.5)) – Minimum distance between peaks in seconds. Default 1.5s corresponds to 40 BPM max.
Previous default of 0.5s was too permissive (allowed 120 BPM).
height (float or None, optional) – Minimum height required for a peak. If None, uses adaptive threshold.
threshold (float or None, optional) – Minimum difference between a peak and its neighboring points.
prominence (float or None, optional) – Minimum prominence of peaks. If None, uses adaptive prominence (0.3 * signal std).
width (int or None, optional) – Minimum width required for a peak, measured as the number of samples.
preprocess_kwargs (dict, optional) – Additional arguments for the preprocessing function.
Returns:
rr – Estimated respiratory rate in breaths per minute.
>>> # For faster breathing (exercise), reduce min_peak_distance>>> rr=peak_detection_rr(signal,sampling_rate=100,min_peak_distance=1.0)
Notes
This implementation fixes critical bugs in the original version:
1. Changed from simple peak counting (num_peaks / duration) to interval-based analysis
2. Increased min_peak_distance default from 0.5s to 1.5s (40 BPM max instead of 120 BPM)
3. Added adaptive prominence threshold if not specified
4. Validates intervals against physiological range (1.5-10 seconds)
5. Uses median interval for robustness against outliers
6. Adds quality metrics (coefficient of variation) for breathing regularity
The interval-based approach is more accurate because:
- Handles irregular breathing patterns
- Robust to missed or false peaks
- Provides quality metrics for result confidence
References
[pan1985]
Pan, J., & Tompkins, W. J. (1985). A real-time QRS detection algorithm.
IEEE transactions on biomedical engineering, (3), 230-236.
### Time Domain Respiratory Rate Estimation
Estimate respiratory rate using time-domain methods, which analyze the signal’s temporal characteristics.
Respiratory Analysis 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:
- Multiple processing methods and functions
- NumPy integration for numerical computations
Estimate respiratory rate using time-domain autocorrelation method.
This method computes the autocorrelation of the respiratory signal and finds
the dominant periodicity within the physiological respiratory range (1.5-10 seconds
corresponding to 40-6 breaths/min).
Parameters:
signal (numpy.ndarray) – The input respiratory signal.
sampling_rate (float) – The sampling rate of the signal in Hz.
preprocess (str, optional) – The preprocessing method to apply before estimation (e.g., “bandpass”, “wavelet”).
preprocess_kwargs (dict, optional) – Additional arguments for the preprocessing function.
Returns:
rr – Estimated respiratory rate in breaths per minute.
This implementation fixes the critical bug in the original version that used
np.diff() followed by np.argmax(), which finds maximum slope instead of maximum peak.
The corrected version uses scipy.signal.find_peaks() to properly identify
autocorrelation peaks within the valid respiratory range.
### Respiratory and Cardiac Signal Fusion
Combine respiratory and cardiac signals to enhance analysis and gain insights into the interactions between respiratory and cardiac activities.
Respiratory Analysis 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:
- Multiple processing methods and functions
- NumPy integration for numerical computations
Detect sleep apnea events based on amplitude thresholding.
Parameters:
signal (numpy.ndarray) – The input respiratory signal.
sampling_rate (float) – The sampling rate of the signal in Hz.
threshold (float) – Amplitude threshold below which an apnea event is detected.
min_duration (int, optional (default=10)) – Minimum duration (in seconds) for which the signal must be below the threshold to be considered an apnea event.
preprocess (str, optional) – The preprocessing method to apply before detection (e.g., “bandpass”, “wavelet”).
preprocess_kwargs (dict, optional) – Additional arguments for the preprocessing function.
Returns:
apnea_events – List of apnea events, each represented as a tuple (start_time, end_time) in seconds.
### Pause Detection for Sleep Apnea
Identify pauses in respiratory signals that may indicate sleep apnea events, critical for early diagnosis and intervention.
Respiratory Analysis 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:
- Multiple processing methods and functions
- NumPy integration for numerical computations
- Configurable parameters and settings
- Pattern and anomaly detection