Utils

This section covers various utility functions and modules provided by the VitalDSP library. These utilities are essential for performing a wide range of operations, from data normalization to the synthesis of signals, and supporting the core signal processing tasks.

Overview

The utils module provides comprehensive utility functions for:

  • Peak Detection: Advanced algorithms for identifying peaks in physiological signals

  • Data Synthesis: Generation of synthetic physiological signals for testing and development

  • Normalization: Various normalization and scaling techniques

  • Interpolation: Data interpolation and gap filling methods

  • Wavelets: Mother wavelet functions for wavelet transforms

  • Machine Learning: Loss functions, attention weights, and convolutional kernels

Peak Detection

Peak Detection

Identify peaks in the signal, which are often indicative of significant events or features, such as heartbeats or respiratory cycles.

Peak Detection Module for Physiological Signal Processing

This module provides comprehensive peak detection capabilities for various physiological signals including ECG, PPG, EEG, respiratory, and arterial blood pressure (ABP) signals. It implements multiple detection algorithms optimized for different signal types and characteristics.

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

Key Features: - Multiple peak detection algorithms - Signal-specific optimizations (ECG R-peaks, PPG systolic peaks) - Advanced filtering and preprocessing integration - Scalable threshold-based detection - Derivative-based detection methods - Wavelet and bandpass filtering for EEG

Examples:

Basic peak detection:
>>> import numpy as np
>>> from vitalDSP.utils.signal_processing.peak_detection import PeakDetection
>>> signal = np.sin(np.linspace(0, 10, 1000)) + np.random.normal(0, 0.1, 1000)
>>> detector = PeakDetection(signal, method="threshold", height=0.5)
>>> peaks = detector.detect_peaks()
>>> print(f"Detected {len(peaks)} peaks")
ECG R-peak detection:
>>> ecg_detector = PeakDetection(ecg_signal, method="ecg_r_peak")
>>> r_peaks = ecg_detector.detect_peaks()
>>> print(f"R-peaks: {len(r_peaks)}")
PPG systolic peak detection:
>>> ppg_detector = PeakDetection(ppg_signal, method="ppg_systolic_peaks")
>>> systolic_peaks = ppg_detector.detect_peaks()
>>> print(f"Systolic peaks: {len(systolic_peaks)}")
class vitalDSP.utils.signal_processing.peak_detection.PeakDetection(signal, method='threshold', **kwargs)[source]

Bases: object

A class to detect peaks in various physiological signals like ECG, PPG, EEG, respiratory, and arterial blood pressure (ABP) signals.

detect_peaks : function

Detects the peaks in the signal using the selected method.

detect_peaks()[source]

Detect peaks in the signal based on the selected method.

Returns:

peaks – The indices of the detected peaks.

Return type:

numpy.ndarray

Raises:

ValueError – If an invalid method is selected.

Examples

>>> signal = np.array([1, 2, 3, 4, 5, 4, 3, 2, 1])
>>> detector = PeakDetection(signal, method="threshold", threshold=4)
>>> peaks = detector.detect_peaks()
>>> print(peaks)

Data Synthesis

Synthesize Data

Methods for generating synthetic data, which can be used for training models, testing algorithms, or simulating signal processing scenarios.

Utility Functions 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 - Interactive visualization capabilities

Examples:

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

Bases: object

A class that provides access to all signal synthesis functions. This class wraps the individual functions for easier access and organization.

static generate_ecg_signal(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, qrs_width=0.08, t_wave_amplitude=0.3, p_wave_amplitude=0.25, randomize=False, display=False)[source]

Generate a synthetic ECG signal.

static generate_noisy_signal(base_signal, noise_level=0.1)[source]

Add Gaussian noise to a base signal.

static generate_ppg_data(duration=50, fs=1000)[source]

Generate synthetic PPG data for testing.

static generate_resp_signal(sampling_rate, duration, frequency=0.2, amplitude=0.5)[source]

Generate a synthetic respiratory signal.

static generate_sinusoidal(frequency, sampling_rate, duration, amplitude=1.0, phase=0.0)[source]

Generate a sinusoidal wave.

static generate_square_wave(frequency, sampling_rate, duration, amplitude=1.0, duty_cycle=0.5)[source]

Generate a square wave.

