Functional Near-Infrared Spectroscopy

Initialize NeuroAnalyzer
using NeuroAnalyzer
import CairoMakie
# 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
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 = CairoMakie.LinearTicks(10),
            xminorticksvisible = true,
            xminorticks = CairoMakie.IntervalsBetween(10),
            xautolimitmargin = (0, 0),
            yautolimitmargin = (0.1, 0.1))

Functional Near-Infrared Spectroscopy (fNIRS) is a non-invasive, optical neuroimaging technique that measures brain activity by detecting changes in blood oxygenation and flow. It is based on the principles of near-infrared spectroscopy (NIRS) and provides real-time, portable, and wearable imaging of brain function. fNIRS is increasingly used in cognitive neuroscience, clinical research, and brain-computer interfaces (BCIs) due to its low cost, safety, and ease of use.

fNIRS is a functional neuroimaging modality that uses near-infrared light (650–900 nm) to measure changes in oxygenated hemoglobin (HbO) and deoxygenated hemoglobin (HbR) in the brain. - It is based on the neurovascular coupling principle, where neural activity leads to localized changes in blood flow and oxygenation.

Key Features

Feature Description
Signal Source Changes in HbO and HbR due to neural activity.
Temporal Resolution Sampling rate ~10 Hz; responses are slow (seconds).
Spatial Resolution 1–3 cm (dependent on optode spacing).
Invasiveness Non-invasive (no ionizing radiation or contrast agents).
Portability Wearable and portable systems available for real-world use.
Cost Lower cost compared to fMRI or MEG.

Near-Infrared Light and Tissue

  • Near-infrared light (650–900 nm) penetrates scalp and skull but is absorbed by hemoglobin in the brain.
  • Oxyhemoglobin (HbO) and deoxyhemoglobin (HbR) have different absorption spectra:
    • HbR absorbs more below the isosbestic point (~800 nm), e.g. at ~760 nm.
    • HbO absorbs more above it, e.g. at ~850 nm.
  • The difference in absorption between HbO and HbR is used to estimate changes in oxygenation.

Modified Beer-Lambert Law

The absorption of light in tissue is described by the Beer-Lambert law:

\[ A = \log \left( \frac{I_0}{I} \right) = \epsilon \cdot c \cdot d \cdot DPF + G \]

where:
\(A\) is the absorbance,
\(I_0\) is the incident light intensity,
\(I\) is the transmitted light intensity,
\(\epsilon\) is the molar extinction coefficient (depends on wavelength),
\(c\) is the concentration of HbO or HbR,
\(d\) is the distance between source and detector,
\(DPF\) is the differential path length factor (the light travels a longer, scattered path than \(d\)),
\(G\) is the scattering losses (empirically determined).

For fNIRS, the change in absorbance (\(\Delta A\)) is related to the change in concentration of HbO and HbR:

\[ \Delta A(\lambda) = (\epsilon_{HbO}(\lambda) \cdot \Delta [HbO] + \epsilon_{HbR}(\lambda) \cdot \Delta [HbR]) \cdot d \cdot DPF \]

where:
\(\epsilon_{HbO}(\lambda)\) and \(\epsilon_{HbR}\) are extinction coefficients at wavelength \(\lambda\),
\(\Delta [HbO]\) and \(\Delta [HbR]\) are the changes in HbO and HbR concentrations.

Instrumentation

Light Sources

  • Near-infrared LEDs or lasers: Typically use 2–4 wavelengths (e.g., 690 nm, 830 nm) to distinguish between HbO and HbR.
  • Laser diodes: Provide higher power and stability but are more expensive.

Detectors

  • Photodiodes or avalanche photodiodes (APDs): Detect transmitted or reflected light.
  • Avalanche photodiodes (APDs): More sensitive but require higher voltage.

Optodes

  • Source optodes: Emit near-infrared light into the scalp.
  • Detector optodes: Measure the light that passes through the brain.
  • Optode spacing: Typically 2.5–3.5 cm to balance depth penetration and signal quality.

fNIRS Systems

  1. Continuous-Wave (CW) fNIRS:
  • Measures changes in light intensity.
  • No depth resolution (only measures superficial cortex).
  • Lower cost and portable.
  1. Time-Domain (TD) fNIRS:
  • Measures time-of-flight of photons.
  • Provides depth resolution (can distinguish between superficial and deep signals).
  • Higher cost and complexity.
  1. Frequency-Domain (FD) fNIRS:
  • Measures amplitude and phase of modulated light.
  • Provides depth resolution and quantitative concentration measurements.
  • Moderate cost.

fNIRS Signal Analysis

