"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" "Biosensors","Cassey2016/PPG_Peak_Detection","main.m",".m","3040","58","% ========================================================================= % Below functions are the implementation for the comparison methods in % paper: % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, % David D. McManus, and Ki H. Chon. 2022. % ""A Real-Time PPG Peak Detection Method for Accurate Determination of % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 % % Please cite our paper if you used our implementation code. Thank you. % Author: Dong Han (dong.han@uconn.edu), 01/31/2022. % ========================================================================= % ------------------------------------------------------------------------- % Input: % PPG_raw_buffer: should be 30-sec segment. % fs_PPG_raw: the sampling frequency of the PPG_raw_buffer. % ------------------------------------------------------------------------- %% Preparation of PPG signal: addpath('.\func') [PPG_buffer,fs_PPG] = my_func_prep_PPG_buffer(PPG_raw_buffer,fs_PPG_raw); %% Method 1: implemented method 1-a V_max_flag = true; % true == upper peak detection. addpath('.\method_01_and_02'); output_upper_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper. %% Method 2: implemented method 1-b V_max_flag = false; % false == lower peak detection. output_lower_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper. %% Method 3 & 4: implemented method 2, it has two output peaks in ""output_Elgendi_1_2013"" delta = 0.5; % it was 0.1 as mentioned in the paper. But I think 0.5 works better (0.5 is in the billauer's website). addpath('.\method_03_and_04'); [output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(PPG_buffer, delta, fs_PPG); %% Method 5: first derivative and adaptive thresholding method in Li et al. [4] and Elgendi's paper [3] abpsig = resample(PPG_buffer,fs_abpsig,fs_PPG_buffer); % upsampling it to 125 Hz. addpath('.\method_05'); [output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(abpsig,fs_abpsig); %% Method 6: implemented method 4 fs_abp = 250; % Hz. abp = resample(PPG_buffer,fs_abp,fs_PPG); % upsampling it to 125 Hz. addpath('.\method_06'); [output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(abp,fs_abp); %% Method 7: event-related moving averages with dynamic threshold method in Elgendi et al.'s paper [3] addpath('.\method_07'); [output_Elgendi_4_2013] = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(-PPG_raw_buffer,fs_PPG_raw); %% Method 8 & 9: peak detection on Stationary Wavelet Transform of PPG signal fs_swt = 125; % Hz. PPG_swt = resample(PPG_buffer,fs_swt,fs_PPG); % upsampling it to 125 Hz. addpath('.\method_08_and_09'); [output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_swt,fs_swt);","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_07/my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV.m",".m","6505","156","function output_Elgendi_4_2013 = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(raw_PPG,fs_PPG) % ========================================================================= % This is my implementation of the method IV in this paper: % Elgendi, Mohamed, et al. % ""Systolic peak detection in acceleration photoplethysmograms measured from % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585. % % Implemented by Dong Han on 03/02/2020. % % Please cite our paper if you used this code: % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, % David D. McManus, and Ki H. Chon. 2022. % ""A Real-Time PPG Peak Detection Method for Accurate Determination of % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 % % Please cite our paper if you used our code. Thank you. % ========================================================================= %% pre-processing - bandpass filtering [b, a] = butter(2,[0.5 8]/(fs_PPG/2)); % 2nd order bandpass filter 0.5-8Hz; filtered_PPG = filtfilt(b, a, raw_PPG); % zero-phase filter. filtered_PPG = filtered_PPG ./ std(filtered_PPG); % normalizing data is very important for my peak detection. filtered_PPG = filtered_PPG - mean(filtered_PPG); debugging_plot_flag = false; % only for plotting debugging figures. % clip the signal by keeping the signal above zero. % I do not want to do this, so i will move all signal above zero. S_n = filtered_PPG; % ---- Not following the paper to clip signal but move all signal above zero: % if min(S_n) < 0 % Z_n = S_n - min(S_n); % elevate signal above zero. % else % % the minimum of S_n is still above zero, so do nothing. % Z_n = S_n; % end % ---- Following the paper: only keep the positive value: Z_n = S_n; Z_n(Z_n < 0) = 0; %% pre-processing - squaring y_n = (Z_n).^2; % element-wise power. %% feature extraction - generating potential blocks using two moving averages W_1 = round(0.111 * fs_PPG); % mentioned as the paper by brute-force search. % first moving average: % MA_peak = y_n; % for the beginning and ending signal, use the original signal. % for nn = 1+round(W_1/2):length(raw_PPG)-round(W_1/2) % temp_range = (nn-round(W_1/2)):(nn+round(W_1/2)); % MA_peak(nn) = sum(y_n(temp_range))/W_1; % end MA_peak = movmean(y_n,W_1); % second moving average: W_2 = round(0.667 * fs_PPG); % MA_beat = y_n; % for nn = 1+round(W_2/2):length(raw_PPG)-round(W_2/2) % temp_range = (nn-round(W_2/2)):(nn+round(W_2/2)); % MA_beat(nn) = sum(y_n(temp_range))/W_2; % end MA_beat = movmean(y_n,W_2); %% classification - thresholding beta = 0.02; % from the paper, by brute force search. z_bar = mean(y_n); alpha = beta * z_bar; % offset level. THR_1 = MA_beat + alpha; Blocks_Of_Interest = zeros(size(MA_peak)); % I initial it as zero. for nn = 1:length(MA_peak) if MA_peak(nn) > THR_1(nn) % I think it is THR_1(nn). Blocks_Of_Interest(nn) = 0.1; else % since I inital block of interest as zero, so I do not need to % assign zero again. end end % searh for onset and offset of each block. count_blocks = 0; block_onset = NaN(size(MA_peak)); block_offset = NaN(size(MA_peak)); if any(Blocks_Of_Interest > 0) % there is a block exist. for nn = 1:length(MA_peak) if nn == 1 && Blocks_Of_Interest(nn) > 0 % the first point is a block; count_blocks = count_blocks + 1; % since the block start from zero, I have to add the counter first. block_onset(count_blocks,1) = nn; elseif nn == length(MA_peak) && Blocks_Of_Interest(nn) > 0 % end with a block: % no need to add count_blocks; block_offset(count_blocks,1) = nn; else if nn > 1 if Blocks_Of_Interest(nn-1) == 0 && Blocks_Of_Interest(nn) > 0 % a jump means a new block. count_blocks = count_blocks + 1; block_onset(count_blocks,1) = nn; elseif Blocks_Of_Interest(nn-1) > 0 && Blocks_Of_Interest(nn) == 0 % a drop means the end of previous block. block_offset(count_blocks,1) = nn; end end end end else % there is no block existed. Check why. % keyboard; HR_Elgendi_4_2013 = 0; % there is no peak location. S_peaks = 1; output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,... 'PPG_peak_loc_Elgendi_4_2013',S_peaks,... 'HR_Elgendi_4_2013',HR_Elgendi_4_2013); return end block_onset(isnan(block_onset)) = []; % remove extra elements. block_offset(isnan(block_offset)) = []; % remove extra elements. if size(block_onset,1) ~= size(block_offset,1) % not same number of onset and offset, check here. keyboard; end if size(block_onset,1) ~= count_blocks keyboard; end S_peaks = NaN(count_blocks,1); THR_2 = W_1; for jj = 1:count_blocks block_idx = [block_onset(jj,1):block_offset(jj,1)]; [~,I] = max(y_n(block_idx)); S_peaks(jj,1) = block_onset(jj,1) + I - 1; end if debugging_plot_flag figure; plot(filtered_PPG);hold on; plot(S_peaks,y_n(S_peaks),'r.','markersize',10); plot(y_n); plot(MA_peak,'k:'); plot(MA_beat,'r--'); plot(THR_1,'g.-'); plot(Blocks_Of_Interest*max(y_n)*10,'color',[0.5,0.5,0.5]); % grey color. I want to make block more obvious. legend('filtered PPG','peaks', 'squared PPG with clip to zero', 'MA peak', 'MA beat','THR 1', 'Blocks of Interest'); end if isempty(S_peaks) HR_Elgendi_4_2013 = 0; % there is no peak location. S_peaks = 1; else HR_Elgendi_4_2013 = 60 * fs_PPG ./ diff(S_peaks); % calculate the HR. end output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,... 'PPG_peak_loc_Elgendi_4_2013',S_peaks,... 'HR_Elgendi_4_2013',HR_Elgendi_4_2013); end","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_01_and_02/my_peak_compare_Shin_2009.m",".m","21523","388","function [output_Shin_2009] = my_peak_compare_Shin_2009(raw_PPG,fs_PPG,V_max_flag) % ========================================================================= % This function is the implementation of this paper: % Shin, Hang Sik, Chungkeun Lee, and Myoungho Lee. % ""Adaptive threshold method for the peak detection of % photoplethysmographic waveform."" % Computers in biology and medicine % 39.12 (2009): 1145-1152. % % Implemented by: Dong Han, on 02/10/2020. % % Please cite our paper if you used this code: % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, % David D. McManus, and Ki H. Chon. 2022. % ""A Real-Time PPG Peak Detection Method for Accurate Determination of % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 % % Please cite our paper if you used our code. Thank you. % ========================================================================= debugging_plot_flag = false; % debugging plot. Can be false if don't want to plot anything. %% Section 2.4 PPG frequency analysis and filtering. % (1): high pass >= 0.5 Hz. [b, a] = butter(6,[0.5 20]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018 raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection. raw_PPG = raw_PPG - mean(raw_PPG); %% Section 2.5 & 2.6 Peak detection algorithm & Adaptive threshold detection % (1): bandpass filtering, no moving average filter or wavelet % decomposition. filtered_PPG = raw_PPG; Fs = fs_PPG; % % ===== interpolation to 1kHz of PPG: ===== % x = 1:length(filtered_PPG); % v = filtered_PPG; % % upsample_Fs = 250; % xq = 1:Fs/upsample_Fs:length(filtered_PPG); % vq1 = interp1(x,v,xq); % % filtered_PPG = vq1; % Fs = upsample_Fs; % upsampled to 1000 Hz. % figure % plot(x,v,'o',xq,vq1,':.'); % xlim([0 max(xq)]); % title('(Default) Linear Interpolation'); % (2): V_max % slope_k: k-th slope amplitude; % s_r: slope changing rate (empirically: V_max = -0.6); % V_n_1: previous peak amplitude; % std_PPG: standard deviation of entire PPG signal; % Fs: sampling frequency. filtered_PPG = filtered_PPG(:); slope_k = NaN(size(filtered_PPG)); % should be a column vector. peak_loc = NaN(size(filtered_PPG)); % the array to store PPG peak index. pk_idx = 1; % the counter of peaks. %% Section 2.7: Peak Correction refractory_period = 0.6 * Fs; % sec * sampling frequency, initial refractory period is 0.6 sec. temp_win_left = round(0.15 * Fs); % sec * sampling frequency. This is the search region for local minima or maxima detection. chose 0.15 sec because 0.3 sec == 200 BPM. temp_win_right = round(0.15 * Fs); if V_max_flag % doing upper peak detection. s_r = -0.6; else s_r = 0.6;%0.6; % not positive because my signal is zero mean. % I need to make all bottom signal positive, so I am moving them up. % move_filter_amp = min(filtered_PPG) * (-1); % filtered_PPG = filtered_PPG + move_filter_amp + std(raw_PPG); % move the lowest value more than zero. end slope_meet_PPG_flag = false; % mark if the slope meet PPG. slope_lower_PPG_flag = false; % mark if slope is lower than PPG, once PPG amp is lower than slope, mark it back. prev_slope = NaN; % First, I want to test not decreasing with PPG amplitude. if debugging_plot_flag % debugging plot figure; plot(filtered_PPG); hold on; end for kk = 1:length(filtered_PPG) % this is for debugging: if kk == 2 my_stop = 1; end if kk == 1 % initial the slope value if V_max_flag slope_k(1,1) = 0.2 * max(filtered_PPG); std_PPG = std(filtered_PPG); else slope_k(1,1) = 0.2 * min(filtered_PPG); % since my signal is zero mean, I start from the negative amp. % I added what I moved. std_PPG = -std(filtered_PPG); end % std_PPG = std(filtered_PPG); V_n_1 = slope_k(1,1); else if slope_meet_PPG_flag % slope has met PPG before. slope_k(kk,1) = filtered_PPG(kk,1); if V_max_flag % upper peak detection. if kk < 2 % in the second point of signal turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)); % we met local maximum. else turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)) & (slope_k(kk - 1,1) > slope_k(kk-2,1)); % we met local maximum. end else if kk < 2 % in the second point of signal turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)); % we met local minimum. else turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)) & (slope_k(kk - 1,1) < slope_k(kk-2,1)); % we met local minimum. end end if turn_point_flag % there is a turning point. if pk_idx > 1 % not the first peak % check local maxima or minima: if (kk - temp_win_left) < 1 temp_left = 1; else temp_left = kk - temp_win_left; end if (kk + temp_win_right) > length(filtered_PPG) temp_right = length(filtered_PPG); else temp_right = kk + temp_win_right; end temp_win = temp_left:temp_right; local_m_check = filtered_PPG(temp_win); if V_max_flag temp_m_idx = find(local_m_check > slope_k(kk - 1,1)); % check if there is another maximum than detected, remember use k-1. else temp_m_idx = find(local_m_check < slope_k(kk - 1,1)); % check if there is another minimum than detected end if isempty(temp_m_idx) % there is no more max or min than this peak if (kk - peak_loc(pk_idx-1,1) > refractory_period) % it is not the first peak, and the second peak is outside refractory period. It should be kk, because I have not assign the peak to the array. peak_loc(pk_idx,1) = kk-1; V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1);% previous peak amplitude %slope_k(kk-1,1); % update refractory period: refractory_period = 0.6 * (kk - peak_loc(pk_idx-1,1)); % current index minus peak location. update the refractory peroid before updating the peak counting. pk_idx = pk_idx + 1; % reset slope meet flag: slope_meet_PPG_flag = false; slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); % ---- for checking lower slope ------- temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs); if V_max_flag if temp_slope_check > 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end else if temp_slope_check < 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end end % ------------------------------------------- if V_max_flag temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal. else temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal. end if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude. slope_lower_PPG_flag = true; % slope is lower than PPG signal. prev_slope = slope_k(kk,1); % store the slope value now. slope_k(kk,1) = filtered_PPG(kk,1); end if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end else if (kk - peak_loc(pk_idx-1,1) <= refractory_period) % it is because of the refractory period that cause the no peak. It should be kk, because I have not assign the peak to the array. slope_k(kk,1) = filtered_PPG(kk,1);% from the fig.3(c) in the paper, I see they are using the signal amplitude, not slope. % no need to reset slope meet flag, waiting for % next turning point. if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end end end else % there are more peaks higher then current kk peak. if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end end else % the first peak, no need to check refractory period. % check local maxima or minima: if (kk - temp_win_left) < 1 temp_left = 1; else temp_left = kk - temp_win_left; end if (kk + temp_win_right) > length(filtered_PPG) temp_right = length(filtered_PPG); else temp_right = kk + temp_win_right; end temp_win = temp_left:temp_right; local_m_check = filtered_PPG(temp_win); if V_max_flag temp_m_idx = find(local_m_check > slope_k(kk-1,1)); % check if there is another maximum than detected, always detect previous peak. else temp_m_idx = find(local_m_check < slope_k(kk-1,1)); % check if there is another minimum than detected end if isempty(temp_m_idx) peak_loc(pk_idx,1) = kk-1; if pk_idx > 1 V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1); else V_n_1 = slope_k(kk-1,1);% previous peak amplitude %slope_k(kk-1,1); end pk_idx = pk_idx + 1; % reset slope meet flag: slope_meet_PPG_flag = false; slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); % ---- for checking lower slope ------- temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs); if V_max_flag if temp_slope_check > 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end else if temp_slope_check < 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end end % ------------------------------------------- if V_max_flag temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal. else temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal. end if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude. slope_k(kk,1) = filtered_PPG(kk,1); end if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end else % there are more peaks higher then current kk peak. if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end end % no need to calculate refractory period, because there is only one peak, at least two peaks can give this correctly: end else % turning point did not meet, so keep decreasing or % increasing the slope. % slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end end else % slope has not met PPG before. Keep decresing or increasing according to 'V_max_flag'. % if slope_lower_PPG_flag % if there is a slope lower than PPG before: % slope_k(kk,1) = prev_slope; % else slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); % ---- for checking lower slope ------- temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs); if V_max_flag if temp_slope_check > 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end else if temp_slope_check < 0 % upper peaks should be decreasing with negative slope. temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check; slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check; end end % ------------------------------------------- % end % if slope_k(kk,1) < filtered_PPG(kk,1) % if slope is below PPG signal, we will reset slope value to PPG amplitude. % slope_lower_PPG_flag = true; % slope is lower than PPG signal. % prev_slope = slope_k(kk,1); % store the slope value now. % slope_k(kk,1) = filtered_PPG(kk,1); % elseif slope_k(kk,1) > filtered_PPG(kk,1) % slope is higher. % slope_lower_PPG_flag = false; % prev_slope = NaN; % reset the prev value. % end % if slope_lower_PPG_flag ~= 1 % if slope was not lower than PPG. % % -------------- Check if two lines will meet ----------------- % PPG_x1 = kk - 1; % PPG_x2 = kk; % PPG_y1 = filtered_PPG(kk-1,1); % PPG_y2 = filtered_PPG(kk,1); % slope = s_r; % slope_y2 = slope_k(kk,1); % slope_y1 = slope_k(kk-1,1); % [meet_x] = my_slope_meet_PPG(PPG_x1,PPG_x2,PPG_y1,PPG_y2,slope,slope_y2,slope_y1); % % slope_meet_PPG_flag = (ceil(meet_x) == kk);%(slope_k(kk,1) - filtered_PPG(kk,1)) < 0.1; % 0.3 is a testing value. %slope_k(kk,1) == filtered_PPG(kk,1) % slope meets the PPG signal. % end if V_max_flag slope_meet_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) > filtered_PPG(kk - 1,1)); else slope_meet_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) < filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude. end % ------------------------------------------------------------- % I found I cannot use equal, because the PPG sampling % frequency is not so high. if slope_meet_PPG_flag slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude. else % don't need to do anything. if slope_lower_PPG_flag ~= 1 % there was no slope lower than PPG before. if V_max_flag slope_lower_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % beginning part has same amplitude, but the ending part slope is lower. else slope_lower_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude. end if slope_lower_PPG_flag prev_slope = slope_k(kk,1); % store the slope value now. slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude. end else % there was slope lower than PPG before. if V_max_flag temp_PPG_below_slope_flag = filtered_PPG(kk,1) < prev_slope; % upper peak detection, so PPG below slope. else temp_PPG_below_slope_flag = filtered_PPG(kk,1) > prev_slope; % lower peak detection, so PPG above slope. end if temp_PPG_below_slope_flag % PPG is lower than prev slope. slope_k(kk,1) = prev_slope; % stop tracking PPG amp. slope_lower_PPG_flag = false; % reset the lower PPG flag. prev_slope = NaN; else slope_k(kk,1) = filtered_PPG(kk,1); % keep tracking PPG amp. end end end if debugging_plot_flag % debugging plot plot(kk,slope_k(kk,1),'r.'); end end end end % ================== IMPORTANT: clean up NaN value ======================== peak_loc(isnan(peak_loc)) = []; % remove empty peak loc. if V_max_flag % doing upper peak detection. else % moving signal back. % filtered_PPG = filtered_PPG - move_filter_amp - std(raw_PPG); % move the lowest value more than zero. % slope_k = slope_k - move_filter_amp - std(raw_PPG); % move the slope as well. end if debugging_plot_flag % debugging plot plot(peak_loc,filtered_PPG(peak_loc),'ko'); end if isempty(peak_loc) HR_Shin_2009 = 0; % there is no peak location. peak_loc = 1; else HR_Shin_2009 = 60 * Fs ./ diff(peak_loc); % calculate the HR. end output_Shin_2009 = struct('PPG_peak_loc_Shin_2009',peak_loc,... 'slope_Shin_2009',slope_k,... 'filtered_PPG_Shin_2009',filtered_PPG,... 'HR_Shin_2009',HR_Shin_2009); end","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_05/my_func_ppg_peakdet_method_05_Elgendi_2013_method_II.m",".m","11993","412","function [output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(raw_PPG,fs_PPG) % ------------------------------------------------------------------------- % This peak detection function was mentioned in this paper: % Elgendi, Mohamed, et al. % ""Systolic peak detection in acceleration photoplethysmograms measured from % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585. % [onsetp,peakp,dicron,abpsig] = delineator(raw_PPG,fs_PPG); % ------------------------------------------------------------------------- if isempty(peakp) % there is no peak detected: HR_Elgendi_2_2013 = 0; % there is no peak location. peakp = 1; else HR_Elgendi_2_2013 = 60 * fs_PPG ./ diff(peakp); % calculate the HR. end output_Elgendi_2_2013 = struct('PPG_peak_loc_Elgendi_2_2013',peakp,... 'HR_Elgendi_2_2013',HR_Elgendi_2_2013,... 'filtered_PPG_Elgendi_2_2013',abpsig); end function [onsetp,peakp,dicron,abpsig] = delineator(abpsig,abpfreq) % Below was copied from Mathwords File Exchange ""Pulse Waveform Delineator"": % https://www.mathworks.com/matlabcentral/fileexchange/29484-pulse-waveform-delineator % This program is intended to delineate the fiducial points of pulse waveforms % Inputs: % abpsig: input as original pulse wave signals; % abpfreq: input as the sampling frequency; % Outputs: % onsetp: output fiducial points as the beginning of each beat; % peakp: output fiducial points as systolic peaks; % dicron: output fiducial points as dicrotic notches; % Its delineation is based on the self-adaptation in pulse waveforms, but % not in the differentials. % Reference: % BN Li, MC Dong & MI Vai (2010) % On an automatic delineator for arterial blood pressure waveforms % Biomedical Signal Processing and Control 5(1) 76-81. % LI Bing Nan @ University of Macau, Feb 2007 % Revision 2.0.5, Apr 2009 %Initialization peakIndex=0; onsetIndex=0; dicroIndex=0; stepWin=2*abpfreq; closeWin=floor(0.1*abpfreq); %invalide for pulse beat > 200BPM sigLen=length(abpsig); peakp=[]; onsetp=[]; dicron=[]; %lowpass filter at first coh=25; %cutoff frequency is 25Hz coh=coh*2/abpfreq; od=3; %3rd order bessel filter [B,A]=besself(od,coh); abpsig=filter(B,A,abpsig); abpsig=10*abpsig; abpsig=smooth(abpsig); %Compute differentials ttp=diff(abpsig); diff1(2:sigLen)=ttp; diff1(1)=diff1(2); diff1=100*diff1; clear ttp; diff1=smooth(diff1); if sigLen>12*abpfreq tk=10; elseif sigLen>7*abpfreq tk=5; elseif sigLen>4*abpfreq tk=2; else tk=1; end %Seek avaerage threshold in original signal if tk>1 %self-learning threshold with interval sampling tatom=floor(sigLen/(tk+2)); for ji=1:tk %search the slopes of abp waveforms sigIndex=ji*tatom; tempIndex=sigIndex+abpfreq; [tempMin,jk,tempMax,jl]=seeklocales(abpsig,sigIndex,tempIndex); tempTH(ji)=tempMax-tempMin; end abpMaxTH=mean(tempTH); else [tempMin,jk,tempMax,jl]=seeklocales(abpsig,closeWin,sigLen); abpMaxTH=tempMax-tempMin; end clear j*; clear t*; abpMaxLT=0.4*abpMaxTH; %Seek pulse beats by MinMax method % diffIndex=1; diffIndex=closeWin; %Avoid filter distortion while diffIndexstepWin % tempIndex=diffIndex-closeWin; tempIndex=diffIndex; abpMaxTH=0.6*abpMaxTH; if abpMaxTH<=abpMaxLT abpMaxTH=2.5*abpMaxLT; end break; end if (diff1(tempIndex-1)*diff1(tempIndex+1))<=0 %Candidate fiducial points if (tempIndex+5)<=sigLen jk=tempIndex+5; else jk=sigLen; end if (tempIndex-5)>=1 jj=tempIndex-5; else jj=1; end %Artifacts of oversaturated or signal loss? if (jk-tempIndex)>=5 for ttk=tempIndex:jk if diff1(ttk)~=0 break; end end if ttk==jk break; %Confirm artifacts end end if diff1(jj)<0 %Candidate onset if diff1(jk)>0 [tempMini,tmin,ta,tb]=seeklocales(abpsig,jj,jk); if abs(tmin-tempIndex)<=2 tempMin=tempMini; tonsetp=tmin; end end elseif diff1(jj)>0 %Candidate peak if diff1(jk)<0 [tc,td,tempMaxi,tmax]=seeklocales(abpsig,jj,jk); if abs(tmax-tempIndex)<=2 tempMax=tempMaxi; tpeakp=tmax; end end end if ((tempMax-tempMin)>0.4*abpMaxTH) %evaluation if ((tempMax-tempMin)<2*abpMaxTH) if tpeakp>tonsetp %If more zero-crossing points, further refine! ttempMin=abpsig(tonsetp); ttonsetp=tonsetp; for ttk=tpeakp:-1:(tonsetp+1) if abpsig(ttk)0 %If pulse period less than eyeclose, then artifact if (tonsetp-peakp(peakIndex))<(3*closeWin) %too many fiducial points, then reset tempIndex=diffIndex; abpMaxTH=2.5*abpMaxLT; break; end %If pulse period bigger than 2s, then artifact if (tpeakp-peakp(peakIndex))>stepWin peakIndex=peakIndex-1; onsetIndex=onsetIndex-1; if dicroIndex>0 dicroIndex=dicroIndex-1; end end if peakIndex>0 %new pulse beat peakIndex=peakIndex+1; peakp(peakIndex)=tpeakp; onsetIndex=onsetIndex+1; onsetp(onsetIndex)=tonsetp; tf=onsetp(peakIndex)-onsetp(peakIndex-1); to=floor(abpfreq./20); %50ms tff=floor(0.1*tf); if tff length(diff1) te = length(diff1); end tff=seekdicrotic(diff1(to:te)); if tff==0 tff=te-peakp(peakIndex-1); tff=floor(tff/3); end dicroIndex=dicroIndex+1; dicron(dicroIndex)=to+tff; tempIndex=tempIndex+closeWin; break; end end if peakIndex==0 %new pulse beat peakIndex=peakIndex+1; peakp(peakIndex)=tpeakp; onsetIndex=onsetIndex+1; onsetp(onsetIndex)=tonsetp; tempIndex=tempIndex+closeWin; break; end end end end end tempIndex=tempIndex+1; %step forward end % diffIndex=tempIndex+closeWin; %for a new beat diffIndex=tempIndex+1; end if isempty(peakp),return;end %Compensate the offsets of lowpass filter sigLen=length(peakp); for diffIndex=1:sigLen %avoid edge effect tempp(diffIndex)=peakp(diffIndex)-od; end ttk=tempp(1); if ttk<=0 tempp(1)=1; end clear peakp; peakp=tempp; clear tempp; sigLen=length(onsetp); for diffIndex=1:sigLen tempp(diffIndex)=onsetp(diffIndex)-od; end ttk=tempp(1); if ttk<=0 tempp(1)=1; end clear onsetp; onsetp=tempp; clear tempp; if isempty(dicron),return;end sigLen=length(dicron); for diffIndex=1:sigLen if dicron(diffIndex)~=0 tempp(diffIndex)=dicron(diffIndex)-od; else tempp(diffIndex)=0; end end clear dicron; dicron=tempp; clear tempp; end function [mini,minip,maxi,maxip]=seeklocales(tempsig,tempbegin,tempend) tempMin=tempsig(tempbegin); tempMax=tempsig(tempbegin); minip=tempbegin; maxip=tempbegin; for j=tempbegin:tempend if tempsig(j)>tempMax tempMax=tempsig(j); maxip=j; elseif tempsig(j)=0 izcMin=izcMin+1; tzcMin(izcMin)=itemp; end end % if tempdiff(itemp-2)>0 % if tempdiff(itemp+2)<=0 % izcMax=izcMax+1; % tzcMax(izcMax)=itemp; % end % end end itemp=itemp+1; end if izcMin==0 %big inflection itemp=3; tempMin=tempdiff(itemp); itempMin=itemp; while itemptempMax tempMax=tempdiff(itemp); itempMax=itemp; end itemp=itemp+1; end for itemp=izcMin:-1:1 if tzcMin(itemp) vector'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % scale physiologic ABP offset = 1600; scale = 20; Araw = abp*scale-offset; % LPF A = filter([1 0 0 0 0 -2 0 0 0 0 1],[1 -2 1],Araw)/24+30; A = (A(4:end)+offset)/scale; % Takes care of 4 sample group delay % ------- Dong changed this: ------- A = A ./ std(A); % normalizing data is very important for my peak detection. A = A - mean(A); % Slope-sum function dypos = diff(A); dypos(dypos<0) = 0; % ssf = [0; 0; conv(ones(16,1),dypos)]; w = 16/125*fs_abp; % 125 Hz to 250 Hz. ssf = [0; 0; conv(ones(w,1),dypos)]; % Decision rule first_8sec = 8*fs_abp; % avg0 = sum(ssf(1:1000))/1000; % average of 1st 8 seconds (1000 samples) of SSF avg0 = sum(ssf(1:first_8sec))/first_8sec; Threshold0 = 3*avg0; % initial decision threshold % ignoring ""learning period"" for now lockout = 0; % lockout >0 means we are in refractory timer = 0; % z = zeros(100000,1); z = zeros(fs_abp*800,1); counter = 0; % Dong: copied from wabp.c, 02/27/2020. % Dong change here. 02/27/2020. TmDEF = 0.25; %5;% Dong change here. 02/27/2020. max_min_thres = 0.1; %10;% Dong change here. 02/27/2020. my_avg0 = zeros(size(abp));% Dong change here. 02/27/2020. step_adjust_thres = 0.025; % it was 0.1 % Dong change here. 02/27/2020. % for t = 50:length(ssf)-17 for t = round(0.4*fs_abp):length(ssf)-w-1 lockout = lockout - 1; timer = timer + 1; % Timer used for counting time after previous ABP pulse if (lockout<1) & (ssf(t)>avg0+TmDEF) %(ssf(t)>avg0+5) % Not in refractory and SSF has exceeded threshold here % Dong change here. 02/27/2020. timer = 0; maxSSF = max(ssf(t:t+w)); % Find local max of SSF minSSF = min(ssf(t-w:t)); % Find local min of SSF if maxSSF > (minSSF + max_min_thres) %(minSSF + 10)% Dong change here. 02/27/2020. onset = 0.01*maxSSF ; % Onset is at the time in which local SSF just exceeds 0.01*maxSSF tt = t-w:t; dssf = ssf(tt) - ssf(tt-1); BeatTime = find(dssf round(312/125*fs_abp) % Lower threshold if no pulse detection for a while Threshold0 = Threshold0 - 0.1; %Threshold0 - 1; % Dong change here. 02/27/2020. avg0 = Threshold0/3; end my_avg0(t,1) = avg0+TmDEF; % % Dong change here. 02/27/2020. end r = z(find(z))-2; end","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_06/my_Elgendi_2013_method_III_peakdet.m",".m","1028","22","function [output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(raw_PPG,fs_PPG) % ------------------------------------------------------------------------- % This peak detection function was mentioned in this paper: % Elgendi, Mohamed, et al. % ""Systolic peak detection in acceleration photoplethysmograms measured from % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585. % [r,ssf,my_avg0,A] = my_revise_run_wabp(raw_PPG,fs_PPG); % ------------------------------------------------------------------------- if isempty(r) HR_Elgendi_3_2013 = 0; % there is no peak location. r = 1; else HR_Elgendi_3_2013 = 60 * fs_PPG ./ diff(r); % calculate the HR. end A = [A;0;0;0;]; % add zero A(1:6) = A(7); % first six plots are all high amplitude. output_Elgendi_3_2013 = struct('PPG_peak_loc_Elgendi_3_2013',r,... 'HR_Elgendi_3_2013',HR_Elgendi_3_2013,... 'filtered_PPG_Elgendi_3_2013',A,... 'thres_Elgendi_3_2013',my_avg0); end","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_03_and_04/my_Elgendi_2013_method_I_peakdet.m",".m","3762","111","function [output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(raw_PPG, delta, fs_PPG) % ------------------------------------------------------------------------- % Dong add this on 02/25/2020, based on this paper: % Elgendi, Mohamed, et al. % ""Systolic peak detection in acceleration photoplethysmograms measured from % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585. % % (1): bandpass filter (0.5-8Hz) [b, a] = butter(6,[0.5 8]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018 raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection. raw_PPG = raw_PPG - mean(raw_PPG); debugging_plot_flag = false; % only for plotting debugging figures. % ------------------------------------------------------------------------- % Below code is copied from: http://billauer.co.il/peakdet.html % PEAKDET Detect peaks in a vector % [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local % maxima and minima (""peaks"") in the vector V. % MAXTAB and MINTAB consists of two columns. Column 1 % contains indices in V, and column 2 the found values. % % With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices % in MAXTAB and MINTAB are replaced with the corresponding % X-values. % % A point is considered a maximum peak if it has the maximal % value, and was preceded (to the left) by a value lower by % DELTA. % Eli Billauer, 3.4.05 (Explicitly not copyrighted). % This function is released to the public domain; Any use is allowed. maxtab = []; mintab = []; raw_PPG = raw_PPG(:); % Just in case this wasn't a proper vector % if nargin < 3 x = (1:length(raw_PPG))'; % else % x = x(:); % if length(raw_PPG)~= length(x) % error('Input vectors v and x must have same length'); % end % end if (length(delta(:)))>1 error('Input argument DELTA must be a scalar'); end if delta <= 0 error('Input argument DELTA must be positive'); end mn = Inf; mx = -Inf; mnpos = NaN; mxpos = NaN; lookformax = 1; for i=1:length(raw_PPG) this = raw_PPG(i); if this > mx, mx = this; mxpos = x(i); end if this < mn, mn = this; mnpos = x(i); end if lookformax if this < mx-delta maxtab = [maxtab ; mxpos mx]; mn = this; mnpos = x(i); lookformax = 0; end else if this > mn+delta mintab = [mintab ; mnpos mn]; mx = this; mxpos = x(i); lookformax = 1; end end end if isempty(maxtab) HR_Elgendi_1_max_2009 = 0; % there is no peak location. peak_loc_max = 1; else peak_loc_max = maxtab(:,1); HR_Elgendi_1_max_2009 = 60 * fs_PPG ./ diff(peak_loc_max); % calculate the HR. end if isempty(mintab) HR_Elgendi_1_min_2009 = 0; % there is no peak location. peak_loc_min = 1; else peak_loc_min = mintab(:,1); HR_Elgendi_1_min_2009 = 60 * fs_PPG ./ diff(peak_loc_min); % calculate the HR. end output_Elgendi_1_2013 = struct('filtered_PPG_Elgendi_1_2013',raw_PPG,... 'PPG_peak_loc_Elgendi_1_max_2013',peak_loc_max,... 'PPG_peak_loc_Elgendi_1_min_2013',peak_loc_min,... 'HR_Elgendi_1_max_2013',HR_Elgendi_1_max_2009,... 'HR_Elgendi_1_min_2013',HR_Elgendi_1_min_2009); if debugging_plot_flag % debugging plot figure; plot(x,raw_PPG);hold on; plot(peak_loc_max,raw_PPG(peak_loc_max),'ro'); plot(peak_loc_min,raw_PPG(peak_loc_min),'go'); end end","MATLAB" "Biosensors","Cassey2016/PPG_Peak_Detection","method_08_and_09/my_Vadrevu_2019_peakdet.m",".m","10598","329","function [output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_buffer,fs_PPG) % ========================================================================= % This is my implementation of this paper: % % Vadrevu, Simhadri, and M. Sabarimalai Manikandan. % ""A robust pulse onset and peak detection method for automated PPG signal % analysis system."" IEEE Transactions on Instrumentation and Measurement % 68.3 (2018): 807-817. % % Implemented by Dong Han on 05/03/2020. % % Please cite our paper if you used this code: % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, % David D. McManus, and Ki H. Chon. 2022. % ""A Real-Time PPG Peak Detection Method for Accurate Determination of % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 % % Please cite our paper if you used our code. Thank you. % ========================================================================= debug_flag = false; % decide to plot the paper figure or not. %% A. Stationary Wavelet Transform of PPG signal. % first, for the input length, you can know the maximum wavelet % decomposition level you can get: TYPE = '1D'; % extension method. MODE = 'zpd'; % zero extension. X = PPG_buffer; % based on your input signal length, you have to extend your input signal % to MATLAB suggested length. LEN = 45;%18; % 18 for fs_PPG 50, 45 for fs_PPG 125; for 30 sec input. YEXT = wextend(TYPE,MODE,X,LEN); % required by swt. sig = YEXT; % s = PPG_buffer; sLen = length(sig); wname = 'bior1.5'; L = wmaxlev(sLen,wname); % [swa,swd] = swt(s,3,'bior1.5'); % the author mentioned wavelet biorthogonal 1.5 (bior1.5) [swa,swd] = swt(sig,L,wname); % the author mentioned wavelet biorthogonal 1.5 (bior1.5) s1 = swd(3,:) + swd(4,:); s1 = s1(:); % make sure it is column vector. s2 = swd(5,:) + swd(6,:) + swd(7,:); s2 = s2(:); % make sure it is column vector. if debug_flag % if you want to debug the result. figure; t_plot = [1:length(sig)]'./fs_PPG; % subplot(5,1,1); plot(t_plot,sig); xlim([0 t_plot(end)]) ylabel('Orig'); title('Fig.3 in TIM 2019 paper'); subplot(5,1,2) plot(t_plot,(swd(1,:) + swd(2,:))) xlim([0 t_plot(end)]) ylabel('s_0'); subplot(5,1,3); plot(t_plot,s1); xlim([0 t_plot(end)]) ylabel('s_1'); subplot(5,1,4); plot(t_plot,s2); xlim([0 t_plot(end)]) ylabel('s_2'); subplot(5,1,5); plot(t_plot,swa(7,:)); xlim([0 t_plot(end)]) ylabel('a_7'); end %% B. Multiscale Sum and Products: p = s1 .* s2; p = p(:); if debug_flag % if you want to debug the result. figure; ax(1) = subplot(4,1,1); plot(t_plot,sig); xlim([0 t_plot(end)]) ylabel('Orig'); title('Fig.4 in TIM 2019 paper'); ax(2) = subplot(4,1,2); p1 = swd(1,:) .* swd(2,:) .* swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:); plot(t_plot,p1); xlim([0 t_plot(end)]) ylabel('p_1'); ax(3) = subplot(4,1,3); p1 = swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:); plot(t_plot,p1); xlim([0 t_plot(end)]) ylabel('p_2'); ax(4) = subplot(4,1,4); plot(t_plot,p); xlim([0 t_plot(end)]) ylabel('p'); linkaxes(ax,'x'); end %% C. Shannon Entropy Envelope Extraction eta = 0.01 + std(p); p_tilda = abs(p); p_tilda(p_tilda < eta) = 0; p_tilda = p_tilda(:); % normalize p_tilda: norm_p_tilda = (p_tilda - min(p_tilda)) ./ (max(p_tilda) - min(p_tilda)); norm_p_tilda = norm_p_tilda(:); se = NaN(size(norm_p_tilda)); for tttt = 1:size(norm_p_tilda,1) if norm_p_tilda(tttt) == 0 % from MATLAB page: https://www.mathworks.com/help/wavelet/ref/wentropy.html % log(0) = 0 % 0log(0) = 0. se(tttt) = 0; else se(tttt) = -1 * norm_p_tilda(tttt) .* log(norm_p_tilda(tttt)); end end % % method 1: CONV twice: filt_Len = floor(0.2 * fs_PPG); % 0.4 is better. 05/04/2020. % h = ones(filt_Len,1)/filt_Len; % A third-order filter has length 4 % s = conv(se,h,'same'); % return the same size as se % s = conv(s,h,'same'); % conv twice % method 2: FILTFILT. % for 4020, ii = 2, PPG is zero. if any(isnan(se)) % any sample is NaN. new_se = se; new_se(isnan(new_se)) = []; if isempty(new_se) % nothing left after removing NaN. HR_Vadrevu_1_2019 = 0; % there is no peak location. onset_zx = 1; HR_Vadrevu_2_2019 = 0; % there is no peak location. peak_zx = 1; filter_PPG = PPG_buffer; output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,... 'PPG_peak_loc_Vadrevu_1_2019',onset_zx,... 'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019); output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,... 'PPG_peak_loc_Vadrevu_2_2019',peak_zx,... 'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019); return else % part of data is NaN, maybe I should fill zeros in it? keyboard; end end b = ones(filt_Len,1); a = -1; s = filtfilt(b, a, se); % -> AC component %% D. Pulse Peak and Onset Determination. % 1. Gaussian derivative kernel: sigma_1 = floor(0.05 * fs_PPG); % 0.05 mentioned in the paper. M = floor(2 * fs_PPG); % 2 mentioned in the paper. g = gausswin(M,sigma_1); % size should be 250 if Fs = 125. h_d = diff(g); % g(m+1) - g(m). z = conv(s,h_d,'same'); % % My conv function did not work. % temp_z = zeros(size(s,1),1); % for nnnn = 1:size(s,1) % for mmmm = 1:size(g,1)-1 % if (nnnn-mmmm+1 > 0) % % h_d(mmmm) = g(mmmm+1) - g(mmmm); % temp_z(nnnn) = temp_z(nnnn) + s(mmmm) * h_d(nnnn-mmmm+1); % end % end % end DownZCi = @(v) find(v(1:end-1) >= 0 & v(2:end) < 0); % Returns Down Zero-Crossing Indices. https://www.mathworks.com/matlabcentral/answers/267222-easy-way-of-finding-zero-crossing-of-a-function zx = DownZCi(z); % negative zero crossing point. % peak correction algorithm for onset: search_intv = floor(0.1 * fs_PPG / 2); % w/2 onset_zx = NaN(size(zx)); for zz = 1:size(zx,1) temp_zx = zx(zz); if temp_zx - search_intv > 0 % not exceed signal limit. if temp_zx + search_intv <= size(sig,1) temp_PPG = sig(temp_zx - search_intv : temp_zx + search_intv); [~,I] = min(temp_PPG); if isempty(I) ~= 1 adj_loc = temp_zx - search_intv + I - 1; else % no local minimum. adj_loc = temp_zx; end onset_zx(zz) = adj_loc; else % right interval exceed signal length. onset_zx(zz) = zx(zz); end else % left interval exceed index 1. onset_zx(zz) = zx(zz); end end % find peak: peak_zx = NaN(size(onset_zx,1)-1,1); % one sample smaller. for zz = 2:size(onset_zx,1) temp_onset_1 = onset_zx(zz-1); temp_onset_2 = onset_zx(zz); temp_PPG = sig(temp_onset_1:temp_onset_2); [~,I] = max(temp_PPG); if isempty(I) ~= 1 peak_zx(zz-1) = temp_onset_1 + I - 1; % peak is one sample size smaller. else peak_zx(zz-1) = onset_zx(zz); end end % prepare to output signal: filter_PPG = z(LEN+1:end-LEN); remove_left = find(onset_zx < LEN+1); if isempty(remove_left) ~= 1 onset_zx(remove_left) = []; end remove_right = find(onset_zx > size(z,1) - LEN); if isempty(remove_right) ~= 1 onset_zx(remove_right) = []; end onset_zx = onset_zx - LEN; % shifted. remove_left = find(peak_zx < LEN+1); if isempty(remove_left) ~= 1 peak_zx(remove_left) = []; end remove_right = find(peak_zx > size(z,1) - LEN); if isempty(remove_right) ~= 1 peak_zx(remove_right) = []; end peak_zx = peak_zx - LEN; if debug_flag % if you want to debug the result. figure; ax(1) = subplot(7,1,1); plot(t_plot,sig); xlim([0 t_plot(end)]) ylabel('Orig'); title('Fig.5 in TIM 2019 paper'); ax(2) = subplot(7,1,2); plot(t_plot,p); xlim([0 t_plot(end)]) ylabel('p'); ax(3) = subplot(7,1,3); plot(t_plot,norm_p_tilda); xlim([0 t_plot(end)]) ylabel('p_th'); ax(4) = subplot(7,1,4); plot(t_plot,se); xlim([0 t_plot(end)]) ylabel('se'); ax(5) = subplot(7,1,5); plot(t_plot,s); xlim([0 t_plot(end)]) ylabel('s'); ax(6) = subplot(7,1,6); plot(t_plot,z); hold on; plot(t_plot(zx),z(zx),'ro'); xlim([0 t_plot(end)]); ylabel('z'); ax(7) = subplot(7,1,7); plot(t_plot,sig); hold on; plot(t_plot(onset_zx),sig(onset_zx),'go'); plot(t_plot(peak_zx),sig(peak_zx),'ro'); xlim([0 t_plot(end)]) ylabel('orig with peak'); linkaxes(ax,'x'); end if isempty(onset_zx) HR_Vadrevu_1_2019 = 0; % there is no peak location. onset_zx = 1; else HR_Vadrevu_1_2019 = 60 * fs_PPG ./ diff(onset_zx); % calculate the HR. end if isempty(peak_zx) HR_Vadrevu_2_2019 = 0; % there is no peak location. peak_zx = 1; else HR_Vadrevu_2_2019 = 60 * fs_PPG ./ diff(peak_zx); % calculate the HR. end output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,... 'PPG_peak_loc_Vadrevu_1_2019',onset_zx,... 'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019); output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,... 'PPG_peak_loc_Vadrevu_2_2019',peak_zx,... 'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019); end ","MATLAB"