Signal Quality Assessment

This section covers the signal quality assessment techniques provided by the VitalDSP library. These methods are designed to evaluate and improve the quality of biomedical signals by estimating signal-to-noise ratios, detecting and removing artifacts, and separating sources.

Adaptive SNR Estimation

Methods for adaptively estimating the Signal-to-Noise Ratio (SNR) of signals, allowing for real-time adjustments to improve signal quality.

Signal Quality Assessment 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

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.adaptive_snr_estimation import AdaptiveSnrEstimation
>>> signal = np.random.randn(1000)
>>> processor = AdaptiveSnrEstimation(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.signal_quality_assessment.adaptive_snr_estimation.adaptive_threshold_snr(signal, threshold=0.5)[source]

Estimate SNR adaptively by applying a threshold to segment the signal.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • threshold (float, optional (default=0.5)) – The amplitude threshold for detecting noise segments.

Returns:

snr_estimate – The estimated SNR.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01)) + 0.1 * np.random.normal(size=1000)
>>> snr_estimate = adaptive_threshold_snr(signal, threshold=0.3)
>>> print(snr_estimate)
vitalDSP.signal_quality_assessment.adaptive_snr_estimation.recursive_snr_estimation(signal, alpha=0.9)[source]

Estimate SNR recursively using an exponential moving average.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • alpha (float, optional (default=0.9)) – Smoothing factor for the exponential moving average.

Returns:

snr_estimates – Array of SNR estimates for each point in the signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01)) + 0.1 * np.random.normal(size=1000)
>>> snr_estimates = recursive_snr_estimation(signal)
>>> print(snr_estimates)
vitalDSP.signal_quality_assessment.adaptive_snr_estimation.sliding_window_snr(signal, window_size=100, step_size=50)[source]

Estimate SNR adaptively using a sliding window approach.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • window_size (int, optional (default=100)) – The size of the sliding window.

  • step_size (int, optional (default=50)) – The step size for moving the window.

Returns:

snr_estimates – Array of SNR estimates for each window.

Return type:

numpy.ndarray

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01)) + 0.1 * np.random.normal(size=1000)
>>> snr_estimates = sliding_window_snr(signal)
>>> print(snr_estimates)

Artifact Detection and Removal

Techniques for detecting and removing artifacts from signals, crucial for maintaining the integrity of biomedical signal analysis.

Signal Quality Assessment 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 - Pattern and anomaly detection

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.artifact_detection_removal import ArtifactDetectionRemoval
>>> signal = np.random.randn(1000)
>>> processor = ArtifactDetectionRemoval(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.signal_quality_assessment.artifact_detection_removal.ArtifactDetectionRemoval(signal, fs=250)[source]

Bases: object

A comprehensive artifact detection and removal class for physiological signals.

This class provides various methods for detecting and removing artifacts from physiological signals including ECG, PPG, EEG, and other vital signs.

Parameters:
  • signal (numpy.ndarray) – The input signal to process.

  • fs (float, optional) – Sampling frequency of the signal (default: 250 Hz).

Examples

>>> import numpy as np
>>> signal = np.random.randn(1000)
>>> adr = ArtifactDetectionRemoval(signal, fs=250)
>>> artifacts = adr.detect_artifacts()
>>> cleaned_signal = adr.remove_artifacts()
detect_artifacts(method='threshold', **kwargs)[source]

Detect artifacts in the signal using various methods.

Parameters:
  • method (str, optional) – Method to use for artifact detection. Options: - ‘threshold’: Amplitude thresholding (default) - ‘z_score’: Z-score based detection - ‘kurtosis’: Kurtosis based detection - ‘adaptive’: Adaptive threshold detection

  • **kwargs – Additional parameters for the specific detection method.

Returns:

Indices of detected artifacts.

Return type:

numpy.ndarray

process(detection_method='threshold', removal_method='moving_average', detection_kwargs=None, removal_kwargs=None)[source]

Complete processing pipeline: detect and remove artifacts.

Parameters:
  • detection_method (str, optional) – Method for artifact detection (default: ‘threshold’).

  • removal_method (str, optional) – Method for artifact removal (default: ‘moving_average’).

  • detection_kwargs (dict, optional) – Parameters for detection method.

  • removal_kwargs (dict, optional) – Parameters for removal method.

Returns:

Processed signal with artifacts removed.

Return type:

numpy.ndarray

remove_artifacts(method='moving_average', **kwargs)[source]

Remove artifacts from the signal using various methods.

Parameters:
  • method (str, optional) – Method to use for artifact removal. Options: - ‘moving_average’: Moving average filter (default) - ‘wavelet’: Wavelet-based removal - ‘median’: Median filter - ‘iterative’: Iterative removal

  • **kwargs – Additional parameters for the specific removal method.

Returns:

Signal with artifacts removed.

Return type:

numpy.ndarray

vitalDSP.signal_quality_assessment.artifact_detection_removal.adaptive_threshold_artifact_detection(signal, window_size=100, std_factor=2.0)[source]

Detect artifacts adaptively by comparing each segment’s standard deviation to a threshold.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • window_size (int, optional (default=100)) – The size of the window for local analysis.

  • std_factor (float, optional (default=2.0)) – Factor of the standard deviation above which points are considered artifacts.

Returns:

artifact_indices – Indices of the detected artifacts.

Return type:

numpy.ndarray

Examples

>>> signal = np.random.normal(size=1000)
>>> signal[500:510] = 10  # Inject an artifact
>>> artifacts = adaptive_threshold_artifact_detection(signal, window_size=50, std_factor=2.0)
>>> print(artifacts)
vitalDSP.signal_quality_assessment.artifact_detection_removal.iterative_artifact_removal(signal, max_iterations=5, threshold=0.5)[source]

Iteratively remove artifacts by applying a threshold-based removal and refining the signal.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • max_iterations (int, optional (default=5)) – The maximum number of iterations to perform.

  • threshold (float, optional (default=0.5)) – The threshold for detecting artifacts.

Returns:

cleaned_signal – The signal with artifacts removed after iterative refinement.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 100, 5, 6, 7])
>>> cleaned_signal = iterative_artifact_removal(signal, max_iterations=3, threshold=0.6)
>>> print(cleaned_signal)
vitalDSP.signal_quality_assessment.artifact_detection_removal.kurtosis_artifact_detection(signal, kurt_threshold=3.0)[source]