Preprocessing

  1. Noise Reduction:
  • Apply band-pass filters (e.g., 0.01–0.2 Hz) to remove high-frequency noise and low-frequency drifts.
  • Use motion artifact correction (e.g., spline interpolation, PCA-based methods).
  1. Signal Normalization:
  • Normalize signals to baseline or global average to reduce inter-subject variability.
  1. Channel Selection:
  • Select channels based on anatomical landmarks or statistical significance.

Hemodynamic Response Function (HRF)

  • fNIRS signals reflect the hemodynamic response, which is delayed and smoothed compared to neural activity.
  • The canonical HRF is modeled as a difference of two gamma functions (a peak at about 5–6 s followed by an undershoot): \(h(t) = \frac{t^{a_1 - 1} e^{-t}}{\Gamma(a_1)} - c \frac{t^{a_2 - 1} e^{-t}}{\Gamma(a_2)}\), typically with \(a_1 = 6\), \(a_2 = 16\), \(c = 1/6\) (\(t\) in seconds).

Hemoglobin Concentration Changes

  • The change in HbO and HbR is calculated using the modified Beer-Lambert law:

\[ \begin{bmatrix} \Delta [HbO] \\ \Delta [HbR] \end{bmatrix} = \frac{1}{d \cdot DPF} \begin{bmatrix} \epsilon_{HbO}(\lambda_1) & \epsilon_{HbR}(\lambda_1) \\ \epsilon_{HbO}(\lambda_2) & \epsilon_{HbR}(\lambda_2) \end{bmatrix}^{-1} \begin{bmatrix} \Delta A(\lambda_1) \\ \Delta A(\lambda_2) \end{bmatrix} \]

i.e. the two equations (one for each wavelength) are solved for the two unknown concentration changes.

Statistical Analysis

  1. General Linear Model (GLM):
    • Models the fNIRS signal as a linear combination of task conditions and nuisance variables.
    • Used to identify activation patterns (e.g., HbO increases during task performance).
  2. Connectivity Analysis:
    • Measures functional connectivity between brain regions (e.g., correlation, coherence).
  3. Multivariate Pattern Analysis (MVPA):
    • Uses machine learning to classify brain states or tasks based on fNIRS patterns.

Applications of fNIRS

Application Description
Cognitive Neuroscience Studying attention, memory, language, and decision-making.
Clinical Research Assessing neurodevelopmental disorders (e.g., autism, ADHD), stroke rehabilitation, and depression.
Brain-Computer Interfaces (BCIs) Using fNIRS for real-time neural decoding (e.g., motor imagery, mental arithmetic).
Neurofeedback Training individuals to regulate their brain activity for therapeutic purposes.
Pediatric Neuroimaging Safe and portable imaging for infants and children.
Sleep Research Monitoring brain activity during sleep without disrupting sleep.
Sports Science Assessing brain function during physical exercise.

Advantages of fNIRS

Advantage Description
Non-Invasive No ionizing radiation, no contrast agents, and safe for repeated use.
Portable and Wearable Systems are lightweight and portable, enabling real-world use.
Higher Sampling Rate Samples hemodynamic changes faster than fMRI (typically ~10 Hz).
Low Cost Lower cost compared to fMRI, PET, or MEG.
Safe for All Ages Can be used in infants, children, and clinical populations.
Multi-Modal Integration Can be combined with EEG, fMRI, and behavioral measures for comprehensive analysis.

Limitations of fNIRS

Limitation Description
Limited Spatial Resolution 1–3 cm resolution, limited to superficial cortex.
Depth Resolution Shallow penetration (primarily measures superficial cortex).
Hemodynamic Lag Delayed and smoothed response compared to neural activity.
Motion Artifacts Sensitive to head movements and environmental light.
Interpretation Challenges Requires expertise to distinguish neural activity from artifacts or systemic changes.
Cost of High-End Systems Time-domain (TD) and frequency-domain (FD) systems are expensive.

fNIRS vs. Other Neuroimaging Modalities

Modality Temporal Resolution Spatial Resolution Invasiveness Cost Applications
fNIRS Seconds 1–3 cm Non-invasive Low Cognitive neuroscience, clinical research.
EEG Milliseconds Centimetres Non-invasive Low Clinical EEG, BCIs.
fMRI Seconds 1–3 mm Non-invasive High Structural-functional mapping.
MEG Milliseconds 5–10 mm Non-invasive High Epilepsy, cognitive neuroscience.
PET Minutes 4–6 mm Radioactive tracer High Metabolic imaging.

Future Directions

  • High-Density fNIRS Arrays: Larger arrays with higher channel counts for better spatial resolution.
  • Wearable fNIRS Systems: Development of lightweight, wireless fNIRS headsets for real-world monitoring.
  • Multi-Modal Integration: Combining fNIRS with EEG, fMRI, or behavioral measures for comprehensive analysis.
  • Closed-Loop Systems: Integration with neurofeedback or BCIs for real-time brain activity modulation.
  • AI and Machine Learning: Using AI to decode fNIRS signals for BCIs and brain state prediction.

