Heart Rate Variability

Initialize NeuroAnalyzer
using NeuroAnalyzer
using CairoMakie
CairoMakie.activate!(type = "png")
# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of
# NeuroAnalyzer figures: remove it
delete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
using DataFrames
using Statistics
NeuroAnalyzer.progress_bar = false

# Makie figure and axis settings matching NeuroAnalyzer plots
fig_size = (900, 450)
ax_style = (titlesize = 18,
            xlabelsize = 18,
            ylabelsize = 18,
            xticklabelsize = 12,
            yticklabelsize = 12,
            xticks = LinearTicks(10),
            xminorticksvisible = true,
            xminorticks = IntervalsBetween(10),
            xautolimitmargin = (0, 0),
            yautolimitmargin = (0.1, 0.1))

# EEG recording with an ECG channel (1000 s)
eeg = load_neuro("files/eeg/eeg.hdf")

Heart Rate Variability (HRV) is the physiological phenomenon of variation in the time interval between heartbeats. It reflects the autonomic nervous system’s (ANS) regulation of heart activity and is influenced by physiological and psychological factors. HRV is widely used in clinical, research, and wellness applications to assess autonomic balance, stress, cardiovascular health, and emotional regulation.

HRV measures the fluctuations in the time intervals between consecutive heartbeats (R-R intervals in ECG).

It is not the same as heart rate (which measures the average number of beats per minute). Instead, HRV reflects the complex interplay between the sympathetic (fight-or-flight) and parasympathetic (rest-and-digest) branches of the autonomic nervous system.

HRV provides insights into:

  • Autonomic nervous system (ANS) function: Balance between sympathetic and parasympathetic activity.
  • Cardiovascular health: Predicts risk of heart disease, hypertension, and arrhythmias.
  • Stress and emotional regulation: Lower HRV is associated with chronic stress, anxiety, and depression.
  • Physical fitness: Athletes often exhibit higher HRV, indicating better recovery and performance.
  • Sleep quality: HRV patterns can indicate sleep stages and quality.
  • Aging: HRV tends to decrease with age.

In NeuroAnalyzer, HRV analysis is performed using ECG data, where the R-peaks of the ECG signal are detected to compute NN intervals (the time between two successive normal heartbeats). Below is a detailed explanation of HRV, its measurement, and the time-domain parameters used for analysis.

  1. Mean NN Interval (MENN)
  • Definition: The mean of all NN intervals.
  • Formula: \(\text{MENN} = \frac{1}{N} \sum_{i=1}^N \text{NN}_i\) where:
    • \(N\): Total number of NN intervals.
    • \(\text{NN}_i\): \(i\)-th NN interval.
  • Interpretation:
    • The average interval between heartbeats (in milliseconds); the mean heart rate is 60000 / MENN beats per minute.
    • Higher values indicate a slower heart rate, lower values a faster heart rate.
  1. Median NN Interval (MDNN)
  • Definition: The median of all NN intervals.
  • Formula:
    • Sort the NN intervals and select the middle value.
  • Interpretation:
    • Less sensitive to outliers than the mean.
    • Provides a robust estimate of central tendency.
  1. Variance of NN Intervals (VNN)
  • Definition: The variance of NN intervals.
  • Formula: \(\text{VNN} = \frac{1}{N-1} \sum_{i=1}^N (\text{NN}_i - \text{MENN})^2\)
  • Interpretation:
    • Reflects overall HRV.
    • Higher variance indicates greater HRV.
  1. Standard Deviation of NN Intervals (SDNN)
  • Definition: The standard deviation of NN intervals.
  • Formula: \(\text{SDNN} = \sqrt{\text{VNN}}\)
  • Interpretation:
    • Most widely used time-domain HRV metric.
    • Reflects overall HRV and autonomic balance.
    • Higher SDNN: Better autonomic regulation, lower stress.
    • Lower SDNN: Poor autonomic regulation, chronic stress, or cardiovascular disease.
  1. Root Mean Square of Successive Differences (RMSSD)
  • Definition: The square root of the mean of the squares of successive NN interval differences.
  • Formula: \(\text{RMSSD} = \sqrt{\frac{1}{N-1} \sum_{i=1}^{N-1} (\text{NN}_{i+1} - \text{NN}_i)^2}\)
  • Interpretation:
    • Reflects short-term HRV and parasympathetic (vagal) activity.
    • Higher RMSSD: Stronger vagal tone, better stress resilience.
    • Lower RMSSD: Weakened vagal tone, stress, or health issues.
  1. Standard Deviation of Successive Differences (SDSD)
  • Definition: The standard deviation of successive NN interval differences.
  • Formula: \(\text{SDSD} = \sqrt{\frac{1}{N-1} \sum_{i=1}^{N-1} (\text{NN}_{i+1} - \text{NN}_i - \text{mean})^2}\)
  • Interpretation:
    • Similar to RMSSD but less commonly used.
    • Reflects variability in short-term HRV.
  1. NN50
  • Definition: The number of pairs of successive NN intervals that differ by more than 50 ms.
  • Formula: \(\text{NN50} = \text{Count}(|\text{NN}_{i+1} - \text{NN}_i| > 50 \text{ ms})\)
  • Interpretation:
    • Reflects short-term HRV.
    • Higher NN50: Better vagal tone.
  1. Proportion of NN50 (pNN50)
  • Definition: The proportion of NN50 divided by the total number of NN intervals
  • Formula: \(\text{pNN50} = \frac{\text{NN50}}{N} \times 100\%\)
  • Interpretation:
    • Normalized version of NN50
    • Higher pNN50 Stronger parasympathetic activity.
  1. NN20
  • Definition: The number of pairs of successive NN intervals that differ by more than 20 ms.
  • Formula: \(\text{NN20} = \text{Count}(|\text{NN}_{i+1} - \text{NN}_i| > 20 \text{ ms})\)
  • Interpretation:
    • Similar to NN50 but more sensitive to smaller changes.
  1. Proportion of NN20 (pNN20)
  • Definition: The proportion of NN20 divided by the total number of NN intervals.
  • Formula: \(\text{pNN20} = \frac{\text{NN20}}{N} \times 100\%\)
  • Interpretation:
    • Normalized version of NN20.
    • Higher pNN20: Better short-term HRV.

