1 Assessing Psychological Stress During Physiological and Memory Tasks Using Non-Invasive fNIRS Kailey Wheeler Department of Biology, Thompson Rivers University 29 September 2024 2 Introduction Memory retrieval tasks are commonly used in clinical settings to assess cognitive decline associated with aging. These tasks rely on an individual’s ability to recall information, a process that can be influenced by various factors, including acute anxiety. The interpretations of the outcome of these tests may be inaccurate if participants were experiencing acute anxiety at the time (Eysenck et al., 2007; Salthouse, 2012). This anxiety can stem from concerns about task performance or participant’s subjective perceptions of their abilities. To ensure the validity of these cognitive assessments, it is often important to measure the participant's state-anxiety or their current level of anxiety. Although questionnaires are frequently used for this purpose, their reliability in capturing momentary anxiety is debatable, and their consistency can vary across repeated measures (Meissel & Salthouse, 2016). As such, employing physiological measures to assess acute anxiety may offer a more reliable approach to correct for this potentially confounding factor. Recently, development of methods to assess stress through indirect measures of the fight or flight response (i.e. sympathetic nervous system activity) have been developed using non-invasive measures at the wrist or in the fingers. Udhayakumar et al. (2023) demonstrated that stress responses can be monitored using photoplethysmography, a technique that detects changes in local blood oxygenation. They found that this method could identify the onset of physiological stresses (like when people place their hand in cold water) by using red light to track fluctuations in blood flow with each heartbeat. 3 Another device that uses infrared light to measure blood oxygen levels is a functional near-infrared spectroscopy device (fNIRS) by Artinis Medical Systems. This system is placed on the head and enables brain activity to be assessed. Moreover, the device also takes measures at very high rates (up to 75/s) enabling the pulsatile changes in blood oxygenation to be gathered. As such, it may be used to assess changes in the height of these pulses in the same manner as Udhayakumar et al. (2023), thus enabling stress levels to be monitored in addition to levels of brain activity. The fNIRS data typically obtained during studies that assess working memory may be rich in additional information that can be used to examine the relationships between stress and performance on working memory tasks in older adults. In this study, we explore the feasibility of using the Artinis Brite fNIRS system to simultaneously monitor anxiety, stress levels, and brain activity. fNIRS is utilized to measure blood oxygenation in the brain and scalp during two physiological stressors and two mental stress tasks. The resulting fNIRS data is analyzed using two metrics known for their sensitivity to sympathetic nervous system activation: total sample entropy and average sample entropy. 4 Methods Participants A total of eight participants, both male and female, aged between 19 and 30, were recruited for this study. Participants were recruited through social media (e.g., instagram and facebook), word of mouth, and posters placed on bulletin boards throughout TRU. The inclusion criteria required participants to be between 18 - 39 years old, have normal or corrected-to-normal vision, and be fluent in English. The exclusion criteria included individuals who had a history of cardiovascular disease (e.g. previous heart attack, or were currently being treated for high blood pressure or high cholesterol, previous stroke), had been diagnosed as having type 1 or 2 diabetes or metabolic syndrome, had respiratory illnesses like chronic obstructive pulmonary disease, or had a cognitive disorder that may be related to vascular dysfunction (e.g. dementias). All participants gave informed consent prior to the commencement of any experimental procedures. Compensation for their participation was provided in the form of Tim Hortons gift cards valued at twenty-five dollars. Procedure Upon arrival at the lab, participants were assured of confidentiality (each was assigned a random number, with no identifying information recorded apart from the consent form). They were provided with a consent form outlining the study's purpose, procedures (including the estimated time commitment), potential risks and benefits, compensation, confidentiality assurances, the right to withdraw, and contact information. Participants who chose not to consent or later withdrew from the study were still compensated. 5 Participants were then instructed to perform three maximal hand grips using a hand grip force measurement device connected to an ADInstruments PowerLab 26T. The data was recorded via LabChart software on a desktop computer. The first maximal hand grip was measured after 30 seconds, with the subsequent two grips separated by 30-second rest intervals. The maximal and minimal values (in mV) were then extracted from the data and used to set 100% and 0% force, respectively, for a later experiment. ECG and ABP set-up After completing the maximal hand grips, participants were equipped with devices to monitor both heart rate and blood pressure. Heart rate was measured using an electrocardiogram (ECG). Three electrodes were positioned on the participant: one just below the right clavicle, one below the left clavicle, and one just above the left hip, using 3M-2560 Red Dot Multi-Purpose Monitoring Electrodes (1000/cs). The positive lead was connected to the hip electrode, the ground to the left clavicle, and the negative lead to the right clavicle (as seen in figure one). Figure 1. ECG set-up used in the study (not including the right leg). 6 Arterial blood pressure (ABP) was measured using a CNAP monitor (CNSystems, Austria) that included an arm cuff and appropriately sized finger cuffs (small, medium, or large). The arm cuff was applied first, followed by the finger cuffs, fitted according to the participant's finger size. Both blood pressure and heart rate data were recorded through Acqknowledge software on a laptop computer (Samsung series 7 Chronos) via the BIOPAC system. fNIRs set-up After participants were equipped with blood pressure and heart rate monitors, they were then fitted with the Artinis Brite fNIRS head cap (Artinis, Medical Systems, The Netherlands). The neoprene cap was equipped with 10 light-emitting optodes, which transmitted near-infrared light in the 650-950 nm range, and 12 receivers that detected changes in light absorption, at a sampling rate of 75 Hz. The optodes were arranged in a 2 x 12 grid, spaced 3 cm apart, except for the short-separation channels, which were spaced 1.5 cm apart. This configuration created 24 recording channels which each continuously tracked fluctuations in the concentrations of oxygenated and deoxygenated hemoglobin. Once robust signals were ensured from the ECG, ABP, and fNIRS, participants completed two mental stress tasks and two physical stress tasks, with the order of tasks randomized for each participant. The randomization included both the sequence of the task categories—mental or physical—and the order of individual tasks within each category. Participants began in a seated position with their left hand, fitted with the ABP finger cuffs, resting on the arm of the chair, while their right hand remained free. They were asked to minimize movement and speech unless necessary to avoid disrupting any signals. A 10-minute rest period was conducted to establish baseline hemodynamic measurements, during which 7 participants remained seated in the chair without engaging in any activity. After the 10-minute rest period, participants undertook one of four tasks. Each mental stress task lasted five minutes, while the physical stress tasks were three minutes in duration. Upon completing a task, participants were instructed to remain very still for an additional three-minute period, which was crucial for data analysis. After the post-task period, participants were permitted to relax further, while continuing to minimize movement and speech as much as possible. Following each task, a 10-minute rest period was mandated before the start of the subsequent task. Upon completing one category of tasks (either mental or physical), participants were provided with an opportunity to rest before proceeding to the next category. Mental Stress Tasks The two mental stress tasks included an unsolvable anagram and a color shape task, both derived from the millisecond test library within the Inquisit 5 software. Each task was presented to participants on a laptop (MacBook Air 2020, 13”, 2560 x 1600 resolution), and they were instructed to only use their free hand. Both tasks were limited to a duration of five minutes, regardless of the participants progress, and including the practice trial. The unsolvable anagrams task involved presenting participants with a series of scrambled letters (see figure two) that could and could not be arranged into meaningful words, at random intervals, within a thirty second time limit. The practice trial consisted of five solvable anagrams. Following the practice trial, participants were prompted with a message informing them they had to unscramble twenty-five letter sets into meaningful words and that they would pass if they solved at least eight of the twenty-five words or fail if they solved seven or fewer. Unbeknownst 8 to the participants, not all the scrambled letter combinations could form meaningful words. During the debriefing session following the experiment, participants were informed of this. Figure 2. An example of a scrambled letter combination presented to participants, who had thirty seconds to solve it before the screen switched to the next anagram. The Color Shape Task involved presenting participants with shapes that varied in color and form (figure three). Each shape and color was associated with a specific key on the laptop: the key 'A' corresponded to a circle and the color red, while 'L' corresponded to a triangle and the color green. Participants were required to press the designated key based on specific rules that varied throughout the task. During the initial practice block, participants were shown shapes without color and instructed to identify the shape. In the subsequent practice block, they were presented with colored squares and asked to identify the color. In the post-practice block one, participants were shown shapes (circle or triangle) or colored squares and were instructed to identify either the shape when no color was present, or the color when it was present. In post-practice block two, participants were shown shapes superimposed on coloured squares and asked to identify the color when it was red or the shape if it was green. The blocks became increasingly difficult as they progressed however, most participants only made it to post-practice block two with the 9 five-minute time limit. Consistent with the unsolvable anagrams task, participants were permitted to use only their free hand. Figure 3. Examples of images presented in the color-shape task. In the upper left (a), one of the two shapes from practice block one is depicted. The upper right (b) illustrates one of the two colors featured in practice block two. The lower left (c) presents two instances requiring participants to choose between shape or color in post-practice block one. Finally, the lower right (d) displays an example of a superimposed image from post-practice block two, where the correct answer is red. Physical Stress Tasks The physical stress tasks consisted of a prolonged handgrip test and a cold pressor test, each lasting three minutes. For the prolonged handgrip test, an MLT004/ST Grip Force Transducer connected to a PowerLab system (ADInstruments, New Zealand) was utilized. Participants were seated with the transducer in their dominant hand, facing a desktop computer displaying the lab chart output. They were instructed to maintain a grip force at 20% of their 10 maximal handgrip strength, which was determined at the start of the experiment, for the duration of three minutes. The exerted percentage and a three-minute timer were visible on the computer screen. Upon completion, participants were asked to release the transducer and remain as still as possible while the researcher removed the device from their hand. The cold pressor test involved the participant submerging their hand in water maintained at a temperature of 3-5°C for three minutes (Silverthorn & Michael, 2013). A four-quart stainless steel mixing bowl was filled to approximately three-quarters capacity with room-temperature water, and ice was added until the water temperature reached the desired range, as measured with a digital thermometer. The participant remained seated and placed their free hand into the bowl positioned beside them. To prevent the formation of a thermal layer, the researcher continuously stirred the water. At the end of the three-minute period, the researcher removed the participant’s hand and gently dried it with a paper towel to minimize participant movement. Analysis ECG Data The ECG intervals for each participant were extracted from AcqKnowledge and exported into an Excel spreadsheet. The spreadsheet contained all relevant ECG parameters, including the R-R interval. For each participant and each of the four tasks, the mean R-R interval was calculated for the pre-task rest period, the first, second, and third minutes of the task, and the post-task recovery period (labeled as "pre," "post 0-1," "post 1-2," "post 2-3," and "recovery," respectively). The mean R-R intervals for the pre and recovery periods were calculated from 30 seconds of data, while the mean R-R intervals for the remaining periods were derived from 60 11 seconds of data. Heart rate was then calculated for each period from the mean R-R intervals by dividing sixty by the R-R interval, expressed in seconds. The heart rate data was then converted to a text file and exported into Jeffrey's Amazing Statistics Program (JASP) where it was analyzed by a repeated measures analysis of variance. ABP Data Arterial blood pressure data for each participant was analyzed using AcqKnowledge software. Consistent with the ECG data analysis, the mean arterial pressure (MAP) was calculated for each event of every task for each participant across the following time periods: pre-task rest, the first, second, and third minutes of the task, and the post-task recovery. The calculation of MAP values adhered to the same time intervals used for determining mean R-R intervals from the ECG data. MAP values were obtained by highlighting the signal within the specified time frames. The MAP data was then converted to a text file and exported into Jeffrey's Amazing Statistics Program (JASP) where it was analyzed by a repeated measures analysis of variance. 12 Results Mean HR Figure 4. The graph shows the mean heart rate (HR) in beats per minute (bpm) across different time points during the Handgrip task for each participant. The x-axis represents time points in seconds (Pre, Post0-1, Post1-2, Post2-3, and Recovery), and the y-axis shows HR values ranging from 20 to 120 bpm. The general trend of this graph shows that HR starts at a baseline level during the pre phase. It then increases progressively through the post phases, reaching a peak at post2-3, indicating the highest HR during the most strenuous part of the task. Finally, the HR decreases during the Recovery phase, approaching baseline values again. 13 Figure 5. The graph shows the mean heart rate (HR) in beats per minute (bpm) across different time points during the Colour-Shape task for each participant. The x-axis represents time points in seconds (Pre, Post0-1, Post1-2, Post2-3, and Recovery), and the y-axis shows HR values ranging from 20 to 120 bpm. The general trend of the graph shows that HR increases moderately from the pre phase through the post phases, with a less pronounced peak compared to the other tasks. This suggests a milder cardiovascular response to this task. The recovery phase shows a gradual return towards the baseline HR. 14 Figure 6. The graph shows the mean heart rate (HR) in beats per minute (bpm) across different time points during the Anagram task for each participant. The x-axis represents time points in seconds (Pre, Post0-1, Post1-2, Post2-3, and Recovery), and the y-axis shows HR values ranging from 20 to 120 bpm. The general trend of this graph shows that HR increases slightly during the post phases compared to the pre phase, indicating a mild increase in cardiovascular response. The HR drops back towards baseline during the recovery phase, but the changes are less noticeable compared to other tasks. 15 Figure 7. The graph shows the mean heart rate (HR) in beats per minute (bpm) across different time points during the Cold Pressor task for each participant. The x-axis represents time points in seconds (Pre, Post0-1, Post1-2, Post2-3, and Recovery), and the y-axis shows HR values ranging from 20 to 120 bpm. The general trend for this graph shows that HR increases steadily from the pre phase to the post phases, with a significant rise at post2-3. During the recovery phase, the HR drops but may remain slightly elevated compared to the pre phase, indicating a slower return to baseline. 16 Mean Arterial Blood Pressure Figure 8. The graph shows the mean arterial pressure (MAP) in mmHg across different time points during the Handgrip task. The x-axis represents time points (Pre, Post0-1, Post1-2, Post2-3, and Recovery) in seconds, and the y-axis shows MAP values ranging from 60 to 160 mmHg. The general trend for this graph shows a slight increase in MAP from pre to post0–1, indicating a mild initial cardiovascular response. MAP continues to rise, peaking at post2–3. After reaching this peak, MAP decreases slightly during the recovery phase, but it does not fully return to baseline. The red asterisk indicates a significant change in MAP between post2-3 and recovery. 17 Figure 9. The graph shows the mean arterial pressure (MAP) in mmHg across different time points during the Cold Pressor task. The x-axis represents time points (Pre, Post0-1, Post1-2, Post2-3, and Recovery) in seconds, and the y-axis shows MAP values ranging from 60 to 160 mmHg. The general trend for this graph shows that there is a slight increase in MAP from baseline to post0-1. MAP continues to gradually rise and peaks at post2-3, showing the highest elevation during the task. Afterwards MAP begins to decline, approaching baseline levels, suggesting a return towards normal, but still slightly elevated compared to the initial pre phase, reflecting a gradual recovery process. The red asterisk represents a significant difference in MAP values between post0-1 and post2-3, the purple between post1-2 and recovery, and the blue between post2-3 and recovery. 18 Figure 10. The graph shows the mean arterial pressure (MAP) in mmHg across different time points during the Colour Shape task. The x-axis represents time points (Pre, Post0-1, Post1-2, Post2-3, and Recovery) in seconds, and the y-axis shows MAP values ranging from 60 to 160 mmHg. The general trend for this graph shows that there is a slight increase in MAP from baseline to post0-1, showing a mild elevation during the task. Across the three post phases MAP values appear relatively stable, with no marked increase compared to earlier phases, indicating that the task might not elicit a strong cardiovascular response. During the recovery phase MAP decreases slightly, suggesting a return towards baseline but not a dramatic drop, indicating mild recovery. 19 Figure 11. The graph shows the mean arterial pressure (MAP) in mmHg across different time points during the Anagram task. The x-axis represents time points (Pre, Post0-1, Post1-2, Post2-3, and Recovery) in seconds, and the y-axis shows MAP values ranging from 60 to 160 mmHg. The general trend of this graph shows a slight increase in MAP from pre to post0–1, indicating a mild cardiovascular response. However, across the three post phases MAP remains fairly stable, showing no significant elevation or drop across the task. During the recovery phase, MAP decreases slightly but stays close to the baseline level, suggesting a mild return towards resting values, with no strong recovery effect. Overall, the task appears to elicit only a minor response in MAP. 20 Discussion Mean HR As seen in figures four - seven, mean HR across each event within each task did not vary significantly. The most notable changes in the general trend of mean HR were seen in the colour shape task and in the hand grip task, however they were not significant changes. This may be due in part to the low sample size. With only eight participants, it is possible that any individual variation in HR response was amplified by the small sample size. Larger groups could reveal more significant differences by averaging out individual variability. Another potential factor for these findings are that males and females generally exhibit different cardiovascular responses to stress. Studies show that males tend to have a larger increase in heart rate, while females may exhibit more heart rate variability (HRV) and smaller increases in heart rate (potentially linked to menstrual cycle) (Ahmadi & Mandic, 2018). These differences in HR responses to stress can lead to increased variability in the overall data. If males tend to show higher HR increases in response to stress while females show a more moderate response with higher variability, the mean HR might fluctuate widely between participants, preventing the detection of a clear trend. We could potentially correct for this by increasing the sample size. A larger sample size allows for the identification of clearer trends by reducing the impact of outliers and individual variations in responses to stress. More data points would help smooth out fluctuations that could otherwise obscure significant findings. 21 Mean Arterial Pressure Figures 10 and 11 illustrate similar changes in MAP across all four events as those observed in the HR graphs. This trend may be attributed to the same factors influencing HR, such as sex-based differences in cardiovascular responses or the limited sample size. Additionally, it is possible that the stress tasks depicted in Figures 10 and 11 (color-shape task and anagram task) were not stressful enough to elicit a significant physiological response. In contrast, mean arterial pressure (MAP) demonstrated significant changes across events during both the cold pressor task (Figure 9) and the handgrip task (Figure 8). Specifically, a significant difference in MAP was observed between the post2-3 and recovery events in the handgrip task (p < .001). In the cold pressor task, three distinct significant differences in MAP were identified: between post0-1 and post2-3 (p < .001), post1-2 and recovery (p < .001), and post2-3 and recovery (p < .001). This suggests that the physical stressors were sufficient enough to elicit a physiological response. 22 Development of fNIRs analysis The above signal is an example of an oxyhemoglobin signal from an area of the brain for one participant. This portion of the UREAP is ongoing and will lead into Directed Studies course work. The goal is to identify all the peaks in the signal and then determine their prominence, as well as when each peak occurs. This is done using the code (see Appendix A for the Matlab code) based upon the work of Udhayakumar et al. (2023). First, we use some filtering techniques that remove non-physiological aspects of the signal. 23 After cleaning the signal, a function in Matlab is implemented that identifies peaks that are spaced out at reasonable intervals. In the case of humans, we expect the duration between peaks to vary between 0.5s-1.5s which corresponds to heart rates between 40-120 bpm. Once completed, the prominence of each peak and their occurrence is exported for further analyses based upon the Udhayakumar et al. (2023) manuscript. This next phase of the analysis involves first extracting from the dataset, time periods to analyze for average sample entropy. To do this a script in Matlab was developed that would first identify the times when each condition was occurring. This information is embedded within the fNIRS data and is referred to as the 24 stimulus. Thus, the script would extract the time of each stimulus and parse data before and after this period into variables to be assessed for average sample entropy. Afterwards the average sample entropy (Appendix B for the Matlab code) was determined for each parsed dataset, for example a 2-minute period during rest. At this stage, the Matlab code is complete and has been tested on one dataset with resting average sample entropy calculated. The next step upon completion of data collection is to apply these Matlab codes to the data and compare the average sample entropy across conditions and see whether we observe changes in average sample entropy that indicate sympathetic activation in our participants. 25 Future Steps for this Study This study will be continued as a directed studies for the fall 2024 semester, with plans to expand the participant pool. Increasing the sample size will provide stronger and more reliable data, allowing for more robust statistical analyses and generalizable conclusions. In addition, with the completion of the data analysis code, a detailed analysis of the fNIRS signals will be conducted in MatLab. The analysis will focus on the following steps: Analyzing the pulse of fNIRS datasets while under stress, cleaning the fNIRS data to extract peaks and troughs, calculating pulse amplitudes over time, incorporating Sample Entropy (SampEn) to assess changes in entropy over time and identifying rapid changes in SampEn to indicate shifts in sympathetic nervous system (SNS) activation. The next steps after this will involve examining data already obtained from young and older adults during a working memory task to assess whether it is possible to identify participants who experienced acute stress and anxiety. Dr. Gonzalez previously studied over 100 participants using fNIRS while they completed an N-back working memory task. Each of these participants was also assessed for state-anxiety levels using a questionnaire. A subset of the data will be analyzed from participants with varying levels of questionnaire-based state-anxiety. The analysis will focus on assessing relationships between fNIRS-measured anxiety and stress during the working memory task and determining if those who exhibited stress responses also have high state-anxiety levels on the questionnaire. The findings of this study will be presented at Thompson Rivers University’s undergraduate conference in collaboration with the Faculty of Science, as well as at the annual Canadian Society for Brain, Behaviour and Cognitive Science (CSBBCS) conference. Additionally, there are plans to potentially publish the results in an open access peer-reviewed journal, such as Experimental Physiology or Experimental Brain Research. 26 References Ahmadi, T., & Mandic, D. (2018). Sex differences in the dynamics of the cardiovascular response to mental stress: Proof of concept. Frontiers in Physiology, 9, 1616. https://doi.org/10.3389/fphys.2018.01616 Eysenck, M. W., Derakshan, N., Santos, R., & Calvo, M. G. (2007). Anxiety and cognitive performance: Attentional control theory. Emotion, 7(2), 336–353. https://doi.org/10.1037/1528-3542.7.2.336 Meissel, K., & Salthouse, T. A. (2016). Relations of naturally occurring variations in state anxiety and cognitive functioning. Personality and Individual Differences, 98, 85–90. https://doi.org/10.1016/j.paid.2016.03.087 Salthouse, T. A. (2012). Consequences of age-related cognitive declines. Annual Review of Psychology, 63, 201–226. https://doi.org/10.1146/annurev-psych-120710-100328 Silverthorn, D. U., & Michael, J. (2013). Cold stress and the cold pressor test. Advances in Physiology Education, 37(1), 93–96. https://doi.org/10.1152/advan.00104.2012 Udhayakumar, R., Miller, C. A., & Alkaabi, A. (2023). Measurement of stress-induced sympathetic nervous activity using multi-wavelength PPG. Royal Society Open Science, 10, 221382. https://doi.org/10.1098/rsos.221382 Cables and Sensors. (n.d.-a). 12-lead ECG placement: The ultimate guide. Cables and Sensors. https://www.cablesandsensors.com/pages/12-lead-ecg-placement-guide-with-illustrations 27 Appendix A MatLab Code - Pulse ID % Analyzing the pulse of fNIRS datasets while under stress % Cleaning of fNIRS data to extract peaks and troughs % Calculating the Pulse amplitudes over time % Incorporation of SampEn to assess changes in entropy over time % Identifying rapid changes in SampEn to indicate changes in SNS activation % Steps in code development % 1. Import the dataset using the Brain AnalyzIR toolkit from snirfs % 2. Convert to Hb and trim data set % 3. Possibly use the SNI to identify useful channels with structured noise % which would be worth asessing % 4. Pre-processing steps will involve: % a. caluculating the power spectrum of % the signal, % b. then identifying the maximal power within the spectrum of % 0.6-3Hz, which would ID HRs of between 36-180bpm % c. Apply a centre median and centre moving average filter to the % data with a window size of 0.2*Peak-to-peak duration % Load the .mat file data = load('nirs_example.mat'); hb_data = data.hb_data; % Sampling frequency (Hz) fs = 25; % Initialize structures to store results peak_amplitudes = struct; %relative_peak_amplitudes = struct; peak_locations = struct; peak_prominence = struct; %baselines_all = struct; % Process each column in hb_data for col = 1:size(hb_data, 2) % Extract the current column data data_col = hb_data(:, col); % Step 1: Calculate the power spectrum n = length(data_col); 28 f = (0:n-1)*(fs/n); % Frequency vector fft_col = fft(data_col); power_spectrum = abs(fft_col).^2 / n; % Step 2: Identify the maximal power within the spectrum of 0.5-3Hz freq_range = find(f >= 0.5 & f <= 3); [max_power, max_index] = max(power_spectrum(freq_range)); max_freq = f(freq_range(max_index)); % Calculate the peak-to-peak duration based on the identified HR frequency peak_to_peak_duration = 1/max_freq; % Step 3: Apply a central median and central moving average filter window_size = round(0.2 * peak_to_peak_duration * fs); filtered_median = medfilt1(data_col, window_size); filtered_cma = movmean(filtered_median, window_size); filtered_cma_invert = -1*filtered_cma; % Step 4: Apply a 3rd order low pass Butterworth filter to create a % % baseline signal to use to calculate relative peak heights % [b, a] = butter(3, 0.5 * peak_to_peak_duration / (fs/2), 'low'); % baseline_filtered = filtfilt(b, a, filtered_cma); % Detect peaks and troughs in the filtered data [peaks, locs, w, p] = findpeaks(filtered_cma,'Annotate', 'extents', 'MinPeakDistance', round(0.5 * fs)); %adjust the 0.5 (120bpm) to ensure all peaks are identified %[troughs, locst] = findpeaks(filtered_cma_invert, 'MinPeakDistance', round(0.5 *fs)); % Calculate relative peak heights from the peak and trough data % relative_peaks = zeros(size(peaks)); % for i = 1:length(locs) % Find difference between the peak and trough of the local peak % relative_peaks(i) = peaks(i) - troughs(i); % end % Store results in structures peak_amplitudes.(['col' num2str(col)]) = peaks; %trough_amplitudes.(['col' num2str(col)]) = troughs; % relative_peak_amplitudes.(['col' num2str(col)]) = relative_peaks; peak_locations.(['col' num2str(col)]) = locs; peak_prominence.(['col' num2str(col)]) = p; % trough_locations.(['col' num2str(col)]) = locst; % filtered_baseline(:,col) = baseline_filtered; cma_filtered(:,col) = filtered_cma; %cma_filtered_invert(:,col) = filtered_cma_invert; 29 % baselines_all.(['col' num2str(col)]) = relative_baseline; end %Determine the peak amplitudes by taking the peak locations and comparing %them to the trough locations and if they are troughs are within 5 points %before the peak, then a peak amplitude is calculated and placed in a % %struct % i=1 % for fieldNumber = 1:42 % fieldName = sprintf('col%d', fieldNumber); % Generate the field name dynamically % fieldValue = myStruct.(fieldName); % Access the field value % % Do something with fieldValue % disp(['Value of ', fieldName, ': ', num2str(fieldValue)]); % end % % Display the relative peak amplitudes for the first column as an example % fprintf('Relative Peak Amplitudes for Column 1:\n'); % disp(relative_peak_amplitudes.col1); %Uncomment the following section to plot specific column peaks time = (0:length(data_col)-1) / fs; col_to_plot = 31; % Change this to plot a different column findpeaks(cma_filtered(:,col_to_plot),'Annotate', 'extents', 'MinPeakDistance', round(0.5 * fs),'MaxPeakWidth',(2 * fs)); figure; plot(time, cma_filtered(:, col_to_plot)); hold on; plot(peak_locations.(['col' num2str(col_to_plot)]) / fs, peak_amplitudes.(['col' num2str(col_to_plot)]), 'rv', 'MarkerFaceColor', 'r'); title(['Data with Detected Peaks for Column ' num2str(col_to_plot)]); xlabel('Time (s)'); ylabel('Amplitude'); grid on; %Uncomment the following section to plot specific column troughs time = (0:length(data_col)-1) / fs; col_to_plot = 19; % Change this to plot a different column figure; plot(time, cma_filtered(:, col_to_plot)); hold on; plot(peak_locations.(['col' num2str(col_to_plot)]) / fs, peak_amplitudes.(['col' num2str(col_to_plot)]), 'rv', 'MarkerFaceColor', 'r'); title(['Data with Detected Peaks for Column ' num2str(col_to_plot)]); xlabel('Time (s)'); ylabel('Amplitude'); grid on; 30 %Extract stimulus timings from the hb data set and place in a matrix for stim_times = zeros(4,length(hb)); i=1:length(hb) temp = hb(i).stimulus.values{1,1}.onset; stim_times(:,i) = temp; clear temp end %Extract pulse related data (height, slope, from each Stim (25 beats prior to 40 beats %afterwards) %Calculate SampEn of the segment with a r= 0.15 *sd and a tolerance of m=2 saen = total_sample_entropy(2,0.15*std(cma_filtered(:,7)),cma_filtered(:,7)); 31 Appendix B MatLab Code - Sample Entropy %% A function to calculate the total and average sample entropy of a parsed signal function TotalSampEn = total_sample_entropy(x, m, r_values) % x: input time series % m: embedded dimension % r_values: range of tolerance values (vector of r) N = length(x); % Length of the time series TotalSampEn = 0; % Initialize total entropy sum % Loop over each r value in the range for r = r_values SampEn = sample_entropy(x, m, r); % Compute SampEn for each r TotalSampEn = TotalSampEn + SampEn; % Sum up the SampEn values end end function SampEn = sample_entropy(x, m, r) % x: time series data % m: embedded dimension % r: tolerance value (e.g., r * std(x)) N = length(x); r = r * std(x); % Tolerance based on the signal's standard deviation % Create m-dimensional embedding vectors Xm = zeros(N - m + 1, m); for i = 1:N - m + 1 Xm(i, :) = x(i:i + m - 1); end % Count matches for m-dimensional vectors Cm = zeros(N - m + 1, 1); for i = 1:N - m + 1 for j = 1:N - m + 1 if i ~= j dist = max(abs(Xm(i, :) - Xm(j, :))); if dist < r Cm(i) = Cm(i) + 1; end end 32 end end Cm = Cm / (N - m); % Normalize the counts % Create (m+1)-dimensional embedding vectors Xm1 = zeros(N - m, m + 1); for i = 1:N - m Xm1(i, :) = x(i:i + m); % Vector of length m+1 end % Count matches for (m+1)-dimensional vectors Cm1 = zeros(N - m, 1); for i = 1:N - m for j = 1:N - m if i ~= j dist = max(abs(Xm1(i, :) - Xm1(j, :))); if dist < r Cm1(i) = Cm1(i) + 1; end end end end Cm1 = Cm1 / (N - m - 1); % Normalize the counts % Compute Sample Entropy SampEn = -log(sum(Cm1) / sum(Cm)); end