Processing and Analyzing fNIRS Data

Importing Data

NIRS data in the Homer2 .nirs format are imported using import_nirs():

n = import_nirs("files/nirs/fnirs.nirs")
info(n)
              Data type: NIRS
            File format: NIRS
            Source file: files/nirs/fnirs.nirs
         File size [MB]: 0.72
       Memory size [MB]: 0.9
                Subject:  
              Recording: 
        Recording notes: 
         Recording date: 
         Recording time: 
     Sampling rate (Hz): 25
Signal length [samples]: 9001
Signal length [seconds]: 360.04
     Number of channels: 12
              Epochs ID: 
       Number of epochs: 1
 Epoch length [samples]: 9001
 Epoch length [seconds]: 360.04
        Wavelength [nm]: [690.0, 830.0]
                Markers: no
      Channel locations: yes
Number of NIRS channels: 12

Channels:
 ch     label           type        unit    wavelength  
 ------ --------------- ----------- ------- ------------
 1      S1_D1 690       NIRS_INT    V       690.0       
 2      S1_D2 690       NIRS_INT    V       690.0       
 3      S1_D1 830       NIRS_INT    V       830.0       
 4      S1_D2 830       NIRS_INT    V       830.0       
 5      AUX1            NIRS_AUX    
 6      AUX2            NIRS_AUX    
 7      AUX3            NIRS_AUX    
 8      AUX4            NIRS_AUX    
 9      AUX5            NIRS_AUX    
 10     AUX6            NIRS_AUX    
 11     AUX7            NIRS_AUX    
 12     AUX8            NIRS_AUX    

and SNIRF files using import_snirf():

n_snirf = import_snirf("files/nirs/fnirs.snirf")
info(n_snirf)
              Data type: NIRS
            File format: SNIRF
            Source file: files/nirs/fnirs.snirf
         File size [MB]: 1.91
       Memory size [MB]: 0.29
                Subject: default:  
              Recording: 
        Recording notes: 
         Recording date: 2022-03-03
         Recording time: 12:03:48
     Sampling rate (Hz): 50
Signal length [samples]: 500
Signal length [seconds]: 10.0
     Number of channels: 72
              Epochs ID: 
       Number of epochs: 1
 Epoch length [samples]: 500
 Epoch length [seconds]: 10.0
        Wavelength [nm]: [760.0, 850.0]
                Markers: yes
      Channel locations: yes
Number of NIRS channels: 72