Detect artifacts based on kurtosis, which measures the “tailedness” of the signal distribution.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • kurt_threshold (float, optional (default=3.0)) – The kurtosis threshold for artifact detection.

Returns:

artifact_indices – Indices of the detected artifacts.

Return type:

numpy.ndarray

Examples

>>> signal = np.random.normal(size=100)
>>> signal[50] = 10  # Inject an artifact
>>> artifacts = kurtosis_artifact_detection(signal, kurt_threshold=5.0)
>>> print(artifacts)
vitalDSP.signal_quality_assessment.artifact_detection_removal.median_filter_artifact_removal(signal, kernel_size=3)[source]

Remove artifacts using a median filter.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • kernel_size (int, optional (default=3)) – The size of the median filter kernel.

Returns:

cleaned_signal – The signal with artifacts removed.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 100, 5, 6, 7])
>>> cleaned_signal = median_filter_artifact_removal(signal, kernel_size=3)
>>> print(cleaned_signal)
vitalDSP.signal_quality_assessment.artifact_detection_removal.moving_average_artifact_removal(signal, window_size=5)[source]

Remove artifacts using a moving average filter.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • window_size (int, optional (default=5)) – The size of the moving average window.

Returns:

cleaned_signal – The signal with artifacts smoothed out.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 100, 5, 6, 7])
>>> cleaned_signal = moving_average_artifact_removal(signal, window_size=3)
>>> print(cleaned_signal)
vitalDSP.signal_quality_assessment.artifact_detection_removal.threshold_artifact_detection(signal, threshold=0.5)[source]

Detect artifacts in the signal based on amplitude thresholding.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • threshold (float, optional (default=0.5)) – The amplitude threshold for artifact detection.

Returns:

artifact_indices – Indices of the detected artifacts.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([0.1, 0.2, 1.0, 0.5, 0.4, 2.0])
>>> artifacts = threshold_artifact_detection(signal, threshold=0.6)
>>> print(artifacts)
vitalDSP.signal_quality_assessment.artifact_detection_removal.wavelet_artifact_removal(signal, wavelet_func, level=3)[source]

Remove artifacts from the signal using wavelet decomposition.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • wavelet_func (callable) – The wavelet function to use for decomposition.

  • level (int, optional (default=3)) – The decomposition level.

Returns:

cleaned_signal – The signal with artifacts removed.

Return type:

numpy.ndarray

Examples

