API Reference¶
Data Preprocessing¶
ECG¶
- class physioview.pipeline.ECG.BeatDetectors(fs: int, preprocessed: bool = True)[source]¶
A class for detecting beats in electrocardiogram (ECG) signals using popular algorithms.
Parameters/Attributes¶
- fsint
The sampling rate of the ECG signal.
- preprocessedbool, optional
Whether the ECG signal is preprocessed or not; by default, True.
Notes
Both unfiltered and filtered ECG data may be passed as inputs to the beat detection functions. If unfiltered data is passed, the preprocessed parameter should be set to False, and the beat detection functions will pre-process the signal using the algorithm’s original pre-processing procedures.
- engzee(signal: ndarray) ndarray[source]¶
Extract QRS complex locations from an ECG signal with the Engelse and Zeelenberg (1979) algorithm, modified by Lourenço et al. (2011).
- Parameters:
signal (array_like) – An array containing the ECG signal.
- Returns:
ecg_beats – An array containing the indices of detected R peaks.
- Return type:
array_like
References
Engelse, W. A. H., & Zeelenberg, C. (1979). A single scan algorithm for QRS detection and feature extraction. IEEE Computers in Cardiology, 6, 37-42.
Lourenço, A., Fred, A., & Ribeiro, B. (2012). Real time electrocardiogram segmentation for finger based ECG biometrics. In Proceedings of the 2012 Eighth International Conference on Intelligent Information Hiding and Multimedia Signal Processing (IIH-MSP) (pp. 21-24). IEEE.
- manikandan(signal: ndarray, adaptive_threshold: bool = True, window: float = 0.44) ndarray[source]¶
Extract R peak locations from an ECG signal with the Manikandan and Soman (2012) algorithm.
- Parameters:
signal (array_like) – An array containing the ECG signal.
adaptive_threshold (boolean, optional) – Whether to refine beat detection using adaptive thresholding; by default, True.
window (float, optional) – The size (in seconds) of the sliding search window for the adaptive threshold; by default, 0.44 seconds (440 milliseconds).
- Returns:
ecg_beats – An array containing the indices of detected R peaks.
- Return type:
array_like
References
Manikandan, R., & Soman, K. P. (2012). A novel method for detecting R-peaks in electrocardiogram (ECG) signal. Biomedical Signal Processing and Control, 7(2), 118-128.
- nabian(signal: ndarray) ndarray[source]¶
Extract R peak locations from an ECG signal with the Nabian et al. (2018) algorithm.
- Parameters:
signal (array_like) – An array containing the ECG signal.
- Returns:
ecg_beats – An array containing the indices of detected R peaks.
- Return type:
array_like
References
Nabian, M., et al. (2018). An open-source feature extraction tool for the analysis of peripheral physiological data. IEEE Journal of Translational Engineering in Health and Medicine, 6, 1-11.
- pantompkins(signal: ndarray) ndarray[source]¶
Extract QRS complex locations from an ECG signal with the Pan & Tompkins (1985) algorithm.
- Parameters:
signal (array_like) – An array containing the ECG signal.
- Returns:
ecg_beats – An array containing the indices of detected beats.
- Return type:
array_like
References
Pan, S. J., & Tompkins, W. J. (1985). A real-time QRS detection algorithm. IEEE Transactions on Biomedical Engineering, 32(3), 230-236.
- class physioview.pipeline.ECG.Filters(fs: int, powerline_freq: Literal[50, 60] = 60)[source]¶
A class for filtering raw electrocardiogram (ECG) signals.
Parameters/Attributes¶
- fsint
The sampling rate of the ECG signal.
- powerline_freqint
The powerline interference frequency. This value must be either 50 or 60 (by default, 60). The 50 Hz power grid is prevalent in many European, Asian, and African countries.
- baseline_wander(signal: ndarray, cutoff: float = 0.05, order: int = 2) ndarray[source]¶
Apply a high-pass filter to remove baseline wander from ECG data.
- Parameters:
signal (array_like) – An array containing the noisy signal data.
cutoff (float) – The cut-off frequency at which frequencies below this value in the signal are attenuated; by default, 0.05 Hz.
order (int) – The filter order, i.e., the number of samples required to produce the desired filtered output; by default, 2.
- Returns:
filtered – An array containing the filtered signal data.
- Return type:
array_like
- filter_signal(signal: ndarray, lowcut: float = 1, highcut: float = 15, rp: float = 0.15, rs: float = 80, order: int = 2) ndarray[source]¶
Filter out artifact from ECG data due to powerline interference, baseline wander, movement, and muscle noise using an elliptic (Cauer) bandpass filter.
- Parameters:
signal (array_like) – An array containing the ECG data to be filtered.
lowcut (float, optional) – The lower cutoff frequency (in Hz) of the bandpass filter below which frequencies are attenuated; by default, 1 Hz.
highcut (float, optional) – The upper cutoff frequency (in Hz) of the bandpass filter above which frequencies are attenuated; by default, 15 Hz.
rp (float, optional) – The maximum ripple (in dB) allowed in the passband; by default, 0.15 dB. Smaller values make the passband flatter (i.e., allow less distortion of ECG frequencies).
rs (float, optional) – The minimum ripple (in dB) allowed in the stopband; by default, 80 dB. Larger values reject more noise.
order (int, optional) – The filter order. Lower orders yield smoother transitions but less sharp cutoff; by default, 2.
- Returns:
filtered – An array containing the bandpass-filtered ECG signal.
- Return type:
array_like
Notes
This is the default filter used in the PhysioView Dashboard.
- muscle_noise(signal: ndarray, lowcut: float = 30, highcut: float = 100, order: int = 2) ndarray[source]¶
Apply a bandstop filter to remove muscle (EMG) noise from ECG data.
- Parameters:
signal (array_like) – An array containing the noisy signal data.
lowcut (float, optional) – The lower cutoff frequency of the bandstop filter; by default, 30.
highcut (float, optional) – The upper cutoff frequency of the bandstop filter; by default, 100
order (int, optional) – The filter order, i.e., the number of samples required to produce the desired filtered output; by default, 2.
- Returns:
filtered – The filtered signal with muscle/EMG noise removed.
- Return type:
array_like
- powerline_interference(signal: ndarray, q: float = 30) ndarray[source]¶
Filter out powerline interference at a specified frequency.
- Parameters:
signal (array_like) – An array containing the noisy signal data.
q (float, optional) – The quality factor, i.e., how narrow or wide the stopband is for a notch filter (by default, 30). A higher quality factor indicates a narrower bandpass.
- Returns:
filtered – An array containing the filtered signal data.
- Return type:
array_like
PPG¶
- class physioview.pipeline.PPG.BeatDetectors(fs: int, preprocessed: bool = True)[source]¶
A class for detecting beats in photoplethysmography (PPG) signals using popular algorithms.
Parameters/Attributes¶
- fsint
The sampling rate of the PPG signal.
- preprocessedbool, optional
Whether the input PPG data is pre-processed or not; by default, True. If False, the beat detection methods will pre-process the input data according to the original algorithms.
Notes
Both unfiltered and filtered PPG data may be passed as inputs to the beat detection functions. If unfiltered data is passed, the preprocessed parameter should be set to False, and the beat detection functions will pre-process the signal using the algorithm’s original pre-processing procedures.
- adaptive_threshold(signal: ndarray, ma_perc: float = 20) ndarray[source]¶
Extract beat locations from PPG data with the adaptive thresholding algorithm by van Gent al. (2018).
- Parameters:
signal (array_like) – An array containing the PPG signal.
ma_perc (float, optional) – The percentage with which to raise the moving average, used for fitting detection solutions to the data; by default, 20.
- Returns:
ppg_beats – An array containing indices of PPG pulse onsets.
- Return type:
array_like
Notes
The original source code can be found in the HeartPy package at: https://github.com/paulvangentcom/heartrate_analysis_python.
References
Van Gent, P., Farah, H., Van Nes, N., & Van Arem, B. (2019). HeartPy: A novel heart rate algorithm for the analysis of noisy signals. Transportation Research Part F: Traffic Psychology and Behaviour, 66, 368-378.
- erma(signal: ndarray, W1: float = 0.111, W2: float = 0.667, offset: float = 0.02, refractory: float = 0.3) ndarray[source]¶
Extract beat locations from PPG data based on the Elgendi et al. (2013) algorithm using event-related moving averages and dynamic thresholding.
- Parameters:
signal (array_like) – An array containing the PPG signal.
W1 (float, optional) – The window size for peak detection in seconds; by default 111 ms.
W2 (float, optional) – The window size for beat detection in seconds; by default, 667 ms.
offset (float, optional) – Offset duration adjustment; by default, 20 ms.
refractory (float, optional) – Refractory period to avoid double detection of the same beat (i.e., the minimum delay between consecutive systolic peaks); by default, 300 ms.
- Returns:
ppg_beats – An array containing indices of PPG pulse onsets.
- Return type:
array_like
References
Elgendi, M., Norton, I., Brearley, M., Abbott, D., & Schuurmans, D. (2013). Systolic peak detection in acceleration photoplethysmograms measured from emergency responders in tropical conditions. PLoS ONE, 8(10), e76585.
- class physioview.pipeline.PPG.Filters(fs: int)[source]¶
A class for filtering raw photoplethysmography (PPG) data.
Parameters/Attributes¶
- fsint
The sampling rate of the PPG signal.
- baseline_wander(signal: ndarray, cutoff: float = 0.5, order: int = 2) ndarray[source]¶
Apply a high-pass filter to remove baseline wander from PPG data.
- Parameters:
signal (array_like) – An array containing the input PPG signal to be filtered.
cutoff (float) – The cut-off frequency at which frequencies below this value in the PPG signal are attenuated; by default, 0.5 Hz.
order (int) – The filter order, i.e., the number of samples required to produce the desired filtered output; by default, 2.
- filter_signal(signal: ndarray, lowcut: float = 0.5, highcut: float = 10, order: int = 4, window_len: float = 0.5) ndarray[source]¶
Filter out baseline drift, motion artifact, and powerline interference from PPG data and smooth out the signal for further processing.
- Parameters:
signal (array_like) – An array containing the input PPG signal to be filtered.
lowcut (int, float) – The cut-off frequency at which frequencies below this value in the signal are attenuated; by default, 0.5 Hz.
highcut (int, float) – The cut-off frequency at which frequencies above this value in the signal are attenuated; by default, 10 Hz.
order (int) – The filter order, i.e., the number of samples required to produce the desired filtered output; by default, 4.
window_len (int) – The size of the moving average window, in seconds.
- Returns:
filtered – An array containing the filtered PPG data.
- Return type:
array_like
References
Liang, Y., Elgendi, M., Chen, Z., et al. (2018). An optimal filter for short photoplethysmogram signals. Scientific Data, 5, 180076.
Notes
This function uses a 4th-order Chebyshev Type II filter according to results of the study by Liang et al. (2018) and a moving average filter using convolution. This is the default filter used in the Heartview Dashboard.
- moving_average(signal: ndarray, window_len: int) ndarray[source]¶
Smooth a PPG signal using a moving average filter.
- Parameters:
signal (array_like) – An array containing the input PPG signal to be filtered.
window_len (int) – The size of the moving average window, in seconds.
- Returns:
filtered – An array containing the filtered PPG signal.
- Return type:
array_like
EDA¶
- class physioview.pipeline.EDA.Filters(fs)[source]¶
A class for filtering raw electrodermal activity (EDA) data.
Parameters/Attributes¶
- fsint
The sampling rate of the EDA signal.
- filter_signal(signal: ndarray, fs: int = 4, cutoff: float = 0.35, filter_length: int = 2057, window_type: Literal['hamming', 'hann', 'blackman'] = 'hamming') ndarray[source]¶
Apply a FIR low-pass filter to an EDA signal.
- Parameters:
signal (array_like) – An array containing the raw EDA signal to be filtered.
fs (int, optional) – The sampling rate of the signal in Hz; by default, 4 Hz.
cutoff (float, optional) – The cut-off frequency above which frequencies are attenuated; by default, 0.35 Hz.
filter_length (int, optional) – The length of the FIR filter (number of taps); by default, 2057. Larger values give smoother filtering but increase computation and delay.
window_type ({'hamming', 'hann', 'blackman'}, optional) – The type of window function to use for FIR design; by default, ‘hamming’.
- Returns:
filtered – An array containing the filtered EDA signal.
- Return type:
array_like
References
Kleckner, I.R., Jones, R.M., Wilder-Smith, O., Wormwood, J.B., Akcakaya, M., Quigley, K.S., … & Goodwin, M.S. (2017). Simple, transparent, and flexible automated quality assessment procedures for ambulatory electrodermal activity data. IEEE Transactions on Biomedical Engineering, 65(7), 1460-1467.
Notes
This is the default filter used in the PhysioView Dashboard.
- lowpass_butter(signal, cutoff=2, order=3)[source]¶
Filter an EDA signal with a Butterworth low-pass filter.
- Parameters:
signal (array_like) – An array containing the raw EDA signal.
cutoff (int, float) – The cut-off frequency at which frequencies above this value in the EDA signal are attenuated; by default, 2 Hz.
order (int) – The filter order, i.e., the number of samples required to produce the desired filtered output; by default, 3.
- Returns:
filtered – An array containing the filtered EDA signal.
- Return type:
array_like
- lowpass_elliptic(signal: ndarray, cutoff: float = 1.0, order: int = 4, rp: float = 1, rs: float = 40) ndarray[source]¶
Apply an elliptic low-pass filter to an EDA signal.
- Parameters:
signal (array_like) – An array containing the raw EDA signal to be filtered.
cutoff (float, optional) – The cutoff frequency in Hz; by default, 1 Hz.
order (int, optional) – The filter order; by default, 4.
rp (float, optional) – Maximum ripple (in dB) allowed in the passband; by default, 1 dB.
rs (float, optional) – Minimum attenuation (in dB) required in the stopband; by default, 40 dB.
- Returns:
filtered – An array containing the filtered EDA signal.
- Return type:
array_like
- lowpass_gaussian(signal, cutoff: float = 1.0)[source]¶
Apply a frequency-domain Gaussian low-pass filter to an EDA signal.
- Parameters:
signal (array_like) – An array containing the raw EDA signal.
cutoff (float, optional) – The desired cutoff frequency in Hz; by default, 1.0 Hz.
- Returns:
filtered – An array containing the low-pass filtered EDA signal.
- Return type:
array_like
References
Nabian, M., et al. (2018). An open-source feature extraction tool for the analysis of peripheral physiological data. IEEE Journal of Translational Engineering in Health and Medicine, 6, 1-11.
- moving_average(signal, window_len)[source]¶
Apply a moving average filter to an EDA signal.
- Parameters:
signal (array_like) – An array containing the raw EDA signal.
window_len (int or float) – The moving average window size, in seconds.
- Returns:
ma – An array containing the moving average of the EDA signal.
- Return type:
array_like
- physioview.pipeline.EDA.compute_features(signal: ndarray, fs: int, window_size: int = 180, step_size: int = 60) DataFrame[source]¶
Compute statistical EDA features from phasic and tonic components of an EDA signal.
- Parameters:
signal (array_like) – An array containing the raw EDA signal.
fs (int) – The sampling rate of the EDA signal.
window_size (int, optional) – The size of the window, in seconds, over which EDA features are computed; by default, 180.
step_size (int, optional) – The time interval, in seconds, at which EDA features are computed; by default, 60.
- physioview.pipeline.EDA.compute_tonic_scl(signal: ndarray, fs: int = 4, seg_size: int | None = None) float | ndarray[source]¶
Compute the tonic skin conductance level (SCL) as the mean of the EDA signal over a given segment, while excluding intervals corresponding to skin conductance responses (SCRs).
- Parameters:
signal (array_like) – An array containing the filtered EDA signal.
fs (int, optional) – The sampling rate of the EDA signal; by default, 4 Hz.
seg_size (int, optional) – The segment size (in seconds) of the EDA signal; by default, None. If given, the EDA signal is divided into non-overlapping segments of this length and a tonic SCL is computed for each segment. If None, the tonic SCL is computed once across the whole signal.
- Returns:
tonic_scl – The tonic skin conductance level (SCL).
- Return type:
float or np.ndarray
Notes
SCRs are detected based on amplitude and temporal criteria, and the data from their onset through recovery are omitted from the calculation. If no SCRs are detected, the tonic SCL is equivalent to the mean of the entire signal.
- physioview.pipeline.EDA.decompose_eda(signal: ndarray, fs: int, show_progress: bool = True) tuple[source]¶
Extract the phasic and tonic components of an electrodermal activity (EDA) signal using the convex optimization approach by Greco et al. (2015). This is an alias function for _cvxEDA() in this module.
- Parameters:
signal (array_like) – An array containing the EDA signal.
fs (float) – The sampling rate of the EDA signal.
- Returns:
phasic (array_like) – The phasic component (fast-moving changes) of the EDA signal.
tonic (array_like) – The tonic component (slow-moving changes) of the EDA signal.
References
Greco, A., Valenza, G., Lanata, A., Scilingo, E. P., & Citi, L. (2016). cvxEDA: A convex optimization approach to electrodermal activity processing. IEEE Transactions on Biomedical Engineering, 63(4), 797–804.
- physioview.pipeline.EDA.detect_scr_peaks(phasic: ndarray | Series, smooth_size: int = 20, min_amp_thresh: float = 0.1, min_peak_amp: float | None = None) ndarray[source]¶
Detect skin conductance response (SCR) peaks in a phasic EDA signal using the Nabian et al. (2018) approach.
- Parameters:
phasic (array-like) – Phasic component of EDA signal.
smooth_size (int, optional) – The size of Bartlett window for smoothing derivative; by default, 20.
min_amp_thresh (float, optional) – The minimum SCR amplitude threshold, relative to the max detected amplitude; by default, 0.1 (i.e., 10%).
min_peak_amp (float, optional) – The minimum amplitude for a SCR peak to be considered valid; by default, None.
- Returns:
peaks – An array containing indices of detected SCR peaks.
- Return type:
np.ndarray
References
Nabian, M., et al. (2018). An open-source feature extraction tool for the analysis of peripheral physiological data. IEEE Journal of Translational Engineering in Health and Medicine, 6, 1-11.
- physioview.pipeline.EDA.resample(signal: ndarray, fs: int, new_fs: int) ndarray[source]¶
Resample a signal to a new sampling frequency using polyphase filtering.
- Parameters:
signal (array_like) – The input signal (1D array).
fs (int) – The original sampling frequency of the signal.
new_fs (int) – The desired sampling frequency.
- Returns:
rs – The resampled signal.
- Return type:
array_like
ACC¶
- physioview.pipeline.ACC.compute_auc(df, signal, fs, seg_size=60, ts_col=None, norm=None, rolling_window=None, rolling_step=15)[source]¶
Compute the area-under-the-curve of acceleration magnitude across a given window size using Riemann sums.
- Parameters:
df (pandas.DataFrame) – The DataFrame containing acceleration magnitude values.
signal (str) – The name of the column containing the acceleration magnitude.
fs (int, float) – The sampling rate.
seg_size (int) – The segment size (in seconds) by which the areas are computed; by default, 60.
ts_col (str, optional) – The name of the column containing timestamps.
norm (str, optional) – The method with which to normalize the magnitude values; by default, None. Possible options include: ‘minmax’ or ‘zscore’.
rolling_window (int, optional) – The size, in seconds, of the sliding window across which to compute the AUC values; by default, None.
rolling_step (int, optional) – The step size, in seconds, of the sliding windows; by default, 15.
- Returns:
auc – A DataFrame containing the AUC, its normalized value of the acceleration magnitude, and corresponding timestamp for each window.
- Return type:
pandas.DataFrame
Notes
If a value is given in the rolling_window parameter, the rolling window approach will override the segmented approach, ignoring any seg_size value.
- physioview.pipeline.ACC.compute_magnitude(x, y, z)[source]¶
Compute the magnitude of a 3-axis accelerometer signal.
- Parameters:
x (array_like) – An array containing the x-axis accelerometer data.
y (array_like) – An array containing the y-axis accelerometer data.
z (array_like) – An array containing the z-axis accelerometer data.
- Returns:
magnitude – A series of acceleration magnitude values.
- Return type:
pandas.Series
- physioview.pipeline.ACC.convert_acc(signal, sensitivity, fs)[source]¶
Convert an acceleration signal from G-force to units of m/s^2.
- Parameters:
signal (array_like) – An array containing the acceleration signal.
sensitivity (int) – The G-force sensitivity level of the accelerometer (e.g., 2 for ± 2g).
fs (int) – The sampling rate of the accelerometer recording.
- Returns:
ms2 – An array containing the converted acceleration signal.
- Return type:
array_like
Signal Quality Assessment¶
- class physioview.pipeline.SQA.Cardio(fs: int)[source]¶
A class for signal quality assessment on cardiovascular data, including electrocardiograph (ECG) or photoplethysmograph (PPG) data.
Parameters/Attributes¶
- fsint
The sampling rate of the cardiovascular data.
- compute_metrics(data: DataFrame, beats_ix: ndarray | None = None, artifacts_ix: ndarray | None = None, ts_col: str | None = None, seg_size: int = 60, min_hr: float = 40, rolling_window: int | None = None, rolling_step: int = 15, show_progress: bool = True) DataFrame[source]¶
Compute all SQA metrics for cardiovascular data by segment or moving window. Metrics per segment or moving window include numbers of detected, expected, missing, and artifactual beats and percentages of missing and artifactual beats.
- Parameters:
data (pandas.DataFrame) – A DataFrame containing pre-processed ECG or PPG data.
beats_ix (array_like, optional) – An array containing the indices of detected beats. Required if data does not contain a “Beat” column with beat occurrences.
artifacts_ix (array_like, optional) – An array containing the indices of artifactual beats. Required if data does not contain an “Artifact” column with artifactual beat occurrences.
ts_col (str, optional) – The name of the column containing timestamps; by default, None. If a string value is given, the output will contain a timestamps column.
seg_size (int, optional) – The segment size in seconds; by default, 60.
min_hr (float, optional) – The minimum heart rate against which the number of detected beats is considered valid; by default, 40.
rolling_window (int, optional) – The size, in seconds, of the sliding window across which to compute the SQA metrics; by default, None.
rolling_step (int, optional) – The step size, in seconds, of the sliding windows; by default, 15.
show_progress (bool, optional) – Whether to display a progress bar while the function runs; by default, True.
- Returns:
metrics – A DataFrame with all computed SQA metrics per segment.
- Return type:
pandas.DataFrame
Notes
If a value is given in the rolling_window parameter, the rolling window approach will override the segmented approach, ignoring any seg_size value.
Examples
>>> from physioview.pipeline import SQA >>> sqa = SQA.Cardio(fs = 1000) >>> artifacts_ix = sqa.identify_artifacts(beats_ix, method = 'cbd') >>> cardio_qa = sqa.compute_metrics(ecg, beats_ix, artifacts_ix, ... ts_col = 'Timestamp', ... seg_size = 60, min_hr = 40)
- correct_interval(beats_ix: ndarray, initial_hr: float | Literal['auto'] = 'auto', prev_n: int = 6, min_bpm: int = 40, max_bpm: int = 200, hr_estimate_window: int = 6, print_estimated_hr: bool = True, short_threshold: float = 0.75, long_threshold: float = 1.375, extra_threshold: float = 1.625) tuple[ndarray, DataFrame, DataFrame, DataFrame][source]¶
Correct artifactual beats in cardiovascular data based on the approach by Hegarty-Craver et al. (2018).
- Parameters:
beats_ix (array_like) – An array containing the indices of detected beats.
initial_hr (float or {'auto'}, optional) – The heart rate value for the first interbeat interval (IBI) to be validated against; by default, ‘auto’ (i.e., the value is determined automatically).
prev_n (int, optional) – The number of preceding IBIs to validate against; by default, 6.
min_bpm (int, optional) – The minimum possible heart rate in beats per minute (bpm); by default, 40.
max_bpm (int, optional) – The maximum possible heart rate in beats per minute (bpm); by default, 200.
hr_estimate_window (int, optional) – The window size for estimating the heart rate; by default, 6.
print_estimated_hr (bool, optional) – Whether to print the estimated heart rate; by default, True.
short_threshold (float, optional) – The threshold for short IBIs; by default, 24/32.
long_threshold (float, optional) – The threshold for long IBIs; by default, 44/32.
extra_threshold (float, optional) – The threshold for extra long IBIs; by default, 52/32.
- Returns:
beats_ix_corrected (array_like) – An array containing the indices of corrected beats.
corrected_ibis (array_like) – An array containing the indices of corrected IBIs.
original (pandas.DataFrame) – A DataFrame containing the original IBIs (millisecond-based and index-based) and beat indices.
corrected (pandas.DataFrame) – A DataFrame containing the corrected IBIs (millisecond-based and index-based) and beat indices.
References
Hegarty-Craver, M. et al. (2018). Automated respiratory sinus arrhythmia measurement: Demonstration using executive function assessment. Behavioral Research Methods, 50, 1816–1823.
- get_artifacts(data: DataFrame, beats_ix: ndarray, artifacts_ix: ndarray, seg_size: int = 60, ts_col: str | None = None) DataFrame[source]¶
Summarize the number and proportion of artifactual beats per segment.
- Parameters:
data (pandas.DataFrame) – A DataFrame containing the pre-processed ECG or PPG data.
beats_ix (array_like) – An array containing the indices of detected beats.
artifacts_ix (array_like) – An array containing the indices of artifactual beats. This is outputted from SQA.Cardio.identify_artifacts().
seg_size (int) – The size of the segment in seconds; by default, 60.
ts_col (str, optional) – The name of the column containing timestamps; by default, None. If a string value is given, the output will contain a timestamps column.
- Returns:
artifacts – A DataFrame with the number and proportion of artifactual beats per segment.
- Return type:
pandas.DataFrame
See also
SQA.Cardio.identify_artifactsIdentify artifactual beats using both or either of the methods.
- get_corrected(beats_ix: ndarray, seg_size: int = 60, initial_hr: float | Literal['auto'] = 'auto', prev_n: int = 6, min_bpm: int = 40, max_bpm: int = 200, hr_estimate_window: int = 6, print_estimated_hr: bool = True, short_threshold: float = 0.75, long_threshold: float = 1.375, extra_threshold: float = 1.625) tuple[DataFrame, DataFrame, DataFrame][source]¶
Get the corrected interbeat intervals (IBIs) and beat indices.
- Parameters:
data (pandas.DataFrame) – A DataFrame containing the pre-processed ECG or PPG data.
beats_ix (array_like) – An array containing the indices of detected beats.
seg_size (int) – The size of the segment in seconds; by default, 60.
initial_hr (float or {'auto'}, optional) – The heart rate value for the first interbeat interval (IBI) to be validated against; by default, ‘auto’ (i.e., the value is determined automatically).
prev_n (int, optional) – The number of preceding IBIs to validate against; by default, 6.
min_bpm (int, optional) – The minimum possible heart rate in beats per minute (bpm); by default, 40.
max_bpm (int, optional) – The maximum possible heart rate in beats per minute (bpm); by default, 200.
hr_estimate_window (int, optional) – The window size for estimating the heart rate; by default, 6.
print_estimated_hr (bool, optional) – Whether to print the estimated heart rate; by default, True.
short_threshold (float, optional) – The threshold for short IBIs; by default, 24/32.
long_threshold (float, optional) – The threshold for long IBIs; by default, 44/32.
extra_threshold (float, optional) – The threshold for extra long IBIs; by default, 52/32.
- Returns:
original (pandas.DataFrame) – A data frame containing the original IBIs and beat indices.
corrected (pandas.DataFrame) – A data frame containing the corrected IBIs and beat indices.
combined (pandas.DataFrame) – A data frame containing the summary of flags in each segment.
- get_missing(data: DataFrame, beats_ix: ndarray | None = None, artifacts_ix: ndarray | None = None, seg_size: int = 60, ts_col: str | None = None) DataFrame[source]¶
Summarize the number and proportion of missing beats per segment.
- Parameters:
data (pandas.DataFrame) – The DataFrame containing the pre-processed ECG or PPG data.
beats_ix (array_like, optional) – An array containing the indices of detected beats. Required if data doesn’t contain a “Beat” column.
artifacts_ix (array_like, optional) – An array containing the indices of artifactual beats. Required if data doesn’t contain an “Artifact” column .
seg_size (int, optional) – The size of the segment in seconds; by default, 60.
ts_col (str, optional) – The name of the column containing timestamps; by default, None. If a string value is given, the output will contain a timestamps column.
- Returns:
missing – A DataFrame with detected, expected, and missing numbers of beats per segment.
- Return type:
pandas.DataFrame
- get_seconds(data: DataFrame, beats_ix: ndarray, ts_col: str | None = None, show_progress: bool = True) DataFrame[source]¶
Get instantaneous (second-by-second) HR, IBI, and beat counts from ECG or PPG data according to the approach by Graham (1978).
- Parameters:
data (pandas.DataFrame) – The DataFrame containing the pre-processed ECG or PPG data.
beats_ix (array-like) – An array containing the indices of detected beats.
ts_col (str, optional) – The name of the column containing timestamps; by default, None. If a string value is given, the output will contain a timestamps column.
show_progress (bool, optional) – Whether to display a progress bar while the function runs; by default, True.
- Returns:
interval_data – A DataFrame containing instantaneous HR and IBI values.
- Return type:
pandas.DataFrame
Notes
Rows with NaN values in the resulting DataFrame interval_data denote seconds during which no beats in the data were detected.
References
Graham, F. K. (1978). Constraints on measuring heart rate and period sequentially through real and cardiac time. Psychophysiology, 15(5), 492–495.
- identify_artifacts(beats_ix: ndarray, method: Literal['hegarty', 'cbd', 'both'], initial_hr: float | Literal['auto'] | None = None, prev_n: int | None = None, neighbors: int | None = None, tol: float | None = None) ndarray[source]¶
Identify locations of artifactual beats in cardiovascular data based on the criterion beat difference approach by Berntson et al. (1990), the Hegarty-Craver et al. (2018) approach, or both.
- Parameters:
beats_ix (array_like) – An array containing the indices of detected beats.
method ({'hegarty', 'cbd', 'both'}) – The artifact identification method for identifying artifacts. This must be ‘hegarty’, ‘cbd’, or ‘both’.
initial_hr (float, or 'auto', optional) – The heart rate value for the first interbeat interval (IBI) to be validated against; by default, ‘auto’ for automatic calculation using the mean heart rate value obtained from six consecutive IBIs with the smallest average successive difference. Required for the ‘hegarty’ method.
prev_n (int, optional) – The number of preceding IBIs to validate against; by default, 6. Required for ‘hegarty’ method.
neighbors (int, optional) – The number of surrounding IBIs with which to derive the criterion beat difference score; by default, 5. Required for ‘cbd’ method.
tol (float, optional) – A configurable hyperparameter used to fine-tune the stringency of the criterion beat difference test; by default, 1. Required for ‘cbd’ method.
- Returns:
artifacts_ix – An array containing the indices of identified artifact beats.
- Return type:
array_like
Notes
The source code for the criterion beat difference test is from work by Hoemann et al. (2020).
References
Berntson, G., Quigley, K., Jang, J., Boysen, S. (1990). An approach to artifact identification: Application to heart period data. Psychophysiology, 27(5), 586–598.
Hegarty-Craver, M. et al. (2018). Automated respiratory sinus arrhythmia measurement: Demonstration using executive function assessment. Behavioral Research Methods, 50, 1816–1823.
Hoemann, K. et al. (2020). Context-aware experience sampling reveals the scale of variation in affective experience. Scientific Reports, 10(1), 1–16.
- plot_artifact(sqa_metrics: DataFrame, invalid_thresh: int = 30, title: str | None = None) Figure[source]¶
Plot detected and artifact beat counts.
- Parameters:
sqa_metrics (pandas.DataFrame) – The DataFrame containing SQA metrics per segment.
invalid_thresh (int, float) – The minimum number of beats detected for a segment to be considered valid; by default, 30.
title (str, optional) – The title of the plot.
- Returns:
fig – A Plotly bar chart of detected and missing beat counts.
- Return type:
plotly.graph_objects.Figure
- plot_missing(sqa_metrics: DataFrame, invalid_thresh=30, title=None) Figure[source]¶
Plot detected and missing beat counts.
- Parameters:
sqa_metrics (pandas.DataFrame) – The DataFrame containing SQA metrics per segment.
invalid_thresh (int, float) – The minimum number of beats detected for a segment to be considered valid; by default, 30.
title (str, optional) – The title of the plot.
- Returns:
fig – A Plotly bar chart of detected and missing beat counts.
- Return type:
plotly.graph_objects.Figure
- class physioview.pipeline.SQA.EDA(fs: int, eda_min: float = 0.2, eda_max: float = 40, eda_max_slope: float = 5, temp_min: float = 20, temp_max: float = 40, invalid_spread_dur: float = 2.5)[source]¶
A class for signal quality assessment on electrodermal activity (EDA) data.
Parameters/Attributes¶
- fsint
The sampling rate of the EDA data.
- eda_minfloat, optional
The minimum acceptable value for EDA data in microsiemens; by default, 0.05 uS.
- eda_maxfloat, optional
The maximum acceptable value for EDA data in microsiemens; by default, 60 uS.
- eda_max_slopefloat, optional
The maximum slope of EDA data in microsiemens per second; by default, 5 uS/sec.
- temp_minfloat, optional
The minimum acceptable temperature in degrees Celsius; by default, 20.
- temp_maxfloat, optional
The maximum acceptable temperature in degrees Celsius; by default, 40.
- invalid_spread_durfloat, optional
The transition radius for artifacts in seconds; by default, 2.
- compute_metrics(signal: ndarray, temp: ndarray | None = None, preprocessed: bool = True, peaks_ix: ndarray | None = None, seg_size: int = 60, rolling_window: int | None = None, rolling_step: int = 15, show_progress: bool = True) DataFrame[source]¶
Assess the quality of electrodermal activity (EDA) data using the rules defined by Kleckner et al. (2017). The method identifies valid and invalid data points and computes rule-specific quality metrics (e.g., proportions of out-of-range points, excessive slopes, temperature violations, and spread-invalid counts), either by segment or across sliding windows.
- Parameters:
signal (array_like) – An array containing the EDA signal in microsiemens.
temp (array_like, optional) – An optional array containing temperature data in Celsius; by default, None.
preprocessed (boolean, optional) – Whether filtered EDA data is being inputted; by default, True.
peaks_ix (array_like, optional) – An optional array containing locations of SCR peaks; by default, None. If provided, an ‘N SCRs’ metric is included in the output.
seg_size (int) – The segment size in seconds; by default, 60.
rolling_window (int, optional) – The size, in seconds, of the sliding window across which to compute the EDA SQA metrics; by default, None.
rolling_step (int, optional) – The step size, in seconds, of the sliding windows; by default, 15.
show_progress (bool, optional) – Whether to show a progress bar; by default, True.
- Returns:
metrics – A DataFrame containing EDA quality assessment metrics by segment or sliding window.
- Return type:
pd.DataFrame
References
Kleckner, I.R., Jones, R. M., Wilder-Smith, O., Wormwood, J.B., Akcakaya, M., Quigley, K.S., … & Goodwin, M.S. (2017). Simple, transparent, and flexible automated quality assessment procedures for ambulatory electrodermal activity data. IEEE Transactions on Biomedical Engineering, 65(7), 1460-1467.
- get_quality_metrics(signal: ndarray, temp: ndarray | None = None, timestamps: ndarray | None = None) DataFrame[source]¶
Assess and flag rule violations of EDA quality based on the quality assessment procdure by Kleckner et al. (2017).
- Parameters:
signal (array_like) – The EDA signal in microsiemens.
temp (array_like, optional) – Temperature data in Celsius.
timestamps (array_like, optional) – Array of timestamps corresponding to each data point.
- Returns:
eda_quality – A DataFrame with the columns: - ‘Timestamp’ - ‘EDA’ - ‘Temp’ (if provided) - ‘Out of Range’ - ‘Excessive Slope’ - ‘Temp Out of Range’ (if provided)
- Return type:
pd.DataFrame
References
Kleckner, I.R., Jones, R. M., Wilder-Smith, O., Wormwood, J.B., Akcakaya, M., Quigley, K.S., … & Goodwin, M.S. (2017). Simple, transparent, and flexible automated quality assessment procedures for ambulatory electrodermal activity data. IEEE Transactions on Biomedical Engineering, 65(7), 1460-1467.
- get_validity_metrics(signal: ndarray, temp: ndarray | None = None, timestamps: ndarray | None = None, preprocessed: bool = True) DataFrame[source]¶
Assess and flag valid and invalid EDA data points.
- Parameters:
signal (array_like) – An array containing the EDA signal in microsiemens.
temp (array_like, optional) – An array containing temperature data in Celsius.
timestamps (array_like, optional) – An array of timestamps corresponding to each data point.
preprocessed (bool, optional) – Whether filtered EDA data is being inputted; by default, True. If False, an FIR low-pass filter is applied.
- Returns:
eda_validity – A DataFrame with the columns: - ‘Timestamp’ (if provided) - ‘EDA’ - ‘Temp’ (if provided) - ‘Valid’ (1 if valid, NaN otherwise) - ‘Invalid’ (1 if invalid, NaN otherwise)
- Return type:
pd.DataFrame
Device-Specific Methods¶
Actiwave Cardio¶
- class physioview.physioview.Actiwave(file: str)[source]¶
A class for convenient preprocessing of data from the Actiwave Cardio device.
Parameters/Attributes¶
- filestr
The path of the Actiwave Cardio device file saved in European Data Format (.edf).
- get_acc_fs() float[source]¶
Get the sampling rate of accelerometer data from an Actiwave Cardio device.
- Returns:
fs – The sampling rate of the accelerometer recording.
- Return type:
int, float
- get_ecg_fs() float[source]¶
Get the sampling rate of ECG data from an Actiwave Cardio device.
- Returns:
fs – The sampling rate of the ECG recording.
- Return type:
int, float
- preprocess(time_aligned: bool = False) tuple[DataFrame, DataFrame] | DataFrame[source]¶
Preprocess electrocardiograph (ECG) and acceleration data from an Actiwave Cardio file.
- Parameters:
time_aligned (bool, optional) – Whether to time-align ECG and acceleration data based on the sampling rate of the ECG data; by default, False.
- Returns:
If time_aligned is False, returns a tuple (ecg, acc), where ecg is a DataFrame containing the preprocessed ECG data and acc is a DataFrame containing the preprocessed X-, Y-, and Z-axis acceleration data. If time_aligned is True, returns a single DataFrame containing time-synced ECG and acceleration data according to the ECG data’s timestamps.
- Return type:
tuple or pandas.DataFrame
Empatica E4¶
- class physioview.physioview.Empatica(file: str)[source]¶
A class to conveniently preprocess and assess quality of PPG and EDA data from Empatica E4 devices.
- file¶
The path of the Empatica archive file with a ‘.zip’ extension.
- Type:
str
- compute_sqa(dtype: str, seg_size: int = 60, initial_hr: int | float | Literal['auto'] = 'auto', min_hr: int = 40, min_eda: float = 0.2, max_eda: float = 40.0, rolling_window: int = None, rolling_step: int = 15, show_progress: bool = True) DataFrame | tuple[DataFrame, DataFrame][source]¶
Compute signal quality assessment metrics (SQA) PPG and/or EDA data from Empatica E4 devices.
- Parameters:
dtype (str) – The type of data whose SQA to compute. This value must be a string variation of ‘all’, ‘eda’, or ‘ppg’.
seg_size (int) – The segment size in seconds; by default, 60.
initial_hr (int, float, or 'auto', optional) – The heart rate value for the first interbeat interval (IBI) to be validated against; by default, ‘auto’ for automatic calculation using the mean heart rate value obtained from six consecutive IBIs with the smallest average successive difference.
min_hr (int, float) – The minimum acceptable heart rate against which the number of beats in the last partial segment will be compared; by default, 40.
min_eda (float, optional) – The minimum acceptable value for EDA data in microsiemens; by default, 0.2 uS.
max_eda (float, optional) – The maximum acceptable value for EDA data in microsiemens; by default, 40 uS.
rolling_window (int, optional) – The size, in seconds, of the sliding window across which to compute the SQA metrics; by default, None.
rolling_step (int, optional) – The step size, in seconds, of the sliding windows; by default, 15.
show_progress (bool, optional) – Whether to display a progress bar while the function runs; by default, True.
- Returns:
metrics – A DataFrame with all computed SQA metrics per segment.
- Return type:
pandas.DataFrame
Notes
If a value is given in the rolling_window parameter, the rolling window approach will override the segmented approach, ignoring any seg_size value.
- get_acc() Data[source]¶
Get the preprocessed acceleration data and its start time and sampling rate from the Empatica E4.
- Returns:
acc_data – An Empatica.Data object with the following attributes and corresponding accelerometer data variables:
- accpandas.DataFrame
A DataFrame containing the preprocessed BVP data with corresponding timestamps.
- startfloat
The Unix-formatted start time of the BVP recording.
- fsint
The sampling rate of the BVP data.
- Return type:
Empatica.Data object
- get_bvp() Data[source]¶
Get the raw blood volume pulse (BVP) data and its start time and sampling rate from the Empatica E4.
- Returns:
bvp_data – An Empatica.Data object with the following attributes and corresponding BVP data variables:
- bvppandas.DataFrame
A DataFrame containing the preprocessed BVP data with corresponding timestamps.
- startfloat
The Unix-formatted start time of the BVP recording.
- fsint
The sampling rate of the BVP data.
- Return type:
Empatica.Data object
- get_e4_beats(bvp_data: DataFrame, ibi_data: DataFrame, start_time: int, show_progress: bool = True) list[int][source]¶
Get locations of beats from Empatica E4 interbeat interval (IBI) data relative to its blood volume pulse (BVP) data.
- Parameters:
bvp_data (pandas.DataFrame) – A DataFrame containing the Empatica E4 BVP data, outputted from Empatica.preprocess().
ibi_data (pandas.DataFrame) – A DataFrame containing the Empatica E4 IBI data, outputted from Empatica.preprocess().
start_time (int) – The Unix timestamp of the recording start time.
show_progress (bool, optional) – Whether to display a progress bar while the function runs; by default, True.
- Returns:
e4_beats – A list containing the indices of beats extracted from IBI data of the Empatica E4.
- Return type:
list
- get_eda() Data[source]¶
Get the raw electrodermal activity (EDA) data and its recording start time and sampling rate from the Empatica E4.
- Returns:
eda_data – An Empatica.Data object with the following attributes and corresponding EDA data variables:
- edapandas.DataFrame
A DataFrame containing the preprocessed EDA data with corresponding timestamps.
- startfloat
The Unix-formatted start time of the EDA recording.
- fsint
The sampling rate of the EDA data.
- Return type:
Empatica.Data object
- get_hr() Data[source]¶
Get the preprocessed heart rate (HR) data, start time of the first HR measurement, and sampling rate from the Empatica E4.
- Returns:
hr_data – An Empatica.Data object with the following attributes and corresponding HR data variables:
- hrpandas.DataFrame
A DataFrame containing the preprocessed HR data with corresponding timestamps.
- startfloat
The Unix-formatted start time of the HR measurements.
- fsint
The sampling rate of the BVP data.
- Return type:
Empatica.Data object
- get_ibi() Data[source]¶
Get the preprocessed interbeat interval (IBI) data and the start time of the first interval from the Empatica E4.
- Returns:
ibi_data – An Empatica.Data object with the following attributes and corresponding IBI data variables:
- ibipandas.DataFrame
A DataFrame containing the preprocessed IBI data with corresponding timestamps.
- startint
The Unix-formatted start time of the IBI data.
- Return type:
Empatica.Data object
- get_temp() Data[source]¶
Get the raw skin temperature data and its recording start time and sampling rate from the Empatica E4.
- Returns:
temp_data – An Empatica.Data object with the following attributes and corresponding temperature data variables:
- temppandas.DataFrame
A DataFrame containing the preprocessed temperature data with corresponding timestamps.
- startfloat
The Unix-formatted start time of the temperature recording.
- fsint
The sampling rate of the temperature data.
- Return type:
Empatica.Data object
- plot_signals(segment: int = 1, seg_size: int = 60, interactive: bool = True, **kwargs) Figure[source]¶
Display a plot of a segment of signals recorded with the Empatica E4 device.
- Parameters:
segment (int, optional) – The number of the position of the segment to plot; by default, 1.
seg_size (int, optional) – The segment size in seconds; by default, 60.
interactive (bool, optional) – Whether to plot an interactive visualization; by default, True.
**kwargs (dict, optional) – Additional keyword arguments passed to the Plotly figure’s update_layout() method. This allows customizing attributes such as height, width, title, template, etc.
- Returns:
fig – If interactive is True, displays and returns an interactive Plotly figure containing the plotted signals. If interactive is False, displays a static figure and returns None.
- Return type:
plotly.graph_objects.Figure or None
Examples
>>> from physioview import physioview >>> e4 = physioview.Empatica('empatica_file.zip') >>> fig = e4.plot_signals( >>> interactive = True, template = 'simple_white')
- preprocess(time_aligned: bool = False) Data[source]¶
Preprocess all data from the Empatica E4.
- Parameters:
time_aligned (bool, optional) – Whether to time-align all data based on the signal with the highest sampling rate (i.e. blood volume pulse); by default, False.
- Returns:
data – An Empatica.Data object with the following attributes and corresponding preprocessed data:
- If time_aligned is False:
- accpandas.DataFrame
A DataFrame containing the preprocessed ACC data with corresponding timestamps.
- bvppandas.DataFrame
A DataFrame containing the preprocessed BVP data with corresponding timestamps.
- edapandas.DataFrame
A DataFrame containing the preprocessed EDA data with corresponding timestamps.
- hrpandas.DataFrame
A DataFrame containing the preprocessed HR data with corresponding timestamps.
- ibipandas.DataFrame
A DataFrame containing the preprocessed IBI data with corresponding timestamps and seconds elapsed since the start time of the IBI recording.
- temppandas.DataFrame
A DataFrame containing the preprocessed temperature data with corresponding timestamps.
- start_timefloat
The Unix-formatted start time of the E4 recording.
- bvp_fsfloat
The sampling rate of the BVP recording.
- eda_fsfloat
The sampling rate of the EDA recording.
- If time_aligned is True:
- hrvpandas.DataFrame
A DataFrame containing time-synced BVP, HR, IBI, and acceleration data.
- edapandas.DataFrame
A DataFrame containing time-synced EDA, temperature, and acceleration data.
- start_timefloat
The Unix-formatted start time of the E4 recording.
- bvp_fsfloat
The sampling rate of the BVP recording.
- eda_fsfloat
The sampling rate of the EDA recording.
- Return type:
Empatica.Data object
Examples
>>> from physioview import physioview >>> e4_archive = 'Sample_E4_Data.zip' >>> E4 = physioview.Empatica(e4_archive) >>> ALL_E4_DATA = E4.preprocess()
Other Signal Processing Functions¶
- physioview.physioview.compute_ibis(data: DataFrame, fs: int, beats_ix: ndarray, ts_col: str | None = None) DataFrame[source]¶
Compute interbeat intervals from beat locations in ECG or PPG data.
- Parameters:
data (pandas.DataFrame) – The DataFrame containing the preprocessed ECG/PPG data.
fs (int) – The sampling rate of the ECG/PPG data.
beats_ix (array_like) – An array of indices corresponding to beat occurrences.
ts_col (str) – The name of the column in data containing timestamp values; by default, None.
- Returns:
ibi – A DataFrame containing timestamps and IBI values.
- Return type:
pandas.DataFrame
Examples
>>> import physioview >>> fs = 1024 # sampling rate >>> # Here, `ecg` is a DataFrame with a "Timestamp" column >>> beats_ix = physioview.ECGBeatDetectors(fs).manikandan(ecg['ECG']) >>> ibi = physioview.compute_ibis(ecg, fs, beats_ix, 'Timestamp')
- physioview.physioview.compute_hrv(data: DataFrame, fs: int, beats_ix: ndarray, window_size: int = 60, step_size: int = 1, ts_col: str | None = None) DataFrame[source]¶
Compute heart rate variability (HRV) metrics from beat locations in ECG or PPG data.
- Parameters:
data (pandas.DataFrame) – The DataFrame containing the preprocessed ECG/PPG data.
fs (int) – The sampling rate of the ECG/PPG data.
beats_ix (array_like) – An array of indices corresponding to beat occurrences.
window_size (int, optional) – The size of the windows over which HRV metrics are calculated; by default, 60.
step_size (int, optional) – The step size of the windows over which HRV metrics are calculated; by default, 1.
ts_col (str) – The name of the column in data containing timestamp values; by default, None.
- Returns:
hrv – A DataFrame containing HRV metrics.
- Return type:
pandas.DataFrame
Examples
>>> import physioview >>> fs = 1024 # sampling rate >>> # Here, `ecg` is a DataFrame with a "Timestamp" column >>> beats_ix = physioview.ECGBeatDetectors(fs).manikandan(ecg['ECG']) >>> # Compute HRV across 60-sec windows at 15-sec intervals >>> hrv = physioview.compute_hrv(ecg, fs, beats_ix, window_size = 15, >>> step_size = 15, ts_col = 'Timestamp')
- physioview.physioview.plot_signal(*, signal: DataFrame, signal_type: Literal['ECG', 'PPG', 'BVP', 'EDA', 'HR', 'RESP', 'TEMP'] | List[Literal['ECG', 'PPG', 'BVP', 'EDA', 'HR', 'RESP', 'TEMP']], axes: Tuple[str, str | List[str]], fs: int, peaks_map: Dict[str, str] | None = None, peaks_label: str | None = None, peaks_color: str | None = None, artifacts_map: Dict[str, str] | None = None, correction_map: Dict[str, str] | None = None, edits_map: Dict[str, str] | None = None, acc: DataFrame | None = None, ibi: DataFrame | None = None, ibi_corrected: DataFrame | None = None, hline: float | None = None, hline_name: str | None = None, seg_number: int | None = 1, seg_size: int | None = 60, n_segments: int | None = 1, fig_title: str | None = None, fig_height: int | None = 450) Figure[source]¶
Create a Plotly figure with primary and optional secondary physiological signals, including optional peaks and artifact markers.
- Parameters:
signal (pandas.DataFrame) – A DataFrame containing the primary signal data to plot.
signal_type (str or list of str) – The name(s) of the primary signal type(s) to plot. Possible values include ‘ECG’, ‘PPG’, ‘BVP’, ‘EDA’, ‘HR’, ‘RESP’, and ‘TEMP’.
axes (tuple of (str, str or list of str or dict)) –
A tuple specifying the x-axis column and the y-axis signal(s) to plot. The first element must be the name of the column in signal to use for the x-axis (e.g., ‘Timestamp’). The second element can take one of the following forms:
str : a single y-axis column to plot for one signal type. Example:
('Timestamp', 'EDA').list of str : multiple y-axis columns to plot for the same signal type. Example:
('Timestamp', ['EDA', 'Phasic']).dict : mapping of signal types to one or more y-axis columns, allowing multiple signal types to be plotted in separate subplots. Example:
('Timestamp', {'EDA': 'EDA', 'ECG': 'ECG'})or('Timestamp', {'EDA': ['EDA', 'Phasic'], 'ECG': ['ECG']})
fs (int) – The sampling rate (Hz) of the signal data.
peaks_map (dict of {str: str}, optional) – A dictionary mapping a signal type to the name of a column in signal containing binary (0/1) peak annotations; by default, None (i.e., no peaks are plotted). Example:
{'ECG': 'Beat'}will plot beat markers from the ‘Beat’ column on the ECG subplot.peaks_label (str, optional) – A label for the peak annotations on the signal subplot.
peaks_color (str, optional) – A color for the peak annotations on the signal subplot.
artifacts_map (dict of {str: str}, optional) – A dictionary mapping a signal type to the name of a column in signal containing binary (0/1) artifact annotations; by default, None (i.e., no artifacts are plotted). Example: {‘ECG’: ‘Artifact’} will plot artifact markers from the ‘Artifact’ column on the ECG subplot.
correction_map (dict of {str: str}, optional) – A dictionary mapping a signal type to the name of a column in signal containing binary (0/1) corrected beat annotations; by default, None (i.e., no corrected peaks are plotted). Example:
{`'ECG': 'Corrected'}will plot corrected beat markers from the ‘Corrected’ column on the ECG subplot.edits_map (dict of {str: str}, optional) –
A dictionary mapping a signal type to one or more edit types and their corresponding binary (0/1) annotation columns in signal; by default, None (i.e., no edits are plotted). Format:
{signal_type: {edit_label: column_name, ...}}.For example:
{'ECG': {'Added': 'Added Beat', 'Deleted': 'Deleted Beat', 'Unusable': 'Unusable'}}hline (float, optional) – If provided, plots a horizontal dotted line for a given reference amplitude value in the primary signal plot(s); by default, None.
hline_name (str, optional) – A label for the horizontal line; by default, None.
acc (pandas.DataFrame, optional) – DataFrame containing accelerometer data. If present, plotted as a secondary signal in the first subplot. Must contain ‘Magnitude’ or another numeric column.
ibi (pandas.DataFrame, optional) – DataFrame containing inter-beat interval (IBI) data. If present, plotted as a secondary signal in the last subplot. Must contain ‘IBI’ or another numeric column.
ibi_corrected (pandas.DataFrame, optional) – DataFrame containing auto-corrected interbeat interval (IBI) data. If present, plotted as a secondary signal in the last subplot. Must contain ‘IBI’ or another numeric column.
seg_number (int, optional) – The positional number of the segment to plot; by default, 1 (first segment).
seg_size (int, optional) – The length of each segment in seconds; by default, 60.
n_segments (int, optional) – The number of consecutive segments to plot starting from seg_number; by default, 1.
fig_title (str, optional) – The title of the figure.
fig_height (int, optional) – The height of the Plotly figure in pixels; by default, 450.
- Returns:
fig – The Plotly figure containing the plotted signals.
- Return type:
go.Figure
Examples
>>> from physioview import physioview >>> # data has columns: 'Timestamp', 'II', 'GSR', 'Beat', 'SCR', 'Artifact' >>> fig = physioview.plot_signal( >>> signal = data, >>> signal_type = ['ECG', 'EDA'], >>> axes = ('Timestamp', {'ECG': 'II', 'EDA': 'GSR'}), >>> fs = 256, >>> peaks_map = {'ECG': 'Beat', 'EDA', 'SCR'}, >>> artifacts_map = {'ECG': 'Artifact'}, >>> acc = acc_data, >>> ibi = ibi_data) >>> fig.show()
Beat Editor Functions¶
- physioview.physioview.write_beat_editor_file(data: DataFrame, fs: int, signal_col: str, beats_col: str, ts_col: str | None = None, filename: str | None = None, batch: bool = False, verbose: bool = True) None[source]¶
Create a JSON file for input to the Beat Editor.
- Parameters:
data (pandas.DataFrame) – A DataFrame containing the cardiac data. Must contain at least two columns with the cardiac signal and beat occurrences labeled as 1. Optionally, data can include a timestamp column (specified by ts_col) and an “Artifact” column, where artifact occurrences are labeled as 1. This allows the Beat Editor to visualize artifactual beat locations. If a timestamp columm is not provided, sample indices are used.
fs (int) – The sampling frequency of the signal.
signal_col (str) – The name of the column in data containing the cardiac signal.
beats_col (str) – The name of the column in data containing beat occurrences.
ts_col (str, optional) – The name of the column in data containing the timestamps. If not provided, timestamps are assumed to correspond to the DataFrame index.
filename (str, optional) – The name of the JSON file to write. If no filename is provided, the default filename ‘physioview_edit.json’ is used.
batch (bool, optional) – Whether input data is from a batch; by default, False. If True, the JSON file is written to a ‘beat-editor/data/batch’ subdirectory.
verbose (bool, optional) – If True, print a confirmation message after writing the JSON file.
- Return type:
None
- physioview.physioview.process_beat_edits(orig_data: DataFrame, edits: DataFrame) DataFrame[source]¶
Apply manual corrections from the Beat Editor output to original data. Edits are aligned either by sample index or timestamp, depending on the structure of orig_data.
- Parameters:
orig_data (pandas.DataFrame) – A DataFrame containing the original cardiac data inputted to the Beat Editor. Must contain a ‘Beat’ column and either: - ‘Timestamp’ column (datetime), or - ‘Sample’ column (integer sample indices)
edits (pandas.DataFrame) –
A DataFrame of edit instructions parsed from a Beat Editor _edited.json file. Must contain:
’editType’: one of ‘ADD’, ‘DELETE’, or ‘UNUSABLE’
either ‘x’ (edit location) or ‘from’ (start of unusable segment, with ‘to’ as the end), in the same time or sample units as orig_data
- Returns:
processed – A copy of orig_data with the following additional columns:
’Edited’: 1 where all final beats are, otherwise NaN
’Deleted Beat’: 1 where beats were deleted, otherwise NaN
’Added Beat’: 1 where beats were added, otherwise NaN
’Unusable’: 1 where segments are marked unusable, otherwise NaN
- Return type:
pandas.DataFrame