Channels:
 ch     label           type        unit    wavelength  
 ------ --------------- ----------- ------- ------------
 1      Tx4_Rx2 760 OD  NIRS_OD             760.0       
 2      Tx3_Rx2 760 OD  NIRS_OD             760.0       
 3      Tx1a_Rx2 760 OD NIRS_OD             760.0       
 4      Tx3_Rx1 760 OD  NIRS_OD             760.0       
 5      Tx2_Rx1 760 OD  NIRS_OD             760.0       
 6      Tx1b_Rx1 760 OD NIRS_OD             760.0       
 7      Tx4_Rx4 760 OD  NIRS_OD             760.0       
 8      Tx3_Rx4 760 OD  NIRS_OD             760.0       
 9      Tx5_Rx4 760 OD  NIRS_OD             760.0       
 10     Tx1c_Rx4 760 OD NIRS_OD             760.0       
 11     Tx3_Rx3 760 OD  NIRS_OD             760.0       
 12     Tx2_Rx3 760 OD  NIRS_OD             760.0       
 13     Tx5_Rx3 760 OD  NIRS_OD             760.0       
 14     Tx1d_Rx3 760 OD NIRS_OD             760.0       
 15     Tx9_Rx6 760 OD  NIRS_OD             760.0       
 16     Tx6a_Rx6 760 OD NIRS_OD             760.0       
 17     Tx8_Rx5 760 OD  NIRS_OD             760.0       
 18     Tx7_Rx5 760 OD  NIRS_OD             760.0       
 19     Tx6b_Rx5 760 OD NIRS_OD             760.0       
 20     Tx9_Rx8 760 OD  NIRS_OD             760.0       
 21     Tx10_Rx8 760 OD NIRS_OD             760.0       
 22     Tx6c_Rx8 760 OD NIRS_OD             760.0       
 23     Tx8_Rx7 760 OD  NIRS_OD             760.0       
 24     Tx7_Rx7 760 OD  NIRS_OD             760.0       
 25     Tx6d_Rx7 760 OD NIRS_OD             760.0       
 26     Tx12_Rx9 760 OD NIRS_OD             760.0       
 27     Tx13_Rx9 760 OD NIRS_OD             760.0       
 28     Tx11a_Rx9 760 ODNIRS_OD             760.0       
 29     Tx12_Rx11 760 ODNIRS_OD             760.0       
 30     Tx13_Rx11 760 ODNIRS_OD             760.0       
 31     Tx11c_Rx11 760 ODNIRS_OD             760.0       
 32     Tx14_Rx10 760 ODNIRS_OD             760.0       
 33     Tx11b_Rx10 760 ODNIRS_OD             760.0       
 34     Tx14_Rx12 760 ODNIRS_OD             760.0       
 35     Tx15_Rx12 760 ODNIRS_OD             760.0       
 36     Tx11d_Rx12 760 ODNIRS_OD             760.0       
 37     Tx4_Rx2 850 OD  NIRS_OD             850.0       
 38     Tx3_Rx2 850 OD  NIRS_OD             850.0       
 39     Tx1a_Rx2 850 OD NIRS_OD             850.0       
 40     Tx3_Rx1 850 OD  NIRS_OD             850.0       
 41     Tx2_Rx1 850 OD  NIRS_OD             850.0       
 42     Tx1b_Rx1 850 OD NIRS_OD             850.0       
 43     Tx4_Rx4 850 OD  NIRS_OD             850.0       
 44     Tx3_Rx4 850 OD  NIRS_OD             850.0       
 45     Tx5_Rx4 850 OD  NIRS_OD             850.0       
 46     Tx1c_Rx4 850 OD NIRS_OD             850.0       
 47     Tx3_Rx3 850 OD  NIRS_OD             850.0       
 48     Tx2_Rx3 850 OD  NIRS_OD             850.0       
 49     Tx5_Rx3 850 OD  NIRS_OD             850.0       
 50     Tx1d_Rx3 850 OD NIRS_OD             850.0       
 51     Tx9_Rx6 850 OD  NIRS_OD             850.0       
 52     Tx6a_Rx6 850 OD NIRS_OD             850.0       
 53     Tx8_Rx5 850 OD  NIRS_OD             850.0       
 54     Tx7_Rx5 850 OD  NIRS_OD             850.0       
 55     Tx6b_Rx5 850 OD NIRS_OD             850.0       
 56     Tx9_Rx8 850 OD  NIRS_OD             850.0       
 57     Tx10_Rx8 850 OD NIRS_OD             850.0       
 58     Tx6c_Rx8 850 OD NIRS_OD             850.0       
 59     Tx8_Rx7 850 OD  NIRS_OD             850.0       
 60     Tx7_Rx7 850 OD  NIRS_OD             850.0       
 61     Tx6d_Rx7 850 OD NIRS_OD             850.0       
 62     Tx12_Rx9 850 OD NIRS_OD             850.0       
 63     Tx13_Rx9 850 OD NIRS_OD             850.0       
 64     Tx11a_Rx9 850 ODNIRS_OD             850.0       
 65     Tx12_Rx11 850 ODNIRS_OD             850.0       
 66     Tx13_Rx11 850 ODNIRS_OD             850.0       
 67     Tx11c_Rx11 850 ODNIRS_OD             850.0       
 68     Tx14_Rx10 850 ODNIRS_OD             850.0       
 69     Tx11b_Rx10 850 ODNIRS_OD             850.0       
 70     Tx14_Rx12 850 ODNIRS_OD             850.0       
 71     Tx15_Rx12 850 ODNIRS_OD             850.0       
 72     Tx11d_Rx12 850 ODNIRS_OD             850.0       

The example .nirs recording contains two measurement channels (source S1 with detectors D1 and D2), each at two wavelengths (690 and 830 nm), recorded as raw light intensity (nirs_int), and 8 auxiliary channels (nirs_aux):

DataFrame(label = labels(n),
          type = n.header.recording[:channel_type],
          unit = n.header.recording[:unit])
12×3 DataFrame
Row label type unit
String String String
1 S1_D1 690 nirs_int V
2 S1_D2 690 nirs_int V
3 S1_D1 830 nirs_int V
4 S1_D2 830 nirs_int V
5 AUX1 nirs_aux
6 AUX2 nirs_aux
7 AUX3 nirs_aux
8 AUX4 nirs_aux
9 AUX5 nirs_aux
10 AUX6 nirs_aux
11 AUX7 nirs_aux
12 AUX8 nirs_aux

Optode locations of the SNIRF recording: sources in red, detectors in green (black and white in monochrome mode); a line connects the source and the detector of each pair (dashed for short-separation pairs) and the channels (pairs) are shown at the midpoints, numbered in the order of the pairs (as in nirs_quality(), see below):

plot_locs(n_snirf;
          ch = "all",
          gui = false)

A schematic montage (schematic = true): sources as diamonds, detectors as circles, channels as numbered squares (short-separation channels, lying next to their optodes, are smaller):

plot_locs(n_snirf;
          ch = "all",
          schematic = true,
          gui = false)