>>> def haar_wavelet(x):
...     return np.array([1/np.sqrt(2), 1/np.sqrt(2)])  # Simple Haar wavelet example
>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> signal[200:300] = 2  # Inject an artifact
>>> cleaned_signal = wavelet_artifact_removal(signal, haar_wavelet, level=3)
>>> print(cleaned_signal)
vitalDSP.signal_quality_assessment.artifact_detection_removal.z_score_artifact_detection(signal, z_threshold=3.0)[source]

Detect artifacts based on Z-score analysis, which identifies points that deviate significantly from the mean.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • z_threshold (float, optional (default=3.0)) – The Z-score threshold for detecting artifacts.

Returns:

artifact_indices – Indices of the detected artifacts.

Return type:

numpy.ndarray

Examples

>>> signal = np.random.normal(size=100)
>>> signal[50] = 10  # Inject an artifact
>>> artifacts = z_score_artifact_detection(signal)
>>> print(artifacts)

Blind Source Separation

Methods for separating mixed signals into their original, independent sources without prior knowledge of the mixing process, often used in EEG and ECG analysis.

Signal Quality Assessment 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

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.blind_source_separation import BlindSourceSeparation
>>> signal = np.random.randn(1000)
>>> processor = BlindSourceSeparation(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.signal_quality_assessment.blind_source_separation.center_signal(signal)[source]

Center the signal by subtracting the mean.

Parameters:

signal (numpy.ndarray) – The input signal matrix, where each row is a different signal.

Returns:

  • centered_signal (numpy.ndarray) – The centered signal matrix.

  • mean_signal (numpy.ndarray) – The mean of the original signal.

Examples

>>> signal = np.array([[1, 2, 3], [4, 5, 6]])
>>> centered_signal, mean_signal = center_signal(signal)
>>> print(centered_signal)
vitalDSP.signal_quality_assessment.blind_source_separation.create_synthetic_components(signal, n_components=3, method='derivatives')[source]

Create synthetic signal components from a 1D signal for ICA processing.

When only a single signal channel is available, this function generates additional synthetic components to enable blind source separation techniques like ICA and PCA. This is particularly useful for physiological signals where we want to separate artifacts from the underlying signal.

Parameters:
  • signal (numpy.ndarray) – The 1D input signal

  • n_components (int, optional (default=3)) – Number of synthetic components to generate (including original) Minimum is 2, recommended 3-5

  • method (str, optional (default='derivatives')) – Method for creating synthetic components: - ‘derivatives’: Uses signal derivatives and delayed versions - ‘wavelet’: Uses wavelet decomposition at different scales - ‘frequency’: Uses bandpass filtered versions

Returns:

synthetic_signals – Matrix of shape (n_components, len(signal)) with synthetic components

Return type:

numpy.ndarray

Notes

The synthetic components are designed to capture different aspects of the signal: - Original signal - First derivative (captures rapid changes, useful for detecting spikes) - Delayed version (captures temporal patterns) - Second derivative (captures acceleration, useful for motion artifacts) - Smoothed version (captures baseline trends)

Examples

>>> import numpy as np
>>> signal = np.sin(2*np.pi*1*np.linspace(0,1,1000)) + 0.1*np.random.randn(1000)
>>> synthetic = create_synthetic_components(signal, n_components=3)
>>> print(synthetic.shape)  # (3, 1000)
vitalDSP.signal_quality_assessment.blind_source_separation.ica_artifact_removal(signals, max_iter=1000, tol=1e-05, auto_synthetic=True, n_components=3)[source]

Perform ICA to separate sources and remove artifacts.

This enhanced version automatically handles both multi-channel and single-channel (1D) signals. For 1D signals, it creates synthetic components to enable ICA.

Parameters:
  • signals (numpy.ndarray) – The mixed signals. Can be: - 1D array: Single signal (will auto-generate synthetic components) - 2D array: Multiple signals, where each row is a different signal

  • max_iter (int, optional (default=1000)) – The maximum number of iterations for the ICA algorithm.

  • tol (float, optional (default=1e-5)) – Tolerance for the convergence of the algorithm.

  • auto_synthetic (bool, optional (default=True)) – If True and input is 1D, automatically create synthetic components

  • n_components (int, optional (default=3)) – Number of synthetic components to create for 1D signals Only used when auto_synthetic=True

Returns:

separated_signals – The matrix of separated signals. If input was 1D, returns the first (cleaned) component.

Return type:

numpy.ndarray

Raises:

ValueError – If signals contain NaN values or have insufficient dimensionality

Examples

>>> # Example 1: Multi-channel signals
>>> signals = np.array([[1, 2, 3], [4, 5, 6]])
>>> separated = ica_artifact_removal(signals)
>>> print(separated.shape)  # (2, 3)
>>>
>>> # Example 2: Single channel (1D) signal - auto synthetic
>>> signal_1d = np.sin(2*np.pi*np.linspace(0,10,1000)) + 0.1*np.random.randn(1000)
>>> cleaned = ica_artifact_removal(signal_1d)
>>> print(cleaned.shape)  # (1000,) - returns cleaned 1D signal
>>>
>>> # Example 3: Single channel with custom n_components
>>> cleaned = ica_artifact_removal(signal_1d, n_components=5)
>>> print(cleaned.shape)  # (1000,)
vitalDSP.signal_quality_assessment.blind_source_separation.jade_ica(signals, max_iter=1000, tol=1e-05)[source]

Perform Joint Approximate Diagonalization of Eigenmatrices (JADE) for ICA.

Parameters:
  • signals (numpy.ndarray) – The mixed signals matrix, where each row is a different signal.

  • max_iter (int, optional (default=1000)) – The maximum number of iterations for the ICA algorithm.

  • tol (float, optional (default=1e-5)) – Tolerance for the convergence of the algorithm.

Returns:

separated_signals – The matrix of separated signals.

Return type:

numpy.ndarray

Examples

>>> # Input must be square matrix
>>> signals = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> separated_signals = jade_ica(signals)
>>> print(separated_signals)
vitalDSP.signal_quality_assessment.blind_source_separation.pca_artifact_removal(signals, n_components=None)[source]

Perform PCA to reduce dimensionality and remove artifacts.

Parameters:
  • signals (numpy.ndarray) – The mixed signals matrix, where each row is a different signal.

  • n_components (int, optional (default=None)) – Number of components to keep. If None, all components are kept.

Returns:

reduced_signals – The matrix of reduced signals.

Return type:

numpy.ndarray

Examples

>>> signals = np.array([[1, 2, 3], [4, 5, 6]])
>>> reduced_signals = pca_artifact_removal(signals, n_components=1)
>>> print(reduced_signals)
vitalDSP.signal_quality_assessment.blind_source_separation.whiten_signal(signal)[source]

Whiten the signal (decorrelate and scale to unit variance).

Parameters:

signal (numpy.ndarray) – The input centered signal matrix.

Returns:

  • whitened_signal (numpy.ndarray) – The whitened signal matrix.

  • whitening_matrix (numpy.ndarray) – The matrix used to whiten the signal.

Examples

>>> signal = np.array([[1, 2, 3], [4, 5, 6]])
>>> whitened_signal, whitening_matrix = whiten_signal(signal)
>>> print(whitened_signal)

Multi-Modal Artifact Detection

Techniques for detecting artifacts across multiple modalities, ensuring that combined signals are free from noise and other distortions.

Signal Quality Assessment 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 - Pattern and anomaly detection

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.multi_modal_artifact_detection import MultiModalArtifactDetection
>>> signal = np.random.randn(1000)
>>> processor = MultiModalArtifactDetection(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.signal_quality_assessment.multi_modal_artifact_detection.correlation_based_artifact_detection(signals, threshold=0.5)[source]

Detect artifacts by analyzing the correlation between multiple signals.

Parameters:
  • signals (list of numpy.ndarray) – List of signals to analyze for artifacts.

  • threshold (float, optional (default=0.5)) – The correlation threshold below which points are considered artifacts.

Returns:

artifact_indices – Indices of the detected artifacts across all signals.

Return type:

numpy.ndarray

Examples

>>> signal1 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> signal2 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01) + 0.5)
>>> artifacts = correlation_based_artifact_detection([signal1, signal2], threshold=0.7)
>>> print(artifacts)
vitalDSP.signal_quality_assessment.multi_modal_artifact_detection.energy_ratio_artifact_detection(signals, window_size=100, threshold=0.5)[source]

