Coherence

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 DSP
using Statistics
NeuroAnalyzer.progress_bar = false

# resting-state EEG, EEG channels only, 10-second epochs
eeg = load_neuro("files/eeg/eeg.hdf")
eeg = keep_channel(eeg; ch = "eeg")
e10 = epoch(eeg; ep_len = 10)

Coherence measures the consistency of the phase relationship between two signals across trials or time windows - quantifying how reliably two channels oscillate together at a given frequency.

Where cross-correlation operates in the time domain, coherence operates in the frequency domain: it asks not just whether two signals are related, but at which frequencies their relationship is stable.

Cross-Power Spectral Density

Coherence is computed from the Cross-Power Spectral Density (CPSD) - a frequency-domain measure of the relationship between two signals, describing how the power of one signal relates to another at each frequency.

In practice, for discrete signals \(x[n]\) and \(y[n]\), the CPSD is estimated by multiplying the Fast Fourier Transform (FFT) of one signal by the complex conjugate of the FFT of the second signal:

\[ P_{xy}(f) = X(f) \times Y^*(f) \]

where:
\(X(f)\) is the Fourier transform of \(x\),
\(Y^*(f)\) is the complex conjugate of the Fourier transform of \(y\).

The result \(P_{xy}\) is complex-valued at each frequency, encoding two distinct pieces of information:

  • Magnitude \(\vert P_{xy} \vert\) - the strength of the relationship between \(x\) and \(y\) at that frequency
  • Phase \(angle P_{xy}\) - the phase difference between the two signals at that frequency

Coherence is then obtained by normalizing the CPSD by the auto-spectral densities of both signals:

\[ C_{xy}(f) = \frac{\vert P_{xy}(f) \vert^2}{P_{xx}(f) \times P_{yy}(f)} \]

which scales the result to the range \([0, 1]\), removing the influence of each signal’s individual power and isolating the consistency of their phase relationship.

Computing CPSD between O1 and O2 in the 10th epoch:

cp, f = cpsd(e10,
             e10;
             ch1 = "O1",
             ch2 = "O2",
             ep1 = 10,
             ep2 = 10,
             method = :mt)

Three estimation methods are available via the method parameter:

  1. :fft - Fast Fourier transform; fast and straightforward, suitable for stationary signals
  2. :mt - multi-taper; reduces spectral leakage by averaging across multiple orthogonal tapers, producing a more stable estimate
  3. :stft - short-time Fourier transform; computes CPSD in sliding time windows, suitable for non-stationary signals where the frequency content changes over time

Plotting magnitudes:

plot_psd(f,
         abs.(cp[1, :, 1]);
         flim = (0, 40),
         xlabel = "Frequency [Hz]",
         ylabel = "Magnitude",
         title = "CPSD magnitude, O1-O2")

Magnitude peaks in the CPSD indicate strong connectivity between the two signals at those specific frequencies - the larger the magnitude, the more consistently the two signals co-vary at that frequency across the observation window.

Plotting phases:

f_idx = vsearch(40, f)
plot_phase(DSP.angle.(cp[1, 1:f_idx, 1]),
           f[1:f_idx])

The phase of the CPSD is close to 0 at the frequencies with high magnitude (the signals of O1 and O2 are nearly in phase) and more variable at frequencies where there is little common power.

Phase information reveals the temporal relationship between the two signals at each frequency - a consistent non-zero phase indicates that one signal systematically leads or lags the other. This may suggest a directional influence, but a phase lag alone does not prove it (see e.g. Granger causality and PSI in the other connectivity measures tutorial).

CPSD can also be compared across conditions at the same electrode location - for example, rest vs. task, or healthy vs. patient groups - to identify frequency-specific changes in inter-regional connectivity associated with cognitive state or pathology.

Coherence

Definition

Coherence is defined as the normalized cross-spectral density between two signals \(x\) and \(y\):

\[ C_{xy}(f) = \frac{\vert S_{xy}(f)\vert ^2}{S_{xx}(f) \times S_{yy}(f)} \]

where:
\(S_{xy}(f)\) is the cross-spectral density of \(x\) and \(y\),
\(S_{xx}(f)\) and \(S_{yy}(f)\) are the auto-spectral densities (power spectra) of \(x\) and \(y\) respectively.

For multi-epoch signal, the complex cross-spectrum \(S_{xy}\) and the auto-spectra \(S_{xx}\) and \(S_{yy}\) are computed across all epochs. Then, \(S_{xy}\), \(S_{xx}\) and \(S_{yy}\) are averaged over all segments. Finally, coherence is calculated from the averaged spectrum and auto-spectra at each frequency bin.

Key properties:

  • Values range from 0 (no consistent relationship) to 1 (perfectly consistent phase relationship at that frequency)
  • Coherence of 1 at a given frequency means the two signals maintain a constant phase difference at that frequency across all observations
  • Coherence is symmetric - \(C_{xy}(f) = C_{yx}(f)\) - and therefore cannot reveal directionality
  • Coherence requires averaging across trials or time segments to produce a stable estimate; computed from a single segment without averaging, it is always 1

Magnitude-squared coherence (MSC) - the squared absolute value of coherence, as defined above, emphasizing strong relationships

Both coherence and magnitude-squared coherence (MSC) measure the linear relationship between two signals in the frequency domain - differing primarily in whether phase information is retained.

Coherence is complex-valued, encoding both the magnitude and the phase of the relationship between two signals at each frequency:

\[ C_{xy}(f) = \frac{P_{xy}(f)}{\sqrt{P_{xx}(f) \times P_{yy}(f)}} \]