Channels can be highlighted (sch, e.g. the pairs of interest), the optodes labelled (src_labels, det_labels) and a value shown for each pair (weights, one value per pair). Channel labels of SNIRF files contain the optode labels of the probe (e.g. Tx3_Rx2 760 OD). Here, the pairs of source Tx3 are highlighted and the source-detector distances (in mm, see nirs_distance()) are shown:

# source-detector distance of each pair (in the order of the pairs)
d_pair = round.(Int, nirs_quality(n_snirf).distance)
plot_locs(n_snirf;
          ch = "all",
          sch = r"^Tx3_",
          weights = d_pair,
          schematic = true,
          src_labels = true,
          gui = false)

Wavelengths:

n.header.recording[:wavelengths]
2-element Vector{Float64}:
 690.0
 830.0

Channels of a given wavelength:

ch690 = get_channel(n; wl = 690)
ch830 = get_channel(n; wl = 830)
println("690 nm: ", ch690)
println("830 nm: ", ch830)
690 nm: ["S1_D1 690", "S1_D2 690"]
830 nm: ["S1_D1 830", "S1_D2 830"]

Signal Quality

Before the analysis, the quality of each source-detector pair is checked. nirs_quality() reports for each pair:

  • the source-detector distance in mm (nirs_distance()), calculated from the 3-D optode positions; channels shorter than about 15 mm are short-separation channels (see below);
  • the scalp coupling index (SCI, nirs_sci()): the correlation between the two wavelengths of the pair, band-pass filtered in the range of the heartbeat (0.5–2.5 Hz). With good contact between the optodes and the scalp, the cardiac pulsation is visible at both wavelengths and the SCI is close to 1; SCI < 0.75 indicates poor coupling;
  • the coefficient of variation of the raw intensity (CV, nirs_cv(), 100 × SD / mean, the largest of the wavelengths of the pair); CV > 15% indicates a noisy channel (poor coupling, motion, low light level).

A pair is marked as bad if its SCI is below sci_t or its CV is above cv_t:

q = nirs_quality(n; sci_t = 0.75, cv_t = 15)
2×5 DataFrame
Row pair distance sci cv bad
String Float64 Float64 Float64 Bool
1 S1_D1 30.0 0.940377 4.74574 false
2 S1_D2 30.0 0.944796 7.3933 false

Both pairs of the example recording are good. Bad pairs would be removed (all their channels, at all wavelengths) with delete_pair():

bad = q[q.bad, :pair]
isempty(bad) || delete_pair!(n; pair = bad)

Optical Density

intensity2od!() converts the raw intensity to the change of optical density (OD, \(-\log(|I| / \bar{I})\), relative to the mean intensity; zero or non-finite intensities raise an error); the OD channels (type nirs_od) are added after the intensity channels:

intensity2od!(n)
labels(n)[1:8]
8-element Vector{String}:
 "S1_D1 690"
 "S1_D2 690"
 "S1_D1 830"
 "S1_D2 830"
 "S1_D1 690 OD"
 "S1_D2 690 OD"
 "S1_D1 830 OD"
 "S1_D2 830 OD"

Motion Artifacts

Head movements shift the optodes on the scalp and cause spikes (fast, short changes of the light intensity) and baseline shifts (step changes) in the signal. tddr() corrects them using the temporal derivative distribution repair (TDDR, Fishburn et al. 2019): the derivative of the signal is robustly re-weighted, so that its outlying (fast) changes, which are caused by motion, are reduced, and the signal is reconstructed from the corrected derivative. The method needs no parameters and is applied to the OD channels (default), before filtering.

The example recording contains no large artifacts; to show the method, a spike and a baseline shift are added to a copy of the data:

n_mot = deepcopy(n)
ch_od = get_channel(n_mot; ch = "S1_D1 690 OD")[1]
fs = sr(n_mot)
# spike at 100 s, shift from 200 s
n_mot.data[ch_od, round(Int, 100 * fs):round(Int, 101 * fs), 1] .+= 0.3
n_mot.data[ch_od, round(Int, 200 * fs):end, 1] .+= 0.2
n_tddr = tddr(n_mot)
fig = CairoMakie.Figure(size = fig_size)
ax = CairoMakie.Axis(fig[1, 1];
                     ax_style...,
                     xlabel = "Time [s]",
                     ylabel = "OD",
                     title = "S1_D1 690 OD")
t = n_mot.time_pts
CairoMakie.lines!(ax, t, n_mot.data[ch_od, :, 1];
                  color = :gray,
                  label = "with artifacts")
CairoMakie.lines!(ax, t, n_tddr.data[ch_od, :, 1];
                  color = :black,
                  label = "TDDR")
CairoMakie.axislegend(ax; position = :lt)
fig