Detect artifacts by analyzing the energy ratio between multiple signals. This version doesn’t involve mutual information, but checks for energy ratios.

Parameters:
  • signals (list of numpy.ndarray) – List of signals to analyze for artifacts.

  • window_size (int, optional (default=100)) – The size of the window for local analysis.

  • threshold (float, optional (default=0.5)) – The energy ratio threshold below which points are considered artifacts.

Returns:

artifact_indices – Indices of the detected artifacts across all signals.

Return type:

numpy.ndarray

Examples

>>> signal1 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> signal2 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01) + 0.5)
>>> artifacts = energy_ratio_artifact_detection([signal1, signal2], window_size=50, threshold=0.6)
>>> print(artifacts)
vitalDSP.signal_quality_assessment.multi_modal_artifact_detection.mutual_information_artifact_detection(signals, num_bins=10, threshold=0.1)[source]

Detect artifacts using mutual information between multiple signals.

Parameters:
  • signals (list of numpy.ndarray) – List of signals to analyze for artifacts.

  • num_bins (int, optional (default=10)) – Number of bins to use for histogram estimation in mutual information.

  • threshold (float, optional (default=0.1)) – The mutual information threshold below which points are considered artifacts.

Returns:

artifact_indices – Indices of the detected artifacts across all signals.