Reference Values

HRV depends strongly on the duration of the recording, age, fitness, posture and breathing, so values should only be compared between recordings of the same duration made under the same conditions. Approximate values for healthy adults:

Parameter Short-term (5 min, at rest) 24-hour recording
SDNN ~30–60 ms ~100–180 ms
RMSSD ~20–60 ms ~20–50 ms
pNN50 ~5–30% ~5–25%

For a comprehensive HRV analysis, time-domain metrics are often combined with:

Frequency-Domain Metrics:

  • LF (Low Frequency): 0.04–0.15 Hz (sympathetic + parasympathetic activity).
  • HF (High Frequency): 0.15–0.40 Hz (parasympathetic activity).
  • LF/HF Ratio: Traditionally interpreted as the sympatho-vagal balance, although this interpretation is disputed (LF power reflects mainly baroreflex activity).

Non-Linear Metrics:

  • Poincaré Plot: Visualizes short-term and long-term HRV.
  • Sample Entropy (SampEn): Measures complexity of HRV.
  • Detrended Fluctuation Analysis (DFA): Assesses fractal properties of HRV.

HRV Analysis in NeuroAnalyzer

Detecting R-peaks

hrv_detect() finds the ECG channel of the object, detects the R-peaks (peaks higher than the mean + 2 SD of the signal, at least 250 ms apart) and returns their positions (r_idx, in samples) and the intervals between them (nn_seg, in ms):

nn_seg, r_idx = hrv_detect(eeg)
println("Detected intervals: ", length(nn_seg))
Detected intervals: 1059

The detected peaks should be checked visually; the first 10 seconds:

ch = get_channel(eeg; type = "ecg")[1]
n10 = 10 * sr(eeg)
ecg = eeg.data[get_channel(eeg; ch = ch), 1:n10, 1][:]
t = eeg.time_pts[1:n10]
fig, ax, _ = lines(t,
                   ecg;
                   color = :black,
                   figure = (size = fig_size,),
                   axis = (ax_style...,
                           xlabel = "Time [s]",
                           ylabel = "Amplitude",
                           title = "ECG with detected R-peaks"))
r10 = r_idx[r_idx .<= n10]
scatter!(ax, t[r10], ecg[r10]; color = :red, markersize = 10)
fig

All R-peaks are detected correctly. There is no QRS complex at about 7 seconds (a gap in the signal or a non-conducted beat), so the interval between the peaks at 6.1 and 7.9 s is about twice as long as the others.

Checking the Intervals

Missing or falsely detected beats and ectopic beats produce intervals that do not reflect the normal (sinus) rhythm. They are seen in the tachogram (the series of intervals):

# median of the 11 neighbouring intervals
nb(i) = max(1, i - 5):min(length(nn_seg), i + 5)
local_med = [median(nn_seg[nb(i)]) for i in eachindex(nn_seg)]
# intervals differing by > 20% from the local median are not normal
ok = abs.(nn_seg .- local_med) .<= 0.2 .* local_med
println("Rejected intervals: ", count(!, ok), " of ", length(nn_seg))
fig, ax, _ = scatterlines(nn_seg;
                          color = :black,
                          markersize = 3,
                          figure = (size = fig_size,),
                          axis = (ax_style...,
                                  xlabel = "Interval",
                                  ylabel = "NN [ms]",
                                  title = "Tachogram"))
scatter!(ax, findall(!, ok), nn_seg[.!ok]; color = :red, markersize = 8)
fig
Rejected intervals: 55 of 1059

The tachogram shows two kinds of non-normal intervals (red): short intervals (about 570 ms) followed by long ones (about 1300 ms), the typical pattern of premature (ectopic) beats followed by a compensatory pause, and isolated intervals about twice as long as normal (a missing beat). They are removed before the analysis; even a few of them inflate the variability measures considerably. Removing intervals is a simple correction; for frequency-domain analyses, which require an evenly sampled series, the rejected intervals are usually interpolated instead.

Time-domain Measures

hrv_analyze() calculates the time-domain measures from the intervals; NN50 and NN20 are counts, pNN50 and pNN20 are proportions (multiply by 100 for %):

h_raw = hrv_analyze(nn_seg)
h = hrv_analyze(nn_seg[ok])
DataFrame(measure = collect(string.(keys(h))),
          all_intervals = round.(collect(values(h_raw)); digits = 3),
          normal_intervals = round.(collect(values(h)); digits = 3))
10×3 DataFrame
Row measure all_intervals normal_intervals
String Float64 Float64
1 menn 943.011 937.173
2 mdnn 941.406 941.406
3 vnn 14718.5 607.324
4 sdnn 121.32 24.644
5 rmssd 169.248 24.373
6 sdsd 169.328 24.385
7 nn50 112.0 19.0
8 pnn50 0.106 0.019
9 nn20 134.0 43.0
10 pnn20 0.127 0.043

With all intervals, RMSSD and SDNN are inflated several times by the detection errors; after removing them, the mean heart rate is 60000 / MENN ≈ 64 beats per minute, and the short-term variability (RMSSD ≈ 24 ms) is within the typical range at rest.