static generate_synthetic_ppg(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal.

static generate_synthetic_ppg_reversed(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal with reversed parameters.

vitalDSP.utils.data_processing.synthesize_data.generate_ecg_signal(sfecg=256, N=None, duration=30, Anoise=0.0, hrmean=60, hrstd=1.0, lfhfratio=0.5, sfint=512, ti=None, ai=None, bi=None)[source]

Generate a synthetic ECG signal using the dynamical model from McSharry et al.

Parameters:
  • sfecg (int, optional) – ECG sampling frequency in Hz (default is 256).

  • N (int, optional) – Approximate number of heartbeats (default is 60).

  • duration (int, optional) – Approximate number of seconds (default is 30).

  • Anoise (float, optional) – Amplitude of additive uniformly distributed measurement noise (default is 0).

  • hrmean (float, optional) – Mean heart rate in beats per minute (default is 60).

  • hrstd (float, optional) – Standard deviation of heart rate in beats per minute (default is 1).

  • lfhfratio (float, optional) – Low frequency to high frequency ratio (default is 0.5).

  • sfint (int, optional) – Internal sampling frequency in Hz (default is 512).

  • ti (list, optional) – Angles of extrema in degrees for PQRST (default is [-70, -15, 0, 15, 100]).

  • ai (list, optional) – Z-position of extrema for PQRST (default is [1.2, -5, 30, -7.5, 0.75]).

  • bi (list, optional) – Gaussian width of peaks for PQRST (default is [0.25, 0.1, 0.1, 0.1, 0.4]).

Returns:

  • s (ndarray) – Generated ECG signal.

  • ipeaks (ndarray) – Labels for PQRST peaks.

Examples

>>> signal = generate_ecg_signal(sfecg=256, N=256, Anoise=0.01, hrmean=70, sfint=512)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_noisy_signal(base_signal, noise_level=0.1)[source]

Add Gaussian noise to a base signal.

Parameters:
  • base_signal (numpy.ndarray) – The input signal to which noise will be added.

  • noise_level (float, optional (default=0.1)) – The standard deviation of the Gaussian noise.

Returns:

noisy_signal – The signal with added Gaussian noise.

Return type:

numpy.ndarray

Examples

>>> base_signal = generate_sinusoidal(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> noisy_signal = generate_noisy_signal(base_signal, noise_level=0.2)
>>> print(noisy_signal)
vitalDSP.utils.data_processing.synthesize_data.generate_resp_signal(sampling_rate, duration, frequency=0.2, amplitude=0.5)[source]

Generate a synthetic respiratory signal.

Parameters:
  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • frequency (float, optional (default=0.2)) – Frequency of the respiratory signal in Hz.

  • amplitude (float, optional (default=0.5)) – Amplitude of the respiratory signal.

Returns:

resp_signal – The generated synthetic respiratory signal.

Return type:

numpy.ndarray

Examples

>>> resp_signal = generate_resp_signal(sampling_rate=1000.0, duration=10.0)
>>> print(resp_signal)
vitalDSP.utils.data_processing.synthesize_data.generate_sinusoidal(frequency, sampling_rate, duration, amplitude=1.0, phase=0.0)[source]

Generate a sinusoidal wave.

Parameters:
  • frequency (float) – Frequency of the sinusoid in Hz.

  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • amplitude (float, optional (default=1.0)) – Amplitude of the sinusoid.

  • phase (float, optional (default=0.0)) – Phase shift of the sinusoid in radians.

Returns:

signal – The generated sinusoidal signal.

Return type:

numpy.ndarray

Examples

>>> signal = generate_sinusoidal(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_square_wave(frequency, sampling_rate, duration, amplitude=1.0, duty_cycle=0.5)[source]

Generate a square wave.

Parameters:
  • frequency (float) – Frequency of the square wave in Hz.

  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • amplitude (float, optional (default=1.0)) – Amplitude of the square wave.

  • duty_cycle (float, optional (default=0.5)) – Duty cycle of the square wave (fraction of one period in which the signal is high).

Returns:

signal – The generated square wave signal.

Return type:

numpy.ndarray

Examples

>>> signal = generate_square_wave(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_synthetic_ppg(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal with adjustable parameters.

Parameters:
  • duration (float, optional) – Duration of the signal in seconds (default is 10).

  • sampling_rate (int, optional) – Sampling rate in Hz (default is 1000).

  • heart_rate (float, optional) – Heart rate in beats per minute (default is 60).

  • noise_level (float, optional) – Standard deviation of the Gaussian noise to be added (default is 0.01).

  • diastolic_amplitude (float, optional) – Amplitude of the diastolic peak relative to the systolic peak (default is 0.8).

  • diastolic_width (float, optional) – Width of the diastolic peak (default is 0.15).

  • dicrotic_notch_depth (float, optional) – Depth of the dicrotic notch (default is 0.6).

  • dicrotic_notch_delay (float, optional) – Time delay for the diastolic peak (default is 0.2).

  • randomize (bool, optional) – If True, introduces randomness in the diastolic amplitude, width, and dicrotic notch depth (default is False).

  • display (bool, optional) – If True, displays the generated PPG signal (default is False).

Returns:

  • time (numpy.ndarray) – Array of time values.

  • ppg_signal (numpy.ndarray) – The generated synthetic PPG signal.

Example

>>> time, ppg_signal = generate_synthetic_ppg(duration=10, heart_rate=60, randomize=True, display=True)
vitalDSP.utils.data_processing.synthesize_data.generate_synthetic_ppg_reversed(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, display=False)[source]

Generate a synthetic PPG signal.

Parameters:
  • duration (float, optional) – Duration of the signal in seconds (default is 10).

  • sampling_rate (int, optional) – Sampling rate in Hz (default is 1000).

  • heart_rate (float, optional) – Heart rate in beats per minute (default is 60).

  • noise_level (float, optional) – Standard deviation of the Gaussian noise to be added (default is 0.01).

  • display (bool, optional) – If True, displays the generated PPG signal (default is False).

Returns:

  • time (numpy.ndarray) – Array of time values.

  • ppg_signal (numpy.ndarray) – The generated synthetic PPG signal.

Example

>>> time, ppg_signal = generate_synthetic_ppg(duration=10, heart_rate=60, display=True)
vitalDSP.utils.data_processing.synthesize_data.ordinary_differential_equation(t, x_equations, rr=None, sfint=None, ti=None, ai=None, bi=None)[source]
vitalDSP.utils.data_processing.synthesize_data.rrprocess(flo, fhi, flostd, fhistd, lfhfratio, hrmean, hrstd, sfrr, n)[source]

Normalization and Scaling

Normalization

Techniques and functions for normalizing data, ensuring that signals have consistent scales, which is essential for accurate analysis and model training.

Utility Functions 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_processing.normalization import Normalization
>>> signal = np.random.randn(1000)
>>> processor = Normalization(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.utils.signal_processing.normalization.min_max_normalization(signal, min_value=0, max_value=1)[source]

Normalize the signal using Min-Max scaling.

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

  • min_value (float, optional (default=0)) – The minimum value of the desired range.

  • max_value (float, optional (default=1)) – The maximum value of the desired range.

Returns:

normalized_signal – The Min-Max normalized signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> normalized_signal = min_max_normalization(signal, min_value=-1, max_value=1)
>>> print(normalized_signal)
[-1.  -0.5  0.   0.5  1. ]
vitalDSP.utils.signal_processing.normalization.z_score_normalization(signal)[source]

Normalize the signal using Z-score normalization.

Parameters:

signal (numpy.ndarray) – The input signal to be normalized.

Returns:

normalized_signal – The Z-score normalized signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> normalized_signal = z_score_normalization(signal)
>>> print(normalized_signal)
[-1.26491106 -0.63245553  0.          0.63245553  1.26491106]

Scaler

Functions for scaling data, which can include methods for both normalization and standardization to prepare signals for analysis or machine learning.

Utility Functions 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.signal_processing.scaler import Scaler
>>> signal = np.random.randn(1000)
>>> processor = Scaler(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.scaler.StandardScaler[source]

Bases: object

A custom implementation of the Standard Scaler, which standardizes signals by removing the mean and scaling to unit variance.

This class can be used to normalize signals before applying transformations like the Discrete Wavelet Transform (DWT).

mean_

The mean of the signal after fitting.

Type:

float or None

std_

The standard deviation of the signal after fitting.

Type:

float or None

fit(signal)[source]

Calculate mean and standard deviation for scaling.

transform(signal)[source]

Scale the signal using the mean and standard deviation.

fit_transform(signal)[source]

Fit to the data and then transform it.

fit(signal)[source]

Fit the scaler to the signal by calculating the mean and standard deviation.

Parameters:

signal (numpy.ndarray) – The input signal to be standardized.

Return type:

None

fit_transform(signal)[source]

Fit to the signal, then transform it.

This is a convenience method that combines fit and transform into a single step.

Parameters:

signal (numpy.ndarray) – The input signal to be fitted and transformed.

Returns:

scaled_signal – The standardized signal with zero mean and unit variance.

Return type:

numpy.ndarray

Examples

>>> scaler = StandardScaler()
>>> scaled_signal = scaler.fit_transform(np.array([1, 2, 3, 4, 5]))
>>> print(scaled_signal)
transform(signal)[source]

Transform the signal using the fitted scaler by removing the mean and scaling to unit variance.

Parameters:

signal (numpy.ndarray) – The input signal to be transformed.

Returns:

scaled_signal – The standardized signal with zero mean and unit variance.

Return type:

numpy.ndarray

Raises:

ValueError – If the scaler has not been fitted yet.

Examples

>>> scaler = StandardScaler()
>>> scaler.fit(np.array([1, 2, 3, 4, 5]))
>>> scaled_signal = scaler.transform(np.array([1, 2, 3, 4, 5]))
>>> print(scaled_signal)

Data Interpolation

Interpolations

Functions for interpolating and filling gaps in data, essential for handling missing values and irregular sampling.

Utility Functions 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

Examples:

Basic usage:
>>> import numpy as np
>>> from vitalDSP.signal_processing.interpolations import Interpolations
>>> signal = np.random.randn(1000)
>>> processor = Interpolations(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.utils.signal_processing.interpolations.backward_fill(intervals)[source]

Impute missing values by carrying backward the next valid RR interval.

Parameters:

intervals (np.array) – The array of RR intervals with NaN values.

Returns:

The array with missing values imputed using backward fill.

Return type:

np.array

Example

>>> backward_fill(np.array([0.8, np.nan, 0.82, np.nan, 0.85]))
vitalDSP.utils.signal_processing.interpolations.forward_fill(intervals)[source]

Impute missing values by carrying forward the last valid RR interval.

Parameters:

intervals (np.array) – The array of RR intervals with NaN values.

Returns:

The array with missing values imputed using forward fill.

Return type:

np.array

Example

>>> forward_fill(np.array([0.8, np.nan, 0.82, np.nan, 0.85]))
vitalDSP.utils.signal_processing.interpolations.linear_interpolation(intervals)[source]

Impute missing values using linear interpolation.

Parameters:

intervals (np.array) – The array of RR intervals with NaN values.

Returns:

The array with missing values imputed using linear interpolation.

Return type:

np.array

Example

>>> linear_interpolation(np.array([0.8, np.nan, 0.82, np.nan, 0.85]))
vitalDSP.utils.signal_processing.interpolations.mean_imputation(intervals)[source]

Impute missing values by replacing them with the mean of the valid RR intervals.

Parameters:

intervals (np.array) – The array of RR intervals with NaN values.

Returns:

The array with missing values imputed using the mean of valid intervals.

Return type:

np.array

Example

>>> mean_imputation(np.array([0.8, np.nan, 0.82, np.nan, 0.85]))
vitalDSP.utils.signal_processing.interpolations.median_imputation(intervals)[source]

Impute missing values by replacing them with the median of the valid RR intervals.

Parameters:

intervals (np.array) – The array of RR intervals with NaN values.

Returns:

The array with missing values imputed using the median of valid intervals.

Return type:

np.array

Example

>>> median_imputation(np.array([0.8, np.nan, 0.82, np.nan, 0.85]))
vitalDSP.utils.signal_processing.interpolations.rolling_mean_imputation(intervals, window=5)[source]

Impute missing values using the rolling mean of valid RR intervals.

Parameters:
  • intervals (np.array) – The array of RR intervals with NaN values.

  • window (int, optional) – The window size for the rolling mean. Defaults to 5.

Returns:

The array with missing values imputed using the rolling mean.

Return type:

np.array

Example

>>> rolling_mean_imputation(np.array([0.8, np.nan, 0.82, np.nan, 0.85]), window=3)
vitalDSP.utils.signal_processing.interpolations.spline_interpolation(intervals, order=3)[source]

Impute missing values using spline interpolation.

Parameters:
  • intervals (np.array) – The array of RR intervals with NaN values.

  • order (int, optional) – The order of the spline, defaults to 3 (cubic spline).

Returns:

The array with missing values imputed using spline interpolation.

Return type:

np.array

Example

>>> spline_interpolation(np.array([0.8, np.nan, 0.82, np.nan, 0.85]), order=3)

Wavelet Functions

Mother Wavelets

Functions related to mother wavelets, which are used as the basis for wavelet transforms, crucial for time-frequency analysis.

Utility Functions 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.signal_processing.mother_wavelets import MotherWavelets
>>> signal = np.random.randn(1000)
>>> processor = MotherWavelets(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.mother_wavelets.Wavelet[source]

Bases: object

A class for generating different types of mother wavelets based on their mathematical formulas.

Wavelets are used in various signal processing applications, particularly in analyzing non-stationary signals where both time and frequency localization is important. This class provides methods to generate common wavelets used in discrete wavelet transforms (DWT).

haar() numpy.ndarray[source]

Generates a Haar wavelet, best for detecting sudden changes in signals.

db(order=4) numpy.ndarray[source]

Generates a Daubechies wavelet, suitable for analyzing smooth signals with sharp discontinuities.

sym(order=4) numpy.ndarray[source]

Generates a Symlet wavelet, ideal for symmetric analysis and minimizing edge effects.

coif(order=1) numpy.ndarray[source]

Generates a Coiflet wavelet, providing near-symmetry and smoothness, ideal for subtle signal variations.

gauchy(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Gaussian wavelet, excellent for isolating features with a Gaussian shape in the time domain.

mexican_hat(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Mexican Hat wavelet, commonly used for detecting peaks and ridges.

morlet(sigma=1.0, N=6, f=1.0) numpy.ndarray[source]

Generates a Morlet wavelet, useful for time-frequency analysis.

meyer(N=6) numpy.ndarray[source]

Generates a Meyer wavelet, suitable for analyzing slowly varying signals without sharp edges.

biorthogonal(N=6, p=2, q=2) numpy.ndarray[source]

Generates a Biorthogonal wavelet, useful in image compression and providing exact reconstruction with linear phase.

reverse_biorthogonal(N=6, p=2, q=2) numpy.ndarray[source]

Generates a Reverse Biorthogonal wavelet, useful in de-noising applications.

complex_gaussian(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Complex Gaussian wavelet, applied in phase and frequency modulation.

shannon(N=6) numpy.ndarray[source]

Generates a Shannon wavelet, ideal for signals with sharp time-frequency localization.

cmor(sigma=1.0, N=6, f=1.0) numpy.ndarray[source]

Generates a Complex Morlet wavelet, used for time-frequency localization in non-stationary signals.

fbsp(N=6, m=5, s=0.5) numpy.ndarray[source]

Generates a Frequency B-Spline wavelet, useful for analyzing frequency-modulated signals.

mhat(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Modified Mexican Hat wavelet, applied in edge detection in images and other signals.

custom_wavelet(wavelet: numpy.ndarray) numpy.ndarray[source]

Use a custom wavelet provided by the user.

static biorthogonal(N=6, p=2, q=2)[source]

Generate a Biorthogonal wavelet.

Biorthogonal wavelets provide exact reconstruction with linear phase, making them useful in image compression (e.g., JPEG 2000).

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • p (int, optional) – The order of the B-spline used for the analysis filter (default is 2).

  • q (int, optional) – The order of the B-spline used for the synthesis filter (default is 2).

Returns:

wavelet – The Biorthogonal wavelet coefficients (analysis side).

Return type:

numpy.ndarray

Examples

>>> biorthogonal_wavelet = Wavelet.biorthogonal(N=6, p=2, q=2)
>>> print(biorthogonal_wavelet)
static cmor(sigma=1.0, N=6, f=1.0)[source]

Generate a Complex Morlet wavelet.

Complex Morlet wavelets are used for time-frequency localization, particularly in non-stationary signal analysis.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

  • f (float, optional) – The central frequency of the Complex Morlet wavelet (default is 1.0).

Returns:

wavelet – The Complex Morlet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> cmor_wavelet = Wavelet.cmor(sigma=1.0, N=6, f=1.0)
>>> print(cmor_wavelet)
static coif(order=1)[source]

Generate a Coiflet wavelet of a given order.

Coiflet wavelets are nearly symmetric and provide smooth waveforms, making them ideal for analyzing subtle variations in signals.

Parameters:

order (int, optional) – The order of the Coiflet wavelet (default is 1).

Returns:

wavelet_coeffs – The Coiflet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> coif_wavelet = Wavelet.coif(order=1)
>>> print(coif_wavelet)
static complex_gaussian(sigma=1.0, N=6)[source]

Generate a Complex Gaussian wavelet.

Complex Gaussian wavelets are applied in phase and frequency modulation, making them suitable for radar and communication signals.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Complex Gaussian wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> complex_gaussian_wavelet = Wavelet.complex_gaussian(sigma=1.0, N=6)
>>> print(complex_gaussian_wavelet)
static custom_wavelet(wavelet)[source]

Use a custom wavelet provided by the user.

This method allows the use of a custom wavelet defined by the user, which can be applied in specific or novel signal processing tasks.

Parameters:

wavelet (numpy.ndarray) – The custom wavelet coefficients provided by the user.

Returns:

wavelet – The custom wavelet.

Return type:

numpy.ndarray

Examples

>>> custom_wavelet = Wavelet.custom_wavelet(np.array([0.2, 0.5, 0.2]))
>>> print(custom_wavelet)
static db(order=4)[source]

Generate Daubechies wavelet low-pass and high-pass filter coefficients.

Returns the standard orthonormal Daubechies scaling (low-pass) and wavelet (high-pass) filter pair for the given vanishing-moment order. Known exact coefficients are used for orders 1-8; higher orders fall back to a symmetric approximation.

Parameters:

order (int, optional) – The order (number of vanishing moments) of the Daubechies wavelet (default is 4).

Returns:

  • low_pass (numpy.ndarray) – Scaling filter coefficients (real-valued).

  • high_pass (numpy.ndarray) – Wavelet filter coefficients (real-valued).

Examples

>>> lo, hi = Wavelet.db(order=4)
>>> print(lo)
static fbsp(N=6, m=5, s=0.5)[source]

Generate a Frequency B-Spline wavelet.

Frequency B-Spline wavelets are useful for analyzing frequency-modulated signals, often applied in audio signal processing.

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • m (int, optional) – The order of the B-spline (default is 5).

  • s (float, optional) – The bandwidth parameter (default is 0.5).

Returns:

wavelet – The Frequency B-Spline wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> fbsp_wavelet = Wavelet.fbsp(N=6, m=5, s=0.5)
>>> print(fbsp_wavelet)
static gauchy(sigma=1.0, N=6)[source]

Generate a Gaussian wavelet.

Gaussian wavelets are ideal for isolating specific features with a Gaussian shape in the time domain, such as spikes in EEG signals.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Gaussian wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> gauchy_wavelet = Wavelet.gauchy(sigma=1.0, N=6)
>>> print(gauchy_wavelet)
static haar()[source]

Generate a Haar wavelet.

The Haar wavelet is the simplest wavelet, best suited for detecting sudden changes in a signal, such as step functions or sharp transitions.

Returns:

wavelet – The Haar wavelet.

Return type:

numpy.ndarray

Examples

>>> haar_wavelet = Wavelet.haar()
>>> print(haar_wavelet)
[0.70710678 0.70710678]
static mexican_hat(sigma=1.0, N=6)[source]

Generate a Mexican Hat wavelet (also known as the Ricker wavelet).

The Mexican Hat wavelet is commonly used in detecting peaks and ridges in signals, particularly useful in EEG spike detection.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Mexican Hat wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> mexican_hat_wavelet = Wavelet.mexican_hat(sigma=1.0, N=6)
>>> print(mexican_hat_wavelet)
static meyer(N=6)[source]

Generate a Meyer wavelet.

Meyer wavelets are smooth and suitable for analyzing slowly varying signals without sharp edges.

Parameters:

N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Meyer wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> meyer_wavelet = Wavelet.meyer(N=6)
>>> print(meyer_wavelet)
static mhat(sigma=1.0, N=6)[source]

Generate a Modified Mexican Hat wavelet.

Modified Mexican Hat wavelets are applied in edge detection in images and other signals with sharp transitions.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Modified Mexican Hat wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> mhat_wavelet = Wavelet.mhat(sigma=1.0, N=6)
>>> print(mhat_wavelet)
static morlet(sigma=1.0, N=6, f=1.0)[source]

Generate a Morlet wavelet.

Morlet wavelets are particularly useful for time-frequency analysis and are frequently applied in EEG and seismic signal analysis.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

  • f (float, optional) – The central frequency of the Morlet wavelet (default is 1.0).

Returns:

wavelet – The Morlet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> morlet_wavelet = Wavelet.morlet(sigma=1.0, N=6, f=1.0)
>>> print(morlet_wavelet)
static reverse_biorthogonal(N=6, p=2, q=2)[source]

Generate a Reverse Biorthogonal wavelet.

Reverse Biorthogonal wavelets are the synthesis duals of biorthogonal wavelets, useful in de-noising applications.

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • p (int, optional) – The order of the B-spline (analysis side, default is 2).

  • q (int, optional) – The order of the B-spline (synthesis side, default is 2).

Returns:

wavelet – The Reverse Biorthogonal wavelet coefficients (synthesis side).

Return type:

numpy.ndarray

Examples

>>> reverse_biorthogonal_wavelet = Wavelet.reverse_biorthogonal(N=6, p=2, q=2)
>>> print(reverse_biorthogonal_wavelet)
static shannon(N=6)[source]

Generate a Shannon wavelet.

Shannon wavelets are ideal for signals with sharp time-frequency localization, such as short pulses.

Parameters:

N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Shannon wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> shannon_wavelet = Wavelet.shannon(N=6)
>>> print(shannon_wavelet)
static sym(order=4)[source]

Generate Symlet wavelet low-pass and high-pass filter coefficients.

Symlets are nearly symmetric modifications of the Daubechies wavelets. Known exact coefficients are used for orders 2-8; other orders fall back to the corresponding Daubechies filters.

Parameters:

order (int, optional) – The order of the Symlet wavelet (default is 4).

Returns:

  • low_pass (numpy.ndarray) – Scaling filter coefficients (real-valued).

  • high_pass (numpy.ndarray) – Wavelet filter coefficients (real-valued).

Examples

>>> lo, hi = Wavelet.sym(order=4)
>>> print(lo)

Machine Learning Utilities

Attention Weights

Functions and methods related to calculating and applying attention weights, commonly used in machine learning models to emphasize important parts of the data.

Utility Functions 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.signal_processing.attention_weights import AttentionWeights
>>> signal = np.random.randn(1000)
>>> processor = AttentionWeights(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.attention_weights.AttentionWeights[source]

Bases: object

A class that provides a collection of predefined attention weights for signal processing.

This class offers various methods to generate attention weights, which can be applied to signals in tasks such as filtering, feature extraction, and data weighting. Attention weights determine the importance of different parts of a signal, allowing for more focused analysis on specific sections.

uniform : static method

Generates uniform attention where all parts of the signal are treated equally.

linear : static method

Generates linearly increasing or decreasing attention.

gaussian : static method

Generates Gaussian-distributed attention weights.

exponential : static method

Generates exponentially increasing or decreasing attention.

custom_weights : static method

Accepts custom attention weights provided by the user.

static custom_weights(weights)[source]

Use custom attention weights provided by the user.

This method allows users to define their own attention weights, which can be tailored to specific applications or signal characteristics.

Parameters:

weights (numpy.ndarray) – The custom attention weights provided by the user.

Returns:

The normalized custom attention weights.

Return type:

numpy.ndarray

Examples

>>> weights = np.array([0.1, 0.2, 0.4, 0.2, 0.1])
>>> custom_weights = AttentionWeights.custom_weights(weights)
>>> print(custom_weights)
[0.1 0.2 0.4 0.2 0.1]
static exponential(size, ascending=True, base=2.0)[source]

Generate exponentially increasing or decreasing attention weights.

Exponential attention weights rapidly increase or decrease, making them suitable for emphasizing certain parts of the signal much more than others. This method can be used when the importance of signal components grows or diminishes exponentially.

Parameters:
  • size (int) – The size of the attention window or the number of elements in the signal.

  • ascending (bool, optional) – If True, weights increase exponentially; if False, weights decrease (default is True).

  • base (float, optional) – The base of the exponential function, controlling the rate of increase or decrease (default is 2.0).

Returns:

The exponential attention weights, either increasing or decreasing based on the ascending parameter.

Return type:

numpy.ndarray

Examples

>>> weights = AttentionWeights.exponential(size=5, ascending=True, base=2.0)
>>> print(weights)
[0.03125 0.0625  0.125   0.25    0.5    ]
>>> weights = AttentionWeights.exponential(size=5, ascending=False, base=2.0)
>>> print(weights)
[0.5    0.25   0.125  0.0625 0.03125]
static gaussian(size, sigma=1.0)[source]

Generate Gaussian-distributed attention weights.

Gaussian attention weights emphasize the central parts of the signal more than the edges, following a bell-shaped curve. This method is ideal for scenarios where the middle portion of the signal is more relevant.

Parameters:
  • size (int) – The size of the attention window or the number of elements in the signal.

  • sigma (float, optional) – The standard deviation of the Gaussian distribution, controlling the spread (default is 1.0).

Returns:

The Gaussian attention weights, centered on the middle of the window.

Return type:

numpy.ndarray

Examples

>>> weights = AttentionWeights.gaussian(size=5, sigma=1.0)
>>> print(weights)
[0.05448868 0.24420134 0.40261995 0.24420134 0.05448868]
static linear(size, ascending=True)[source]

Generate linearly increasing or decreasing attention weights.

Linear attention weights are useful when a gradual change in importance across the signal is desired. This can be applied when the beginning or end of a signal is more relevant.

Parameters:
  • size (int) – The size of the attention window or the number of elements in the signal.

  • ascending (bool, optional) – If True, weights increase linearly; if False, weights decrease linearly (default is True).

Returns:

The linear attention weights, either increasing or decreasing based on the ascending parameter.

Return type:

numpy.ndarray

Examples

>>> weights = AttentionWeights.linear(size=5, ascending=True)
>>> print(weights)
[0.06666667 0.13333333 0.2        0.26666667 0.33333333]
>>> weights = AttentionWeights.linear(size=5, ascending=False)
>>> print(weights)
[0.33333333 0.26666667 0.2        0.13333333 0.06666667]
static uniform(size)[source]

Generate uniform attention weights.

Uniform attention weights assign equal importance to all elements in the signal, making this method suitable for scenarios where each part of the signal is equally relevant.

Parameters:

size (int) – The size of the attention window or the number of elements in the signal.

Returns:

The uniform attention weights, with each element having equal value.

Return type:

numpy.ndarray

Examples

>>> weights = AttentionWeights.uniform(size=5)
>>> print(weights)
[0.2 0.2 0.2 0.2 0.2]

Loss Functions

Various loss functions used in training machine learning models, particularly in the context of signal processing tasks.

Utility Functions 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.signal_processing.loss_functions import LossFunctions
>>> signal = np.random.randn(1000)
>>> processor = LossFunctions(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.loss_functions.LossFunctions[source]

Bases: object

A class that provides a collection of common loss functions for signal processing.

This class includes various loss functions commonly used in regression tasks and signal processing. These loss functions measure the discrepancy between predicted and actual values, helping to optimize models during training.

mse(signal, target)[source]

Compute the Mean Square Error (MSE) loss.

mae(signal, target)[source]

Compute the Mean Absolute Error (MAE) loss.

huber(signal, target, delta=1.0)[source]

Compute the Huber loss, combining MSE and MAE.

smooth_l1(signal, target, beta=1.0)[source]

Compute the Smooth L1 loss, similar to Huber loss with a different formulation.

log_cosh(signal, target)[source]

Compute the Log-Cosh loss, a smooth approximation to the absolute error.

quantile(signal, target, quantile=0.5)[source]

Compute the Quantile loss, useful for quantile regression.

custom_loss(loss_func)[source]

Use a custom loss function provided by the user.

custom_loss(loss_func)[source]

Use a custom loss function provided by the user.

This method allows the user to define their own loss function, which can be passed as a callable to this method.

Parameters:

loss_func (callable) – The custom loss function provided by the user.

Returns:

The custom loss function itself, which can be applied to a signal and target.

Return type:

callable

Examples

>>> def custom_lf(signal, target): return np.sum((signal - target) ** 2)
>>> lf = LossFunctions()
>>> loss = lf.custom_loss(custom_lf)
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(loss(signal, target))
0.75
huber(signal, target, delta=1.0)[source]

Compute the Huber loss between the signal and target.

Huber loss is a combination of MSE and MAE, being quadratic for small errors and linear for large errors. It is less sensitive to outliers compared to MSE.

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

  • target (numpy.ndarray) – The target signal or true values.

  • delta (float, optional) – The threshold at which to switch from MSE to MAE (default is 1.0).

Returns:

The computed Huber loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.huber(signal, target, delta=1.0))
0.125
log_cosh(signal, target)[source]

Compute the Log-Cosh loss between the signal and target.

Log-Cosh loss is the logarithm of the hyperbolic cosine of the prediction error. It behaves similarly to MAE but is smoother near zero, which makes it less sensitive to outliers than MAE.

Parameters:
Returns:

The computed Log-Cosh loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.log_cosh(signal, target))
0.120114
mae(signal, target)[source]

Compute the Mean Absolute Error (MAE) between the signal and target.

The MAE loss is a robust measure of the average magnitude of errors in a set of predictions, without considering their direction.

Parameters:
Returns:

The computed MAE value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.mae(signal, target))
0.5
mse(signal, target)[source]

Compute the Mean Square Error (MSE) between the signal and target.

The MSE loss is a commonly used loss function for regression tasks, penalizing larger errors more heavily by squaring the difference between the predicted and actual values.

Parameters:
Returns:

The computed MSE value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.mse(signal, target))
0.25
quantile(signal, target, quantile=0.5)[source]

Compute the Quantile loss between the signal and target.

Quantile loss is used in quantile regression to predict the quantiles of the target variable. The loss is asymmetric and assigns different penalties to overestimates and underestimates.

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

  • target (numpy.ndarray) – The target signal or true values.

  • quantile (float, optional) – The quantile to predict (0 < quantile < 1) (default is 0.5).

Returns:

The computed Quantile loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.quantile(signal, target, quantile=0.5))
0.25
smooth_l1(signal, target, beta=1.0)[source]

Compute the Smooth L1 loss between the signal and target.

Smooth L1 loss, also known as the Huber loss in object detection, is less sensitive to outliers than MSE and provides a smooth transition between L1 and L2 losses.

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

  • target (numpy.ndarray) – The target signal or true values.

  • beta (float, optional) – The transition point between quadratic and linear loss (default is 1.0).

Returns:

The computed Smooth L1 loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.smooth_l1(signal, target, beta=1.0))
0.125

Convolutional Kernels

Functions for creating and applying convolutional kernels, which are essential in convolutional neural networks and other filtering tasks.

Utility Functions 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.signal_processing.convolutional_kernels import ConvolutionalKernels
>>> signal = np.random.randn(1000)
>>> processor = ConvolutionalKernels(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.convolutional_kernels.ConvolutionKernels[source]

Bases: object

A class that provides a collection of common convolution kernels for signal processing.

Convolution kernels are used to perform various operations on signals, such as smoothing, sharpening, and edge detection. These operations are crucial in preprocessing steps, particularly in fields like signal processing, image processing, and computer vision.

smoothing : static method

Generates a simple smoothing (average) kernel.

sharpening : static method

Generates a kernel for sharpening signals.

edge_detection : static method

Generates a kernel for detecting edges in signals.

custom_kernel : static method

Accepts and returns a custom kernel provided by the user.

static custom_kernel(kernel)[source]

Use a custom convolution kernel provided by the user.

This method allows the user to define a custom kernel that can be applied to a signal for specialized filtering or other operations.

Parameters:

kernel (numpy.ndarray) – The custom kernel provided by the user.

Returns:

The custom kernel itself.

Return type:

numpy.ndarray

Examples

>>> kernel = np.array([0.2, 0.5, 0.2])
>>> custom_kernel = ConvolutionKernels.custom_kernel(kernel)
>>> print(custom_kernel)
[0.2 0.5 0.2]
static edge_detection()[source]

Generate an edge detection kernel.

An edge detection kernel is designed to highlight the boundaries between different regions in a signal. This kernel is particularly useful in detecting transitions or changes in intensity, which is essential in edge detection tasks in image processing.

Returns:

The edge detection kernel, typically highlighting changes in intensity between adjacent elements.

Return type:

numpy.ndarray

Examples

>>> kernel = ConvolutionKernels.edge_detection()
>>> print(kernel)
[ -1  0  1 ]
static sharpening()[source]

Generate a sharpening kernel.

A sharpening kernel enhances the differences between adjacent values in a signal, making the features more pronounced. This is particularly useful in applications like edge enhancement in images.

Returns:

The sharpening kernel, typically centered around a positive value with negative values on either side.

Return type:

numpy.ndarray

Examples

>>> kernel = ConvolutionKernels.sharpening()
>>> print(kernel)
[ -1  2  -1 ]
static smoothing(size=3)[source]

Generate a smoothing kernel, also known as an averaging kernel.

A smoothing kernel is used to reduce noise or to create a blurred version of the signal by averaging neighboring values. This is often the first step in signal processing to remove high-frequency noise.

Parameters:

size (int, optional) – The size of the kernel (must be odd). The default is 3.

Returns:

The smoothing kernel, where each element is equal to 1/size.

Return type:

numpy.ndarray

Raises:

ValueError – If the size of the kernel is not an odd number.

Examples

>>> kernel = ConvolutionKernels.smoothing(size=3)
>>> print(kernel)
[0.33333333 0.33333333 0.33333333]

Common Utilities

Common Utilities

A collection of common utility functions that provide general-purpose support across various signal processing tasks.

Utility Functions 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.config_utilities.common import Common
>>> signal = np.random.randn(1000)
>>> processor = Common(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.utils.config_utilities.common.argrelextrema(signal, comparator=<ufunc 'greater'>, order=1)[source]

Find the relative extrema (maxima or minima) in a 1D signal.

This function identifies local maxima or minima in a signal by comparing each point with its neighbors.

Parameters:
  • signal (numpy.ndarray) – The input signal in which to find the extrema.

  • comparator (function, optional) – The comparison function to use (e.g., np.greater for maxima, np.less for minima). Defaults to np.greater.

  • order (int, optional) – The number of points on each side to use for comparison. Must be a positive integer. Defaults to 1.

Returns:

extrema – Indices of the relative extrema in the signal.

Return type:

numpy.ndarray

Raises:

ValueError – If the order is less than 1 or if the signal is too short to find extrema with the given order.

Examples

>>> signal = np.array([1, 3, 2, 4, 3, 5, 4])
>>> maxima = argrelextrema(signal, comparator=np.greater, order=1)
>>> print(maxima)
[1, 3, 5]
vitalDSP.utils.config_utilities.common.coherence(x, y, fs=1.0, nperseg=256)[source]

Compute the coherence between two signals.

Coherence measures the degree of correlation between two signals in the frequency domain.

Parameters:
  • x (numpy.ndarray) – First input signal.

  • y (numpy.ndarray) – Second input signal.

  • fs (float, optional) – Sampling frequency of the signals (default is 1.0).

  • nperseg (int, optional) – Length of each segment for coherence computation (default is 256).

Returns:

  • numpy.ndarray – Frequency array.

  • numpy.ndarray – Coherence values.

Examples

>>> x = np.sin(2 * np.pi * np.linspace(0, 1, 500))
>>> y = np.sin(2 * np.pi * np.linspace(0, 1, 500) + np.pi / 4)
>>> freqs, coh = coherence(x, y, fs=500)
>>> print(freqs, coh)
vitalDSP.utils.config_utilities.common.deprecated(reason)[source]
vitalDSP.utils.config_utilities.common.dtw_distance_windowed(x, y, window=None)[source]

Compute the Dynamic Time Warping (DTW) distance between two sequences using a sliding window.

Parameters:
  • x (numpy.ndarray) – The first time series.

  • y (numpy.ndarray) – The second time series.

  • window (int, optional) – The size of the window for the DTW computation. If None, it uses the full sequence.

Returns:

The DTW distance between the two sequences.

Return type:

float

vitalDSP.utils.config_utilities.common.filtfilt(b, a, signal)[source]

Apply a forward-backward IIR/FIR filter to a signal for zero-phase filtering.

Parameters:
  • b (numpy.ndarray) – Numerator coefficients of the filter (the feedforward part).

  • a (numpy.ndarray) – Denominator coefficients of the filter (the feedback part).

  • signal (numpy.ndarray) – The input signal to be filtered.

Returns:

y – The filtered signal with zero phase distortion.

Return type:

numpy.ndarray

Examples

>>> b = np.array([0.0675, 0.1349, 0.0675])
>>> a = np.array([1.0000, -1.1430, 0.4128])
>>> signal = np.array([0.0, 0.5, 1.0, 0.5, 0.0])
>>> filtered_signal = filtfilt(b, a, signal)
>>> print(filtered_signal)
vitalDSP.utils.config_utilities.common.find_peaks(signal, height=None, distance=None, threshold=None, prominence=None, width=None)[source]

Identify peaks in a 1D signal.

This function finds local maxima in a signal that meet specific criteria such as minimum height, distance, and prominence.

Parameters:
  • signal (numpy.ndarray) – The input signal in which to find peaks.

  • height (float or None, optional) – Minimum height required for a peak. Peaks below this value are ignored.

  • distance (int or None, optional) – Minimum number of samples required between neighboring peaks.

  • threshold (float or None, optional) – Minimum difference between a peak and its neighboring points.

  • prominence (float or None, optional) – Minimum prominence of peaks, which measures how much a peak stands out relative to its surroundings.

  • width (int or None, optional) – Minimum width required for a peak, measured as the number of samples.

Returns:

peaks – Indices of the peaks in the signal that meet the specified criteria.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([0, 1, 0, 2, 0, 3, 0])
>>> peaks = find_peaks(signal, height=1)
>>> print(peaks)
[1, 3, 5]
vitalDSP.utils.config_utilities.common.grangercausalitytests(data, max_lag, verbose=False)[source]

Perform Granger causality tests to determine if one time series can predict another.

The Granger causality test evaluates whether the past values of one time series can provide statistically significant information about the future values of another time series.

Parameters:
  • data (numpy.ndarray) – The input data array with shape (n_samples, 2), where the first column is the dependent variable.

  • max_lag (int) – Maximum lag to consider for causality.

  • verbose (bool, optional) – If True, prints out detailed test statistics (default is False).

Returns:

Granger causality test results, including F-test statistics for each lag.

Return type:

dict

Examples

>>> data = np.random.rand(100, 2)
>>> results = grangercausalitytests(data, max_lag=4, verbose=True)
>>> print(results)
vitalDSP.utils.config_utilities.common.pearsonr(x, y)[source]

Compute the Pearson correlation coefficient between two signals.

The Pearson correlation coefficient is a measure of linear correlation between two signals, with a value between -1 and 1.

Parameters:
Returns:

Pearson correlation coefficient.

Return type:

float

Raises:

ValueError – If the input arrays do not have the same length.

Examples

>>> x = np.array([1, 2, 3, 4])
>>> y = np.array([1, 2, 3, 5])
>>> corr = pearsonr(x, y)
>>> print(corr)
0.98

Usage Examples

Peak Detection

from vitalDSP.utils.signal_processing.peak_detection import PeakDetection

# Initialize peak detector
detector = PeakDetection(signal, sampling_rate)

# Detect peaks
peaks = detector.detect_peaks(method='savgol')

# Detect specific signal types
ecg_peaks = detector.detect_ecg_peaks()
ppg_peaks = detector.detect_ppg_peaks()

Data Synthesis

from vitalDSP.utils.data_processing.synthesize_data import SynthesizeData

synthesizer = SynthesizeData()

# Generate synthetic ECG
ecg = synthesizer.generate_synthetic_ecg(
    duration=10,
    sampling_rate=1000,
    heart_rate=72
)

# Generate synthetic PPG
ppg = synthesizer.generate_synthetic_ppg(
    duration=10,
    sampling_rate=1000,
    heart_rate=72
)

Normalization

from vitalDSP.utils.signal_processing.normalization import z_score_normalization, min_max_normalization
from vitalDSP.utils.signal_processing.scaler import StandardScaler

# Z-score normalization
normalized_signal = z_score_normalization(signal)

# Min-max normalization
scaled_signal = min_max_normalization(signal)

# Using scaler class
scaler = StandardScaler()
fitted_signal = scaler.fit_transform(signal)

Interpolation

from vitalDSP.utils.signal_processing.interpolations import linear_interpolation, spline_interpolation

# Linear interpolation
interpolated = linear_interpolation(signal, missing_indices)

# Spline interpolation
smooth_interpolated = spline_interpolation(signal, missing_indices)

Convolutional Kernels

Functions for creating and applying convolutional kernels, which are essential in convolutional neural networks and other filtering tasks.

Utility Functions 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.signal_processing.convolutional_kernels import ConvolutionalKernels
>>> signal = np.random.randn(1000)
>>> processor = ConvolutionalKernels(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.convolutional_kernels.ConvolutionKernels[source]

Bases: object

A class that provides a collection of common convolution kernels for signal processing.

Convolution kernels are used to perform various operations on signals, such as smoothing, sharpening, and edge detection. These operations are crucial in preprocessing steps, particularly in fields like signal processing, image processing, and computer vision.

smoothing : static method

Generates a simple smoothing (average) kernel.

sharpening : static method

Generates a kernel for sharpening signals.

edge_detection : static method

Generates a kernel for detecting edges in signals.

custom_kernel : static method

Accepts and returns a custom kernel provided by the user.

static custom_kernel(kernel)[source]

Use a custom convolution kernel provided by the user.

This method allows the user to define a custom kernel that can be applied to a signal for specialized filtering or other operations.

Parameters:

kernel (numpy.ndarray) – The custom kernel provided by the user.

Returns:

The custom kernel itself.

Return type:

numpy.ndarray

Examples

>>> kernel = np.array([0.2, 0.5, 0.2])
>>> custom_kernel = ConvolutionKernels.custom_kernel(kernel)
>>> print(custom_kernel)
[0.2 0.5 0.2]
static edge_detection()[source]

Generate an edge detection kernel.

An edge detection kernel is designed to highlight the boundaries between different regions in a signal. This kernel is particularly useful in detecting transitions or changes in intensity, which is essential in edge detection tasks in image processing.

Returns:

The edge detection kernel, typically highlighting changes in intensity between adjacent elements.

Return type:

numpy.ndarray

Examples

>>> kernel = ConvolutionKernels.edge_detection()
>>> print(kernel)
[ -1  0  1 ]
static sharpening()[source]

Generate a sharpening kernel.

A sharpening kernel enhances the differences between adjacent values in a signal, making the features more pronounced. This is particularly useful in applications like edge enhancement in images.

Returns:

The sharpening kernel, typically centered around a positive value with negative values on either side.

Return type:

numpy.ndarray

Examples

>>> kernel = ConvolutionKernels.sharpening()
>>> print(kernel)
[ -1  2  -1 ]
static smoothing(size=3)[source]

Generate a smoothing kernel, also known as an averaging kernel.

A smoothing kernel is used to reduce noise or to create a blurred version of the signal by averaging neighboring values. This is often the first step in signal processing to remove high-frequency noise.

Parameters:

size (int, optional) – The size of the kernel (must be odd). The default is 3.

Returns:

The smoothing kernel, where each element is equal to 1/size.

Return type:

numpy.ndarray

Raises:

ValueError – If the size of the kernel is not an odd number.

Examples

>>> kernel = ConvolutionKernels.smoothing(size=3)
>>> print(kernel)
[0.33333333 0.33333333 0.33333333]

Peak Detection

Identify peaks in the signal, which are often indicative of significant events or features, such as heartbeats or respiratory cycles.

Peak Detection Module for Physiological Signal Processing

This module provides comprehensive peak detection capabilities for various physiological signals including ECG, PPG, EEG, respiratory, and arterial blood pressure (ABP) signals. It implements multiple detection algorithms optimized for different signal types and characteristics.

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

Key Features: - Multiple peak detection algorithms - Signal-specific optimizations (ECG R-peaks, PPG systolic peaks) - Advanced filtering and preprocessing integration - Scalable threshold-based detection - Derivative-based detection methods - Wavelet and bandpass filtering for EEG

Examples:

Basic peak detection:
>>> import numpy as np
>>> from vitalDSP.utils.signal_processing.peak_detection import PeakDetection
>>> signal = np.sin(np.linspace(0, 10, 1000)) + np.random.normal(0, 0.1, 1000)
>>> detector = PeakDetection(signal, method="threshold", height=0.5)
>>> peaks = detector.detect_peaks()
>>> print(f"Detected {len(peaks)} peaks")
ECG R-peak detection:
>>> ecg_detector = PeakDetection(ecg_signal, method="ecg_r_peak")
>>> r_peaks = ecg_detector.detect_peaks()
>>> print(f"R-peaks: {len(r_peaks)}")
PPG systolic peak detection:
>>> ppg_detector = PeakDetection(ppg_signal, method="ppg_systolic_peaks")
>>> systolic_peaks = ppg_detector.detect_peaks()
>>> print(f"Systolic peaks: {len(systolic_peaks)}")
class vitalDSP.utils.signal_processing.peak_detection.PeakDetection(signal, method='threshold', **kwargs)[source]

Bases: object

A class to detect peaks in various physiological signals like ECG, PPG, EEG, respiratory, and arterial blood pressure (ABP) signals.

detect_peaks : function

Detects the peaks in the signal using the selected method.

detect_peaks()[source]

Detect peaks in the signal based on the selected method.

Returns:

peaks – The indices of the detected peaks.

Return type:

numpy.ndarray

Raises:

ValueError – If an invalid method is selected.

Examples

>>> signal = np.array([1, 2, 3, 4, 5, 4, 3, 2, 1])
>>> detector = PeakDetection(signal, method="threshold", threshold=4)
>>> peaks = detector.detect_peaks()
>>> print(peaks)

Loss Functions

Various loss functions used in training machine learning models, particularly in the context of signal processing tasks.

Utility Functions 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.signal_processing.loss_functions import LossFunctions
>>> signal = np.random.randn(1000)
>>> processor = LossFunctions(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.loss_functions.LossFunctions[source]

Bases: object

A class that provides a collection of common loss functions for signal processing.

This class includes various loss functions commonly used in regression tasks and signal processing. These loss functions measure the discrepancy between predicted and actual values, helping to optimize models during training.

mse(signal, target)[source]

Compute the Mean Square Error (MSE) loss.

mae(signal, target)[source]

Compute the Mean Absolute Error (MAE) loss.

huber(signal, target, delta=1.0)[source]

Compute the Huber loss, combining MSE and MAE.

smooth_l1(signal, target, beta=1.0)[source]

Compute the Smooth L1 loss, similar to Huber loss with a different formulation.

log_cosh(signal, target)[source]

Compute the Log-Cosh loss, a smooth approximation to the absolute error.

quantile(signal, target, quantile=0.5)[source]

Compute the Quantile loss, useful for quantile regression.

custom_loss(loss_func)[source]

Use a custom loss function provided by the user.

custom_loss(loss_func)[source]

Use a custom loss function provided by the user.

This method allows the user to define their own loss function, which can be passed as a callable to this method.

Parameters:

loss_func (callable) – The custom loss function provided by the user.

Returns:

The custom loss function itself, which can be applied to a signal and target.

Return type:

callable

Examples

>>> def custom_lf(signal, target): return np.sum((signal - target) ** 2)
>>> lf = LossFunctions()
>>> loss = lf.custom_loss(custom_lf)
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(loss(signal, target))
0.75
huber(signal, target, delta=1.0)[source]

Compute the Huber loss between the signal and target.

Huber loss is a combination of MSE and MAE, being quadratic for small errors and linear for large errors. It is less sensitive to outliers compared to MSE.

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

  • target (numpy.ndarray) – The target signal or true values.

  • delta (float, optional) – The threshold at which to switch from MSE to MAE (default is 1.0).

Returns:

The computed Huber loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.huber(signal, target, delta=1.0))
0.125
log_cosh(signal, target)[source]

Compute the Log-Cosh loss between the signal and target.

Log-Cosh loss is the logarithm of the hyperbolic cosine of the prediction error. It behaves similarly to MAE but is smoother near zero, which makes it less sensitive to outliers than MAE.

Parameters:
Returns:

The computed Log-Cosh loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.log_cosh(signal, target))
0.120114
mae(signal, target)[source]

Compute the Mean Absolute Error (MAE) between the signal and target.

The MAE loss is a robust measure of the average magnitude of errors in a set of predictions, without considering their direction.

Parameters:
Returns:

The computed MAE value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.mae(signal, target))
0.5
mse(signal, target)[source]

Compute the Mean Square Error (MSE) between the signal and target.

The MSE loss is a commonly used loss function for regression tasks, penalizing larger errors more heavily by squaring the difference between the predicted and actual values.

Parameters:
Returns:

The computed MSE value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.mse(signal, target))
0.25
quantile(signal, target, quantile=0.5)[source]

Compute the Quantile loss between the signal and target.

Quantile loss is used in quantile regression to predict the quantiles of the target variable. The loss is asymmetric and assigns different penalties to overestimates and underestimates.

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

  • target (numpy.ndarray) – The target signal or true values.

  • quantile (float, optional) – The quantile to predict (0 < quantile < 1) (default is 0.5).

Returns:

The computed Quantile loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.quantile(signal, target, quantile=0.5))
0.25
smooth_l1(signal, target, beta=1.0)[source]

Compute the Smooth L1 loss between the signal and target.

Smooth L1 loss, also known as the Huber loss in object detection, is less sensitive to outliers than MSE and provides a smooth transition between L1 and L2 losses.

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

  • target (numpy.ndarray) – The target signal or true values.

  • beta (float, optional) – The transition point between quadratic and linear loss (default is 1.0).

Returns:

The computed Smooth L1 loss value.

Return type:

float

Examples

>>> lf = LossFunctions()
>>> signal = np.array([1, 2, 3])
>>> target = np.array([1.5, 2.5, 3.5])
>>> print(lf.smooth_l1(signal, target, beta=1.0))
0.125

Mother Wavelets

Functions related to mother wavelets, which are used as the basis for wavelet transforms, crucial for time-frequency analysis.

Utility Functions 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.signal_processing.mother_wavelets import MotherWavelets
>>> signal = np.random.randn(1000)
>>> processor = MotherWavelets(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.mother_wavelets.Wavelet[source]

Bases: object

A class for generating different types of mother wavelets based on their mathematical formulas.

Wavelets are used in various signal processing applications, particularly in analyzing non-stationary signals where both time and frequency localization is important. This class provides methods to generate common wavelets used in discrete wavelet transforms (DWT).

haar() numpy.ndarray[source]

Generates a Haar wavelet, best for detecting sudden changes in signals.

db(order=4) numpy.ndarray[source]

Generates a Daubechies wavelet, suitable for analyzing smooth signals with sharp discontinuities.

sym(order=4) numpy.ndarray[source]

Generates a Symlet wavelet, ideal for symmetric analysis and minimizing edge effects.

coif(order=1) numpy.ndarray[source]

Generates a Coiflet wavelet, providing near-symmetry and smoothness, ideal for subtle signal variations.

gauchy(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Gaussian wavelet, excellent for isolating features with a Gaussian shape in the time domain.

mexican_hat(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Mexican Hat wavelet, commonly used for detecting peaks and ridges.

morlet(sigma=1.0, N=6, f=1.0) numpy.ndarray[source]

Generates a Morlet wavelet, useful for time-frequency analysis.

meyer(N=6) numpy.ndarray[source]

Generates a Meyer wavelet, suitable for analyzing slowly varying signals without sharp edges.

biorthogonal(N=6, p=2, q=2) numpy.ndarray[source]

Generates a Biorthogonal wavelet, useful in image compression and providing exact reconstruction with linear phase.

reverse_biorthogonal(N=6, p=2, q=2) numpy.ndarray[source]

Generates a Reverse Biorthogonal wavelet, useful in de-noising applications.

complex_gaussian(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Complex Gaussian wavelet, applied in phase and frequency modulation.

shannon(N=6) numpy.ndarray[source]

Generates a Shannon wavelet, ideal for signals with sharp time-frequency localization.

cmor(sigma=1.0, N=6, f=1.0) numpy.ndarray[source]

Generates a Complex Morlet wavelet, used for time-frequency localization in non-stationary signals.

fbsp(N=6, m=5, s=0.5) numpy.ndarray[source]

Generates a Frequency B-Spline wavelet, useful for analyzing frequency-modulated signals.

mhat(sigma=1.0, N=6) numpy.ndarray[source]

Generates a Modified Mexican Hat wavelet, applied in edge detection in images and other signals.

custom_wavelet(wavelet: numpy.ndarray) numpy.ndarray[source]

Use a custom wavelet provided by the user.

static biorthogonal(N=6, p=2, q=2)[source]

Generate a Biorthogonal wavelet.

Biorthogonal wavelets provide exact reconstruction with linear phase, making them useful in image compression (e.g., JPEG 2000).

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • p (int, optional) – The order of the B-spline used for the analysis filter (default is 2).

  • q (int, optional) – The order of the B-spline used for the synthesis filter (default is 2).

Returns:

wavelet – The Biorthogonal wavelet coefficients (analysis side).

Return type:

numpy.ndarray

Examples

>>> biorthogonal_wavelet = Wavelet.biorthogonal(N=6, p=2, q=2)
>>> print(biorthogonal_wavelet)
static cmor(sigma=1.0, N=6, f=1.0)[source]

Generate a Complex Morlet wavelet.

Complex Morlet wavelets are used for time-frequency localization, particularly in non-stationary signal analysis.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

  • f (float, optional) – The central frequency of the Complex Morlet wavelet (default is 1.0).

Returns:

wavelet – The Complex Morlet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> cmor_wavelet = Wavelet.cmor(sigma=1.0, N=6, f=1.0)
>>> print(cmor_wavelet)
static coif(order=1)[source]

Generate a Coiflet wavelet of a given order.

Coiflet wavelets are nearly symmetric and provide smooth waveforms, making them ideal for analyzing subtle variations in signals.

Parameters:

order (int, optional) – The order of the Coiflet wavelet (default is 1).

Returns:

wavelet_coeffs – The Coiflet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> coif_wavelet = Wavelet.coif(order=1)
>>> print(coif_wavelet)
static complex_gaussian(sigma=1.0, N=6)[source]

Generate a Complex Gaussian wavelet.

Complex Gaussian wavelets are applied in phase and frequency modulation, making them suitable for radar and communication signals.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Complex Gaussian wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> complex_gaussian_wavelet = Wavelet.complex_gaussian(sigma=1.0, N=6)
>>> print(complex_gaussian_wavelet)
static custom_wavelet(wavelet)[source]

Use a custom wavelet provided by the user.

This method allows the use of a custom wavelet defined by the user, which can be applied in specific or novel signal processing tasks.

Parameters:

wavelet (numpy.ndarray) – The custom wavelet coefficients provided by the user.

Returns:

wavelet – The custom wavelet.

Return type:

numpy.ndarray

Examples

>>> custom_wavelet = Wavelet.custom_wavelet(np.array([0.2, 0.5, 0.2]))
>>> print(custom_wavelet)
static db(order=4)[source]

Generate Daubechies wavelet low-pass and high-pass filter coefficients.

Returns the standard orthonormal Daubechies scaling (low-pass) and wavelet (high-pass) filter pair for the given vanishing-moment order. Known exact coefficients are used for orders 1-8; higher orders fall back to a symmetric approximation.

Parameters:

order (int, optional) – The order (number of vanishing moments) of the Daubechies wavelet (default is 4).

Returns:

  • low_pass (numpy.ndarray) – Scaling filter coefficients (real-valued).

  • high_pass (numpy.ndarray) – Wavelet filter coefficients (real-valued).

Examples

>>> lo, hi = Wavelet.db(order=4)
>>> print(lo)
static fbsp(N=6, m=5, s=0.5)[source]

Generate a Frequency B-Spline wavelet.

Frequency B-Spline wavelets are useful for analyzing frequency-modulated signals, often applied in audio signal processing.

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • m (int, optional) – The order of the B-spline (default is 5).

  • s (float, optional) – The bandwidth parameter (default is 0.5).

Returns:

wavelet – The Frequency B-Spline wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> fbsp_wavelet = Wavelet.fbsp(N=6, m=5, s=0.5)
>>> print(fbsp_wavelet)
static gauchy(sigma=1.0, N=6)[source]

Generate a Gaussian wavelet.

Gaussian wavelets are ideal for isolating specific features with a Gaussian shape in the time domain, such as spikes in EEG signals.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Gaussian wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> gauchy_wavelet = Wavelet.gauchy(sigma=1.0, N=6)
>>> print(gauchy_wavelet)
static haar()[source]

Generate a Haar wavelet.

The Haar wavelet is the simplest wavelet, best suited for detecting sudden changes in a signal, such as step functions or sharp transitions.

Returns:

wavelet – The Haar wavelet.

Return type:

numpy.ndarray

Examples

>>> haar_wavelet = Wavelet.haar()
>>> print(haar_wavelet)
[0.70710678 0.70710678]
static mexican_hat(sigma=1.0, N=6)[source]

Generate a Mexican Hat wavelet (also known as the Ricker wavelet).

The Mexican Hat wavelet is commonly used in detecting peaks and ridges in signals, particularly useful in EEG spike detection.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Mexican Hat wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> mexican_hat_wavelet = Wavelet.mexican_hat(sigma=1.0, N=6)
>>> print(mexican_hat_wavelet)
static meyer(N=6)[source]

Generate a Meyer wavelet.

Meyer wavelets are smooth and suitable for analyzing slowly varying signals without sharp edges.

Parameters:

N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Meyer wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> meyer_wavelet = Wavelet.meyer(N=6)
>>> print(meyer_wavelet)
static mhat(sigma=1.0, N=6)[source]

Generate a Modified Mexican Hat wavelet.

Modified Mexican Hat wavelets are applied in edge detection in images and other signals with sharp transitions.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Modified Mexican Hat wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> mhat_wavelet = Wavelet.mhat(sigma=1.0, N=6)
>>> print(mhat_wavelet)
static morlet(sigma=1.0, N=6, f=1.0)[source]

Generate a Morlet wavelet.

Morlet wavelets are particularly useful for time-frequency analysis and are frequently applied in EEG and seismic signal analysis.

Parameters:
  • sigma (float, optional) – The standard deviation of the Gaussian function (default is 1.0).

  • N (int, optional) – The number of points in the wavelet (default is 6).

  • f (float, optional) – The central frequency of the Morlet wavelet (default is 1.0).

Returns:

wavelet – The Morlet wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> morlet_wavelet = Wavelet.morlet(sigma=1.0, N=6, f=1.0)
>>> print(morlet_wavelet)
static reverse_biorthogonal(N=6, p=2, q=2)[source]

Generate a Reverse Biorthogonal wavelet.

Reverse Biorthogonal wavelets are the synthesis duals of biorthogonal wavelets, useful in de-noising applications.

Parameters:
  • N (int, optional) – The number of points in the wavelet (default is 6).

  • p (int, optional) – The order of the B-spline (analysis side, default is 2).

  • q (int, optional) – The order of the B-spline (synthesis side, default is 2).

Returns:

wavelet – The Reverse Biorthogonal wavelet coefficients (synthesis side).

Return type:

numpy.ndarray

Examples

>>> reverse_biorthogonal_wavelet = Wavelet.reverse_biorthogonal(N=6, p=2, q=2)
>>> print(reverse_biorthogonal_wavelet)
static shannon(N=6)[source]

Generate a Shannon wavelet.

Shannon wavelets are ideal for signals with sharp time-frequency localization, such as short pulses.

Parameters:

N (int, optional) – The number of points in the wavelet (default is 6).

Returns:

wavelet – The Shannon wavelet coefficients.

Return type:

numpy.ndarray

Examples

>>> shannon_wavelet = Wavelet.shannon(N=6)
>>> print(shannon_wavelet)
static sym(order=4)[source]

Generate Symlet wavelet low-pass and high-pass filter coefficients.

Symlets are nearly symmetric modifications of the Daubechies wavelets. Known exact coefficients are used for orders 2-8; other orders fall back to the corresponding Daubechies filters.

Parameters:

order (int, optional) – The order of the Symlet wavelet (default is 4).

Returns:

  • low_pass (numpy.ndarray) – Scaling filter coefficients (real-valued).

  • high_pass (numpy.ndarray) – Wavelet filter coefficients (real-valued).

Examples

>>> lo, hi = Wavelet.sym(order=4)
>>> print(lo)

Normalization

Techniques and functions for normalizing data, ensuring that signals have consistent scales, which is essential for accurate analysis and model training.

Utility Functions 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_processing.normalization import Normalization
>>> signal = np.random.randn(1000)
>>> processor = Normalization(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
vitalDSP.utils.signal_processing.normalization.min_max_normalization(signal, min_value=0, max_value=1)[source]

Normalize the signal using Min-Max scaling.

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

  • min_value (float, optional (default=0)) – The minimum value of the desired range.

  • max_value (float, optional (default=1)) – The maximum value of the desired range.

Returns:

normalized_signal – The Min-Max normalized signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> normalized_signal = min_max_normalization(signal, min_value=-1, max_value=1)
>>> print(normalized_signal)
[-1.  -0.5  0.   0.5  1. ]
vitalDSP.utils.signal_processing.normalization.z_score_normalization(signal)[source]

Normalize the signal using Z-score normalization.

Parameters:

signal (numpy.ndarray) – The input signal to be normalized.

Returns:

normalized_signal – The Z-score normalized signal.

Return type:

numpy.ndarray

Examples

>>> signal = np.array([1, 2, 3, 4, 5])
>>> normalized_signal = z_score_normalization(signal)
>>> print(normalized_signal)
[-1.26491106 -0.63245553  0.          0.63245553  1.26491106]

Scaler

Functions for scaling data, which can include methods for both normalization and standardization to prepare signals for analysis or machine learning.

Utility Functions 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.signal_processing.scaler import Scaler
>>> signal = np.random.randn(1000)
>>> processor = Scaler(signal)
>>> result = processor.process()
>>> print(f'Processing result: {result}')
class vitalDSP.utils.signal_processing.scaler.StandardScaler[source]

Bases: object

A custom implementation of the Standard Scaler, which standardizes signals by removing the mean and scaling to unit variance.

This class can be used to normalize signals before applying transformations like the Discrete Wavelet Transform (DWT).

mean_

The mean of the signal after fitting.

Type:

float or None

std_

The standard deviation of the signal after fitting.

Type:

float or None

fit(signal)[source]

Calculate mean and standard deviation for scaling.

transform(signal)[source]

Scale the signal using the mean and standard deviation.

fit_transform(signal)[source]

Fit to the data and then transform it.

fit(signal)[source]

Fit the scaler to the signal by calculating the mean and standard deviation.

Parameters:

signal (numpy.ndarray) – The input signal to be standardized.

Return type:

None

fit_transform(signal)[source]

Fit to the signal, then transform it.

This is a convenience method that combines fit and transform into a single step.

Parameters:

signal (numpy.ndarray) – The input signal to be fitted and transformed.

Returns:

scaled_signal – The standardized signal with zero mean and unit variance.

Return type:

numpy.ndarray

Examples

>>> scaler = StandardScaler()
>>> scaled_signal = scaler.fit_transform(np.array([1, 2, 3, 4, 5]))
>>> print(scaled_signal)
transform(signal)[source]

Transform the signal using the fitted scaler by removing the mean and scaling to unit variance.

Parameters:

signal (numpy.ndarray) – The input signal to be transformed.

Returns:

scaled_signal – The standardized signal with zero mean and unit variance.

Return type:

numpy.ndarray

Raises:

ValueError – If the scaler has not been fitted yet.

Examples

>>> scaler = StandardScaler()
>>> scaler.fit(np.array([1, 2, 3, 4, 5]))
>>> scaled_signal = scaler.transform(np.array([1, 2, 3, 4, 5]))
>>> print(scaled_signal)

Synthesize Data

Methods for generating synthetic data, which can be used for training models, testing algorithms, or simulating signal processing scenarios.

Utility Functions 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 - Interactive visualization capabilities

Examples:

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

Bases: object

A class that provides access to all signal synthesis functions. This class wraps the individual functions for easier access and organization.

static generate_ecg_signal(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, qrs_width=0.08, t_wave_amplitude=0.3, p_wave_amplitude=0.25, randomize=False, display=False)[source]

Generate a synthetic ECG signal.

static generate_noisy_signal(base_signal, noise_level=0.1)[source]

Add Gaussian noise to a base signal.

static generate_ppg_data(duration=50, fs=1000)[source]

Generate synthetic PPG data for testing.

static generate_resp_signal(sampling_rate, duration, frequency=0.2, amplitude=0.5)[source]

Generate a synthetic respiratory signal.

static generate_sinusoidal(frequency, sampling_rate, duration, amplitude=1.0, phase=0.0)[source]

Generate a sinusoidal wave.

static generate_square_wave(frequency, sampling_rate, duration, amplitude=1.0, duty_cycle=0.5)[source]

Generate a square wave.

static generate_synthetic_ppg(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal.

static generate_synthetic_ppg_reversed(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal with reversed parameters.

vitalDSP.utils.data_processing.synthesize_data.generate_ecg_signal(sfecg=256, N=None, duration=30, Anoise=0.0, hrmean=60, hrstd=1.0, lfhfratio=0.5, sfint=512, ti=None, ai=None, bi=None)[source]

Generate a synthetic ECG signal using the dynamical model from McSharry et al.

Parameters:
  • sfecg (int, optional) – ECG sampling frequency in Hz (default is 256).

  • N (int, optional) – Approximate number of heartbeats (default is 60).

  • duration (int, optional) – Approximate number of seconds (default is 30).

  • Anoise (float, optional) – Amplitude of additive uniformly distributed measurement noise (default is 0).

  • hrmean (float, optional) – Mean heart rate in beats per minute (default is 60).

  • hrstd (float, optional) – Standard deviation of heart rate in beats per minute (default is 1).

  • lfhfratio (float, optional) – Low frequency to high frequency ratio (default is 0.5).

  • sfint (int, optional) – Internal sampling frequency in Hz (default is 512).

  • ti (list, optional) – Angles of extrema in degrees for PQRST (default is [-70, -15, 0, 15, 100]).

  • ai (list, optional) – Z-position of extrema for PQRST (default is [1.2, -5, 30, -7.5, 0.75]).

  • bi (list, optional) – Gaussian width of peaks for PQRST (default is [0.25, 0.1, 0.1, 0.1, 0.4]).

Returns:

  • s (ndarray) – Generated ECG signal.

  • ipeaks (ndarray) – Labels for PQRST peaks.

Examples

>>> signal = generate_ecg_signal(sfecg=256, N=256, Anoise=0.01, hrmean=70, sfint=512)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_noisy_signal(base_signal, noise_level=0.1)[source]

Add Gaussian noise to a base signal.

Parameters:
  • base_signal (numpy.ndarray) – The input signal to which noise will be added.

  • noise_level (float, optional (default=0.1)) – The standard deviation of the Gaussian noise.

Returns:

noisy_signal – The signal with added Gaussian noise.

Return type:

numpy.ndarray

Examples

>>> base_signal = generate_sinusoidal(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> noisy_signal = generate_noisy_signal(base_signal, noise_level=0.2)
>>> print(noisy_signal)
vitalDSP.utils.data_processing.synthesize_data.generate_resp_signal(sampling_rate, duration, frequency=0.2, amplitude=0.5)[source]

Generate a synthetic respiratory signal.

Parameters:
  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • frequency (float, optional (default=0.2)) – Frequency of the respiratory signal in Hz.

  • amplitude (float, optional (default=0.5)) – Amplitude of the respiratory signal.

Returns:

resp_signal – The generated synthetic respiratory signal.

Return type:

numpy.ndarray

Examples

>>> resp_signal = generate_resp_signal(sampling_rate=1000.0, duration=10.0)
>>> print(resp_signal)
vitalDSP.utils.data_processing.synthesize_data.generate_sinusoidal(frequency, sampling_rate, duration, amplitude=1.0, phase=0.0)[source]

Generate a sinusoidal wave.

Parameters:
  • frequency (float) – Frequency of the sinusoid in Hz.

  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • amplitude (float, optional (default=1.0)) – Amplitude of the sinusoid.

  • phase (float, optional (default=0.0)) – Phase shift of the sinusoid in radians.

Returns:

signal – The generated sinusoidal signal.

Return type:

numpy.ndarray

Examples

>>> signal = generate_sinusoidal(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_square_wave(frequency, sampling_rate, duration, amplitude=1.0, duty_cycle=0.5)[source]

Generate a square wave.

Parameters:
  • frequency (float) – Frequency of the square wave in Hz.

  • sampling_rate (float) – Sampling rate in Hz.

  • duration (float) – Duration of the signal in seconds.

  • amplitude (float, optional (default=1.0)) – Amplitude of the square wave.

  • duty_cycle (float, optional (default=0.5)) – Duty cycle of the square wave (fraction of one period in which the signal is high).

Returns:

signal – The generated square wave signal.

Return type:

numpy.ndarray

Examples

>>> signal = generate_square_wave(frequency=1.0, sampling_rate=100.0, duration=5.0)
>>> print(signal)
vitalDSP.utils.data_processing.synthesize_data.generate_synthetic_ppg(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, diastolic_amplitude=0.8, diastolic_width=0.15, dicrotic_notch_depth=0.6, dicrotic_notch_delay=0.2, randomize=False, display=False)[source]

Generate a synthetic PPG signal with adjustable parameters.

Parameters:
  • duration (float, optional) – Duration of the signal in seconds (default is 10).

  • sampling_rate (int, optional) – Sampling rate in Hz (default is 1000).

  • heart_rate (float, optional) – Heart rate in beats per minute (default is 60).

  • noise_level (float, optional) – Standard deviation of the Gaussian noise to be added (default is 0.01).

  • diastolic_amplitude (float, optional) – Amplitude of the diastolic peak relative to the systolic peak (default is 0.8).

  • diastolic_width (float, optional) – Width of the diastolic peak (default is 0.15).

  • dicrotic_notch_depth (float, optional) – Depth of the dicrotic notch (default is 0.6).

  • dicrotic_notch_delay (float, optional) – Time delay for the diastolic peak (default is 0.2).

  • randomize (bool, optional) – If True, introduces randomness in the diastolic amplitude, width, and dicrotic notch depth (default is False).

  • display (bool, optional) – If True, displays the generated PPG signal (default is False).

Returns:

  • time (numpy.ndarray) – Array of time values.

  • ppg_signal (numpy.ndarray) – The generated synthetic PPG signal.

Example

>>> time, ppg_signal = generate_synthetic_ppg(duration=10, heart_rate=60, randomize=True, display=True)
vitalDSP.utils.data_processing.synthesize_data.generate_synthetic_ppg_reversed(duration=10, sampling_rate=1000, heart_rate=60, noise_level=0.01, display=False)[source]

Generate a synthetic PPG signal.

Parameters:
  • duration (float, optional) – Duration of the signal in seconds (default is 10).

  • sampling_rate (int, optional) – Sampling rate in Hz (default is 1000).

  • heart_rate (float, optional) – Heart rate in beats per minute (default is 60).

  • noise_level (float, optional) – Standard deviation of the Gaussian noise to be added (default is 0.01).

  • display (bool, optional) – If True, displays the generated PPG signal (default is False).

Returns:

  • time (numpy.ndarray) – Array of time values.

  • ppg_signal (numpy.ndarray) – The generated synthetic PPG signal.

Example

>>> time, ppg_signal = generate_synthetic_ppg(duration=10, heart_rate=60, display=True)
vitalDSP.utils.data_processing.synthesize_data.ordinary_differential_equation(t, x_equations, rr=None, sfint=None, ti=None, ai=None, bi=None)[source]
vitalDSP.utils.data_processing.synthesize_data.rrprocess(flo, fhi, flostd, fhistd, lfhfratio, hrmean, hrstd, sfrr, n)[source]