Return type:

numpy.ndarray

Examples

>>> signal1 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> signal2 = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01) + 0.5)
>>> artifacts = mutual_information_artifact_detection([signal1, signal2], threshold=0.05)
>>> print(artifacts)

SNR Computation

Functions for computing the Signal-to-Noise Ratio (SNR) of signals, which is a critical metric in assessing the quality of biomedical signals.

Signal Quality Assessment 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

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.snr_computation import SnrComputation
>>> signal = np.random.randn(1000)
>>> processor = SnrComputation(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.signal_quality_assessment.snr_computation.crest_factor(signal)[source]

Calculate the crest factor of the signal, which is the ratio of the peak amplitude to the RMS value.

Parameters:

signal (numpy.ndarray) – The input signal.

Returns:

crest_factor – The crest factor of the signal.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> cf = crest_factor(signal)
>>> print(cf)
vitalDSP.signal_quality_assessment.snr_computation.harmonic_distortion(signal, fundamental_freq, sampling_rate, harmonics=5)[source]

Calculate the total harmonic distortion (THD) of the signal.

Parameters:
  • signal (numpy.ndarray) – The input signal.

  • fundamental_freq (float) – The fundamental frequency of the signal.

  • sampling_rate (float) – The sampling rate of the signal.

  • harmonics (int, optional (default=5)) – The number of harmonics to include in the THD calculation.

Returns:

thd – The total harmonic distortion as a percentage.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 50 * np.arange(0, 1, 1/1000))
>>> thd = harmonic_distortion(signal, fundamental_freq=50, sampling_rate=1000)
>>> print(thd)
vitalDSP.signal_quality_assessment.snr_computation.signal_to_noise_and_distortion_ratio(signal, noise)[source]

Calculate the Signal-to-Noise and Distortion Ratio (SINAD).

Parameters:
  • signal (numpy.ndarray) – The original clean signal.

  • noise (numpy.ndarray) – The noise and distortion components of the signal.

Returns:

sinad – The SINAD in dB.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> noise = 0.1 * np.random.normal(size=signal.shape)
>>> sinad = signal_to_noise_and_distortion_ratio(signal, noise)
>>> print(sinad)
vitalDSP.signal_quality_assessment.snr_computation.signal_to_noise_and_interference_ratio(signal, interference)[source]

Calculate the Signal-to-Noise and Interference Ratio (SNIR).

Parameters:
Returns:

snir – The SNIR in dB.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> interference = 0.1 * np.random.normal(size=signal.shape)
>>> snir = signal_to_noise_and_interference_ratio(signal, interference)
>>> print(snir)
vitalDSP.signal_quality_assessment.snr_computation.snr_mean_square(signal, noise)[source]

Calculate the SNR using the mean square of the signal and noise.

Parameters:
Returns:

snr – The SNR in dB.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> noise = 0.1 * np.random.normal(size=signal.shape)
>>> snr = snr_mean_square(signal, noise)
>>> print(snr)
vitalDSP.signal_quality_assessment.snr_computation.snr_peak_to_peak(signal, noise)[source]

Calculate the SNR using the peak-to-peak amplitude method.

Parameters:
Returns:

snr – The SNR in dB.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> noise = 0.1 * np.random.normal(size=signal.shape)
>>> snr = snr_peak_to_peak(signal, noise)
>>> print(snr)
vitalDSP.signal_quality_assessment.snr_computation.snr_power_ratio(signal, noise)[source]

Calculate the SNR using the power ratio method.

Parameters:
Returns:

snr – The SNR in dB.

Return type:

float

Examples

>>> signal = np.sin(2 * np.pi * 0.2 * np.arange(0, 10, 0.01))
>>> noise = 0.1 * np.random.normal(size=signal.shape)
>>> snr = snr_power_ratio(signal, noise)
>>> print(snr)

Signal Quality Index