where:
\(P_{xy}\) is the cross-power spectral density,
\(P_{xx}\), \(P_{yy}\) are the auto-power spectral densities of \(x\) and \(y\).

  • Magnitude \(\vert C_{xy} \vert\) - strength of the linear relationship (0 = none, 1 = perfect)
  • Phase \(\angle C_{xy}\) - phase difference between the signals at each frequency

Magnitude-squared coherence (MSC) discards the phase and retains only the strength of the relationship. It is always a real number in \([0, 1]\):

\[ MSC_{xy}(f) = \frac{\vert P_{xy}(f) \vert^2}{P_{xx}(f) \times P_{yy}(f)} = \vert C_{xy}(f)\vert^2 \]

Interpretation is the same as coherence magnitude: 0 indicates no linear relationship at that frequency, 1 indicates a perfect linear relationship.

Imaginary Coherence (IC) uses only the imaginary component of the cross-spectrum, measures coherence while ignoring zero-lag synchronization (which may be due to volume conduction), making it insensitive to volume-conducted signals that appear with zero phase lag.

Formula:

\[ \text{IC} = \vert \Im(C_{xy}(f)) \vert \]

Interpretation:

  • IC = 0: No synchronization.
  • IC > 0: Significant synchronization at frequency \(f\).

Advantages:

  • Reduces volume conduction effects.
  • Frequency-specific: Can be computed for specific frequency bands.

Which to use:

  • Use coherence (coherency) when both the strength and the phase lag/lead are of interest.
  • Use MSC when only the strength of frequency-specific coupling is needed - e.g. for detecting synchronization between channels.
  • Use imaginary coherence to reduce the effects of volume conduction (at the cost of missing true zero-lag coupling).

Computing coherence, imaginary part of coherence and magnitude-squared coherence using multi-taper method:

coh_data = NeuroAnalyzer.coherence(e10,
                                   e10;
                                   ch1 = "Fp1",
                                   ch2 = "Fp2",
                                   method = :mt)

Three estimation methods are available via the method parameter:

  1. :fft - Fast Fourier transform; fast and straightforward, suitable for stationary signals
  2. :mt - multi-taper; reduces spectral leakage by averaging across multiple orthogonal tapers, producing a more stable estimate
  3. :stft - short-time Fourier transform; computes CPSD in sliding time windows, suitable for non-stationary signals where the frequency content changes over time

Getting phases:

coh_ph = DSP.angle.(coh_data.coh)

Getting magnitudes:

coh = abs.(coh_data.coh)

Tip: coherence() is also exported by DSP.jl, so it is called with the NeuroAnalyzer. prefix.

Coherence between O1 and O2 in the 1–30 Hz range:

coh_data = NeuroAnalyzer.coherence(e10,
                                   e10;
                                   ch1 = "O1",
                                   ch2 = "O2",
                                   flim = (1, 30))

Magnitude:

coh_mag = abs.(coh_data.coh)
plot_coherence(coh_mag[1, :],
               coh_data.f,
               ylabel = "",
               title = "Coherence (magnitude)")
plot_coherence(coh_data.msc[1, :],
               coh_data.f,
               ylabel = "",
               title = "MSC")
plot_coherence(coh_data.imcoh[1, :],
               coh_data.f,
               ylabel = "",
               title = "Coherence (imaginary part)")

The coherence of O1 and O2 is high (about 0.8) over the whole range, as expected for neighbouring electrodes (volume conduction and shared activity), while the imaginary part of coherence is close to 0: the signals are nearly in phase.

Coherence of several pairs of channels (ch1[i] with ch2[i]):

ch1 = ["Fp1", "F3", "C3", "P3"]
ch2 = ["Fp2", "F4", "C4", "P4"]
coh_data = NeuroAnalyzer.coherence(e10,
                                   e10;
                                   ch1 = ch1,
                                   ch2 = ch2,
                                   flim = (1, 30))

areduce() reduces the number of frequencies (here to steps of 0.1 Hz) for plotting:

coh, _ = areduce(abs.(coh_data.coh), coh_data.f; n = 0.1)
mscoh, f = areduce(coh_data.msc, coh_data.f; n = 0.1)

Labels of the pairs:

l = paired_labels(ch1, ch2)
4-element Vector{String}:
 "Fp1-Fp2"
 "F3-F4"
 "C3-C4"
 "P3-P4"
plot_coherence(mscoh,
               f;
               clabels = l,
               title = "Magnitude-squared coherence")
plot_coherence(mscoh,
               f;
               clabels = l,
               avg = true,
               title = "Averaged magnitude-squared coherence")
plot_coherence(mscoh,
               f;
               clabels = l,
               ci95 = true,
               title = "Magnitude-squared coherence")

The mean coherence of each pair can be plotted as connections between the electrodes; the connection matrix is indexed by the positions of the channels in the object:

coh_avg = round.(vec(mean(coh; dims = 2)); digits = 2)
c = zeros(nchannels(eeg), nchannels(eeg))
for idx in eachindex(ch1)
    i1 = get_channel(eeg; ch = ch1[idx])[1]
    i2 = get_channel(eeg; ch = ch2[idx])[1]
    c[i1, i2] = coh_avg[idx]
end
plot_locs(eeg;
          ch = "eeg",
          connections = c,
          gui = false)

Tip: plotting connections requires channel locations. Line widths and transparency are scaled by the connection values; positive values are drawn in red and negative values in blue (with mono = true: solid and dotted gray lines).

With weights = false the lines are not scaled:

plot_locs(eeg;
          ch = "eeg",
          ch_labels = false,
          connections = c,
          weights = false,
          gui = false)