The baseline shift and most of the spike are removed, and the slow hemodynamic changes are kept. A brief transient remains at the onset of each artifact: TDDR corrects only the low-frequency part of the signal (below 0.5 Hz), while the faster part (e.g. the heartbeat) is left unchanged. The output is centered, so its offset differs from the input. The correction is applied in place with tddr!():

tddr!(n)

Filtering

The hemodynamic response is slow (it peaks about 5–6 s after the stimulus), so the signal of interest is below about 0.2 Hz. The OD signals are band-pass filtered (0.01–0.2 Hz) to remove slow drifts and physiological noise: the heartbeat (about 1 Hz), respiration (about 0.2–0.3 Hz; partly overlapping the response) and Mayer waves (about 0.1 Hz) cannot be removed completely by filtering.

NeuroAnalyzer.filter!(n;
                      ch = get_channel(n; type = "nirs_od"),
                      fprototype = :butterworth,
                      ftype = :bp,
                      cutoff = (0.01, 0.2),
                      order = 4)

Hemoglobin Concentration

od2conc!() converts OD to the changes of the concentration of oxygenated (HbO), deoxygenated (HbR) and total (HbT = HbO + HbR) hemoglobin using the modified Beer-Lambert law. For each measurement channel three channels are added (types nirs_hbo, nirs_hbr, nirs_hbt):

# copy of the OD data (used below)
n_od = deepcopy(n)
od2conc!(n)
# get_channel(; type) returns labels, get_channel(; ch) returns indices
hb_types = ["nirs_hbo", "nirs_hbr", "nirs_hbt"]
ch_hb = get_channel(n; ch = get_channel(n; type = hb_types))
DataFrame(label = labels(n)[ch_hb],
          type = n.header.recording[:channel_type][ch_hb],
          unit = n.header.recording[:unit][ch_hb])
6×3 DataFrame
Row label type unit
String String String
1 S1_D1 HbO nirs_hbo μM·mm
2 S1_D1 HbR nirs_hbr μM·mm
3 S1_D1 HbT nirs_hbt μM·mm
4 S1_D2 HbO nirs_hbo μM·mm
5 S1_D2 HbR nirs_hbr μM·mm
6 S1_D2 HbT nirs_hbt μM·mm

By default the partial path length factor is 1 and the signal is not divided by the source-detector distance, so the concentrations are in μM·mm (the convention of Homer3). To obtain concentrations in μM, the OD is divided by the path length: the source-detector distance (calculated from the optode positions, in the length unit stored in the file) multiplied by

  • the differential pathlength factor (DPF) of each wavelength, calculated for the age of the subject (age, equation of Scholkmann & Wolf, 2013), or
  • partial path length factors given for each wavelength (ppf).

The DPF of a 30-year-old subject at the wavelengths of the recording:

nirs_dpf(; age = 30, wl = n.header.recording[:wavelengths])
2-element Vector{Float64}:
 6.32436462780845
 5.682365227808646

Concentrations in μM, from the copy of the OD data:

n_um = od2conc(n_od; age = 30)

The data of channel S1_D1:

hb = n.data[get_channel(n; ch = ["S1_D1 HbO", "S1_D1 HbR"]), :, :]

Removing Channels

Channels are removed with delete_channel() or keep_channel(). An intensity or OD channel is removed (or kept) together with the channels of the same optode pair at the other wavelengths, since the conversion to concentration needs all wavelengths of a pair.

All channels of a source-detector pair (e.g. a channel with poor scalp coupling), at all wavelengths and processing stages, are removed with delete_pair(); the optodes are kept, as they may be used by other pairs (delete_optode() removes an optode with all its channels):

n_del = delete_pair(n; pair = "S1_D2")
labels(n_del)
15-element Vector{String}:
 "S1_D1 690"
 "S1_D1 830"
 "S1_D1 690 OD"
 "S1_D1 830 OD"
 "S1_D1 HbO"
 "S1_D1 HbR"
 "S1_D1 HbT"
 "AUX1"
 "AUX2"
 "AUX3"
 "AUX4"
 "AUX5"
 "AUX6"
 "AUX7"
 "AUX8"

Keeping only the concentration channels (e.g. for the analysis, to reduce memory use):

n_hb = keep_channel(n; ch = get_channel(n; type = ["nirs_hbo", "nirs_hbr"]))
labels(n_hb)
4-element Vector{String}:
 "S1_D1 HbO"
 "S1_D1 HbR"
 "S1_D2 HbO"
 "S1_D2 HbR"

Simulated Task

The example recording contains no stimulus markers and no short-separation channel. To show the analysis of a task experiment, both are simulated:

  • detector D2 is moved to 8 mm from the source, so that S1_D2 becomes a short-separation channel;
  • seven 15-s task blocks (markers task, every 45 s from 30 s) are added;
  • a hemodynamic response (the task blocks convolved with the canonical HRF, see nirs_hrf()) is added to channel S1_D1: an increase of HbO and a smaller decrease of HbR.