This module provides methods to calculate various signal quality indices (SQI), which help in assessing the reliability and usability of the recorded signals.

Signal Quality Assessment 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 validation and error handling

Examples:

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

Bases: object

A class to compute various Signal Quality Index (SQI) metrics for assessing the quality of vital signals.

This class includes methods to evaluate signal quality based on different characteristics such as amplitude variability, baseline wander, zero-crossing consistency, waveform similarity, entropy, and more. These metrics are useful in ensuring that physiological signals like ECG, PPG, EEG, and respiratory signals are of high quality and reliable for further analysis.

amplitude_variability_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the amplitude variability SQI over segments of the signal.

Parameters:
  • window_size (int) – The size of each segment to compute the SQI.

  • step_size (int) – The step size to move the window for each segment.

  • threshold (float or tuple, optional) – The threshold to determine normal and abnormal segments.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

  • aggregate (bool, optional) – If True (default), returns the mean SQI value as a single float. If False, returns detailed tuple (sqi_values, normal_segments, abnormal_segments).

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments).

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5])
>>> sqi = SignalQualityIndex(signal)
>>> # Get single aggregated score (default)
>>> quality_score = sqi.amplitude_variability_sqi(window_size=5, step_size=2)
>>> # Get detailed results
>>> sqi_values, normal_segments, abnormal_segments = sqi.amplitude_variability_sqi(
...     window_size=5, step_size=2, threshold=0.8, aggregate=False)
baseline_wander_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', moving_avg_window=50, aggregate=True)[source]

Compute the baseline wander SQI.

This metric evaluates the amount of baseline wander in the signal, which is unwanted low-frequency noise that can distort the true signal. Baseline wander is particularly important in ECG and PPG signals.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

  • moving_avg_window (int, optional) – Size of the window for calculating the moving average. Default is 50.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.baseline_wander_sqi(window_size=3, step_size=1, threshold=0.8)