n_task = deepcopy(n)
# short-separation channel: D2 8 mm from S1
locs = n_task.locs
s1 = findfirst(==("S1"), locs.label)
d2 = findfirst(==("D2"), locs.label)
locs[d2, :loc_x] = locs[s1, :loc_x]
locs[d2, :loc_y] = locs[s1, :loc_y] + 8
# task blocks
onsets = 30:45:330
for o in onsets
    add_marker!(n_task;
                id = "stim",
                start = Float64(o),
                len = 15.0,
                value = "task",
                ch = 0)
end
# hemodynamic response: boxcar convolved with the HRF
fs = sr(n_task)
u = zeros(epoch_len(n_task))
for o in onsets
    u[(round(Int, o * fs) + 1):round(Int, (o + 15) * fs)] .= 1
end
h = nirs_hrf(; fs = fs).h
hrf = NeuroAnalyzer.DSP.conv(u, h)[1:epoch_len(n_task)]
ho, hr, ht = get_channel(n_task;
                         ch = ["S1_D1 HbO", "S1_D1 HbR", "S1_D1 HbT"])
# amplitude of the response (about 1 SD of the HbO signal)
a = 60
n_task.data[ho, :, 1] .+= a .* hrf
n_task.data[hr, :, 1] .-= a / 3 .* hrf
n_task.data[ht, :, 1] .+= 2a / 3 .* hrf

Source-detector distances:

d = nirs_distance(n_task)
DataFrame(channel = d.ch, distance = d.d)
14×2 DataFrame
Row channel distance
String Float64
1 S1_D1 690 30.0
2 S1_D2 690 8.0
3 S1_D1 830 30.0
4 S1_D2 830 8.0
5 S1_D1 690 OD 30.0
6 S1_D2 690 OD 8.0
7 S1_D1 830 OD 30.0
8 S1_D2 830 OD 8.0
9 S1_D1 HbO 30.0
10 S1_D1 HbR 30.0
11 S1_D1 HbT 30.0
12 S1_D2 HbO 8.0
13 S1_D2 HbR 8.0
14 S1_D2 HbT 8.0

The canonical HRF:

h = nirs_hrf(; fs = sr(n))
CairoMakie.lines(h.t, h.h;
                 color = :black,
                 figure = (size = fig_size,),
                 axis = (ax_style...,
                         xlabel = "Time [s]",
                         ylabel = "Amplitude",
                         title = "Canonical HRF"))

Short-Separation Regression

The light of a short-separation channel (source-detector distance below about 15 mm, typically 8 mm) does not reach the brain: it measures the hemodynamics of the scalp, i.e. the systemic physiology (heartbeat, respiration, Mayer waves, changes of the blood pressure) that also contaminates the long channels. nirs_ssr() regresses the nearest short channel of the same type out of each long channel (HbO and HbR channels by default; channels with distance < short_t mm are short channels):

\[ y_{corrected} = y - \beta \cdot (x - \bar{x}), \quad \beta = \frac{cov(x, y)}{var(x)} \]

where \(y\) is the long channel and \(x\) the short channel.

n_ssr = nirs_ssr(n_task; short_t = 15)
fig = CairoMakie.Figure(size = fig_size)
ax = CairoMakie.Axis(fig[1, 1];
                     ax_style...,
                     xlabel = "Time [s]",
                     ylabel = "Δ HbO [μM·mm]",
                     title = "S1_D1 HbO")
t = n_task.time_pts
CairoMakie.lines!(ax, t, n_task.data[ho, :, 1];
                  color = :gray,
                  label = "original")
CairoMakie.lines!(ax, t, n_ssr.data[ho, :, 1];
                  color = :red,
                  label = "short-separation regression")
for o in onsets
    CairoMakie.vspan!(ax, o, o + 15; color = (:gray, 0.2))
end
CairoMakie.axislegend(ax; position = :lb)
fig

The slow fluctuations common to both channels are removed and the responses to the task blocks (gray) are clearer.

Block Average

The responses to the task blocks are averaged: the signal is divided into epochs from 5 s before to 25 s after each marker, and average_epochs() averages them (after subtracting the mean of the baseline, bl). The averaged response is the first epoch of the output object, followed by the individual epochs (the auxiliary channels are removed):

e = epoch(n_ssr;
          marker = "task",
          offset = 5,
          ep_len = 30)
e_avg = average_epochs(e; bl = (-5, 0))

plot_hb() plots HbO (red) and HbR (blue) of each source-detector pair in one panel (optionally also HbT, green, with hbt = true); for the averaged object, epoch 1 is the averaged response:

plot_hb(e_avg;
        pair = "S1_D1",
        ep = 1,
        title = "Averaged response")

HbO peaks after the end of the 15-s block (the response is delayed by several seconds) and HbR decreases.

Activation: General Linear Model

nirs_glm() estimates the activation using the general linear model. For each condition (marker value), the task blocks (marker onsets and lengths, or duration) are convolved with the canonical HRF; the design matrix contains these regressors, a constant and slow drifts (a discrete cosine basis with periods longer than 1 / drift s). The fNIRS noise is serially correlated (the physiological signals are slow), which makes the ordinary least-squares statistics too optimistic, so the model is prewhitened with an autoregressive model of the residuals (order selected by BIC, up to ar; as in the AR-IRLS method of Barker et al. 2013).

The β coefficient is the amplitude of the response (plateau of a long block, in the units of the channel):

glm = nirs_glm(n_ssr;
               ch = ["S1_D1 HbO", "S1_D1 HbR"],
               cond = "task",
               drift = 0.01)
2×7 DataFrame
Row channel condition beta se t df p
String String Float64 Float64 Float64 Int64 Float64
1 S1_D1 HbO task 55.9625 0.933563 59.9451 8975 0.0
2 S1_D1 HbR task -14.5261 0.611019 -23.7736 8975 3.30658e-121

The simulated activation (60 μM·mm for HbO, −20 μM·mm for HbR) is found. Without the short-separation regression, the systemic noise increases the standard errors:

nirs_glm(n_task;
         ch = ["S1_D1 HbO", "S1_D1 HbR"],
         cond = "task")
2×7 DataFrame
Row channel condition beta se t df p
String String Float64 Float64 Float64 Int64 Float64
1 S1_D1 HbO task 56.3906 3.20558 17.5914 8980 3.95213e-68
2 S1_D1 HbR task -11.6722 1.4796 -7.8888 8944 3.41004e-15

Plotting

Intensity, OD and hemoglobin channels (the auxiliary channels are plotted separately, below):

ch_nirs = ["nirs_int", "nirs_od", "nirs_hbo", "nirs_hbr", "nirs_hbt"]
NeuroAnalyzer.plot(n;
                   ch = get_channel(n; type = ch_nirs),
                   seg = (0, 60),
                   gui = false)

HbO and HbR of both channels over the whole recording:

NeuroAnalyzer.plot(n;
                   ch = ["S1_D1 HbO", "S1_D2 HbO"],
                   type = :butterfly,
                   seg = (0, 360),
                   title = "HbO",
                   gui = false)
NeuroAnalyzer.plot(n;
                   ch = ["S1_D1 HbR", "S1_D2 HbR"],
                   type = :butterfly,
                   seg = (0, 360),
                   title = "HbR",
                   gui = false)

HbO and HbR of the source-detector pairs (stimulus markers are shown as gray blocks):

plot_hb(n_task; seg = (0, 120))

The auxiliary channels contain signals of other devices, with different amplitudes; each of them is scaled separately, so they do not compress the other channels of the plot:

NeuroAnalyzer.plot(n;
                   ch = get_channel(n; type = "nirs_aux"),
                   seg = (0, 60),
                   gui = false)

During neural activation HbO increases and HbR decreases (with a delay of a few seconds); slow fluctuations that are common to HbO and HbR and to both channels are mostly of systemic (non-neural) origin.

Topographical Maps

For NIRS objects, plot_topo() places the value of each channel at the midpoint between its source and detector. Since the optodes usually cover only a part of the head, the map is masked (mask = true is the default for NIRS): it is shown only near the channels.

The example SNIRF recording contains 36 source-detector pairs (OD data), including short-separation channels. Its OD channels are converted to hemoglobin concentrations; the map shows the mean HbO of the long channels (nmethod = :none: the values are not normalized):

n_s = od2conc(n_snirf)
d = nirs_distance(n_s)
ch_long = d.ch[d.d .>= 15]
ch_hbo = filter(l -> endswith(l, "HbO") && l in ch_long, labels(n_s))
hbo = n_s.data[get_channel(n_s; ch = ch_hbo), :, 1]
m = vec(sum(hbo; dims = 2)) ./ size(hbo, 2)
plot_topo(n_s;
          ch = ch_hbo,
          data = m,
          ch_labels = false,
          nmethod = :none,
          cb_title = "Δ HbO [μM·mm]",
          title = "Mean HbO")

Exporting Data

export_snirf() saves a continuous NIRS object as a SNIRF file: intensity, OD and concentration channels, optode labels and positions, markers (one stimulus group per marker value) and auxiliary channels:

f = tempname() * ".snirf"
export_snirf(n_task; file_name = f)
n_imp = import_snirf(f)
println("channels: ", nchannels(n_imp))
println("markers: ", nrow(n_imp.markers))
channels: 22
markers: 7