eeg_band_power_sqi(band_power, window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the EEG band power SQI.

This metric assesses the consistency of EEG band power, which is important for ensuring signal quality. Stable band power indicates a high-quality EEG signal.

Parameters:
  • band_power (numpy.ndarray) – Array of band power values for EEG.

  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> band_power = np.array([10, 12, 11, 13, 12])
>>> sqi = SignalQualityIndex(band_power)
>>> sqi_values, normal_segments, abnormal_segments = sqi.eeg_band_power_sqi(band_power, window_size=3, step_size=1, threshold=0.8)
energy_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the energy SQI.

This metric computes the energy of the signal over a segment, which can be an indicator of the signal’s strength or activity.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.energy_sqi(window_size=3, step_size=1, threshold=0.8)
heart_rate_variability_sqi(rr_intervals, window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the heart rate variability (HRV) SQI.

This metric assesses the variability in RR intervals of ECG, which should be within a certain range for a healthy signal. Abnormal HRV can indicate issues with heart health or signal quality.

Parameters:
  • rr_intervals (numpy.ndarray) – Array of RR intervals.

  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> rr_intervals = np.array([0.8, 0.9, 1.0, 0.9, 0.8])
>>> sqi = SignalQualityIndex(rr_intervals)
>>> sqi_values, normal_segments, abnormal_segments = sqi.heart_rate_variability_sqi(rr_intervals, window_size=3, step_size=1, threshold=0.8)
kurtosis_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the kurtosis SQI.

This metric measures the “tailedness” of the signal distribution. High kurtosis values indicate the presence of outliers or sharp peaks in the signal.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.kurtosis_sqi(window_size=3, step_size=1, threshold=0.8)
peak_to_peak_amplitude_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the peak-to-peak amplitude SQI.

This metric assesses the peak-to-peak amplitude of the signal, which is the difference between the maximum and minimum values within a segment.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.peak_to_peak_amplitude_sqi(window_size=3, step_size=1, threshold=0.8)
ppg_signal_quality_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the PPG signal quality SQI.

This metric evaluates the overall quality of PPG signals based on amplitude variability and baseline wander. High-quality PPG signals should have minimal noise and stable amplitude.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 1.1, 0.9, 1, 1.2, 0.8, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.ppg_signal_quality_sqi(window_size=3, step_size=1, threshold=0.8)
respiratory_signal_quality_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the respiratory signal quality SQI.

This metric evaluates the quality of respiratory signals, considering factors like consistency in breathing cycles and stability of the amplitude.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> resp_signal = np.array([1, 1.1, 1.0, 1.1, 1.0])
>>> sqi = SignalQualityIndex(resp_signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.respiratory_signal_quality_sqi(window_size=3, step_size=1, threshold=0.8)
signal_entropy_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the signal entropy SQI.

This metric measures the entropy of the signal, which indicates the complexity or predictability of the signal. Lower entropy generally indicates a more regular and stable signal, while higher entropy suggests more randomness.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 1, 1, 1, 1, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.signal_entropy_sqi(window_size=3, step_size=1, threshold=0.8)
skewness_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the skewness SQI.

This metric assesses the asymmetry of the signal distribution, where a high skewness value indicates that the signal is not symmetrically distributed.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.skewness_sqi(window_size=3, step_size=1, threshold=0.8)
snr_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the Signal-to-Noise Ratio (SNR) SQI.

This metric measures the ratio of the signal power to the noise power, which is an important metric for evaluating signal quality.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.snr_sqi(window_size=3, step_size=1, threshold=0.8)
waveform_similarity_sqi(window_size, step_size, reference_waveform, threshold=None, threshold_type='below', scale='zscore', similarity_method='correlation', aggregate=True)[source]

Compute the waveform similarity SQI using various similarity metrics.

This metric compares the similarity between consecutive waveforms in the signal. High similarity indicates that the signal is stable and free from significant artifacts.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • reference_waveform (numpy.ndarray) – A reference waveform to compare against.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

  • similarity_method (str, optional) – The method to use for similarity calculation (‘correlation’, ‘custom’). Default is ‘correlation’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([1, 2, 3, 2, 1])
>>> reference = np.array([1, 2, 3, 2, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.waveform_similarity_sqi(
...     window_size=3, step_size=1, reference_waveform=reference, threshold=0.8)
zero_crossing_sqi(window_size, step_size, threshold=None, threshold_type='below', scale='zscore', aggregate=True)[source]

Compute the zero-crossing SQI.

This metric assesses the number of zero crossings in the signal, which should be consistent in high-quality signals. Irregular zero crossings can indicate noise or instability in the signal.

Parameters:
  • window_size (int) – The size of each segment.

  • step_size (int) – The step size to slide the window.

  • threshold (float or tuple, optional) – Threshold to classify a segment as normal or abnormal.

  • threshold_type (str, optional) – The type of thresholding (‘below’, ‘above’, ‘range’). Default is ‘below’.

  • scale (str, optional) – The scaling method to apply to SQI values (‘zscore’, ‘iqr’, ‘minmax’). Default is ‘zscore’.

Returns:

If aggregate=True: Mean SQI value as float. If aggregate=False: Tuple of (sqi_values, normal_segments, abnormal_segments) where sqi_values is array of SQI values for each segment, normal_segments and abnormal_segments are lists of (start, end) indices.

Return type:

float or tuple

Examples

>>> signal = np.array([-1, 1, -1, 1, -1, 1])
>>> sqi = SignalQualityIndex(signal)
>>> sqi_values, normal_segments, abnormal_segments = sqi.zero_crossing_sqi(window_size=3, step_size=1, threshold=0.8)

Signal Quality

Comprehensive tools for assessing and enhancing the overall quality of signals. This includes both objective measures and methods for improving signal integrity.

Signal Quality Assessment Module for Physiological Signal Processing

This module provides comprehensive signal quality assessment capabilities for physiological signals including ECG, PPG, and other vital signs. It implements various quality metrics such as Signal-to-Noise Ratio (SNR), Peak Signal-to-Noise Ratio (PSNR), and Mean Square Error (MSE) to evaluate signal quality and the impact of noise or processing artifacts.

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

Key Features: - Signal-to-Noise Ratio (SNR) computation - Peak Signal-to-Noise Ratio (PSNR) calculation - Mean Square Error (MSE) assessment - Noise-based SNR estimation - Comprehensive quality metrics for signal evaluation

Examples:

Basic signal quality assessment:
>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.signal_quality import SignalQuality
>>> original_signal = np.sin(np.linspace(0, 10, 1000))
>>> noise = np.random.normal(0, 0.1, 1000)
>>> noisy_signal = original_signal + noise
>>> sq = SignalQuality(original_signal, noisy_signal)
>>> print(f"SNR: {sq.snr():.2f} dB")
>>> print(f"PSNR: {sq.psnr():.2f} dB")
>>> print(f"MSE: {sq.mse():.6f}")
Quality assessment with different noise levels:
>>> high_noise = np.random.normal(0, 0.5, 1000)
>>> very_noisy_signal = original_signal + high_noise
>>> sq_high_noise = SignalQuality(original_signal, very_noisy_signal)
>>> print(f"High noise SNR: {sq_high_noise.snr():.2f} dB")
Using noise signal directly:
>>> sq_noise = SignalQuality(original_signal)
>>> snr_from_noise = sq_noise.snr_of_noise(noise)
>>> print(f"SNR from noise: {snr_from_noise:.2f} dB")
class vitalDSP.signal_quality_assessment.signal_quality.SignalQuality(original_signal, processed_signal=None)[source]

Bases: object

A class to assess the quality of signals using various metrics.

This class provides methods to compute commonly used signal quality metrics such as Signal-to-Noise Ratio (SNR), Peak Signal-to-Noise Ratio (PSNR), and Mean Square Error (MSE). It can be used to evaluate the impact of noise or other processing on the original signal.

snr : function

Computes the Signal-to-Noise Ratio.

psnr : function

Computes the Peak Signal-to-Noise Ratio.

mse : function

Computes the Mean Square Error between the original and processed signals.

snr_of_noise : function

Computes the Signal-to-Noise Ratio given a noise signal.

Examples

>>> import numpy as np
>>> from vitalDSP.signal_quality_assessment.signal_quality import SignalQuality
>>>
>>> # Example 1: Basic signal quality assessment
>>> original_signal = np.sin(np.linspace(0, 10, 1000))
>>> noise = np.random.normal(0, 0.1, 1000)
>>> noisy_signal = original_signal + noise
>>> sq = SignalQuality(original_signal, noisy_signal)
>>> print(f"SNR: {sq.snr():.2f} dB")
>>> print(f"PSNR: {sq.psnr():.2f} dB")
>>> print(f"MSE: {sq.mse():.6f}")
>>>
>>> # Example 2: Quality assessment with different noise levels
>>> high_noise = np.random.normal(0, 0.5, 1000)
>>> very_noisy_signal = original_signal + high_noise
>>> sq_high_noise = SignalQuality(original_signal, very_noisy_signal)
>>> print(f"High noise SNR: {sq_high_noise.snr():.2f} dB")
>>>
>>> # Example 3: Using noise signal directly
>>> sq_noise = SignalQuality(original_signal)
>>> snr_from_noise = sq_noise.snr_of_noise(noise)
>>> print(f"SNR from noise: {snr_from_noise:.2f} dB")
mse()[source]

Compute the Mean Square Error (MSE) between the original and processed signals.

MSE measures the average squared difference between the original and processed signals. It is commonly used to quantify the error introduced by noise or signal processing.

Returns:

mse_value – The MSE value.

Return type:

float

Raises:

ValueError – If processed_signal is not provided during initialization.

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> noise = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
>>> noisy_signal = signal + noise
>>> sq = SignalQuality(signal, noisy_signal)
>>> print(sq.mse())
0.010000000000000002
psnr()[source]

Compute the Peak Signal-to-Noise Ratio (PSNR) of the signal.

PSNR compares the maximum possible signal power to the noise power. It is commonly used in image and signal processing to assess the quality of signal reconstruction or compression techniques.

Returns:

psnr_value – The PSNR value in decibels (dB).

Return type:

float

Raises:

ValueError – If processed_signal is not provided during initialization.

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> noise = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
>>> noisy_signal = signal + noise
>>> sq = SignalQuality(signal, noisy_signal)
>>> print(sq.psnr())
26.020599913279625
snr()[source]

Compute the Signal-to-Noise Ratio (SNR) of the signal.

SNR is a measure of signal quality that compares the level of the desired signal to the level of background noise. A higher SNR indicates a cleaner signal with less noise.

Returns:

snr_value – The SNR value in decibels (dB).

Return type:

float

Raises:

ValueError – If processed_signal is not provided during initialization.

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> noise = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
>>> noisy_signal = signal + noise
>>> sq = SignalQuality(signal, noisy_signal)
>>> print(sq.snr())
14.154543666201898
snr_of_noise(noise_signal)[source]

Compute the Signal-to-Noise Ratio (SNR) given a noise signal.

This method calculates the SNR by comparing the power of the original signal to the power of the provided noise signal, without needing a processed signal.

Parameters:

noise_signal (numpy.ndarray) – The noise signal.

Returns:

snr_value – The SNR value in decibels (dB).

Return type:

float

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> noise = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
>>> sq = SignalQuality(signal)
>>> print(sq.snr_of_noise(noise))
20.0