Connectivity measures on simulated signals#

Goal: see what each spectral and connectivity measure shows on signals whose coupling is known. The sections cover power and spectrograms, coherence and coherograms, the phase-locking and phase-lag measures, group delay and the phase slope index, canonical and global coherence, and the labeled xarray interface.

You need: the getting-started tutorial, or the README’s quick example.

Every example builds its data with spectral_connectivity.simulate, so the structure in each plot is planted and known: simulate_shared_oscillation puts one sinusoid, with chosen amplitudes and phase offsets, into several signals, and simulate_lagged_broadband delays copies of one broadband source by a known number of samples. Each section ends with an assert cell that checks what its plot shows, so running the notebook verifies it. Every simulation passes random_state, so the output is reproducible.

import warnings

import matplotlib.pyplot as plt
import numpy as np

from spectral_connectivity import (
    Connectivity,
    Multitaper,
    SidednessWarning,
    multitaper_connectivity,
)
from spectral_connectivity.simulate import (
    simulate_lagged_broadband,
    simulate_shared_oscillation,
)

# Connectivity.power() is one-sided and Connectivity.global_coherence() covers
# the non-negative frequencies (as this tutorial expects); the reminders meant
# for code written for 2.x, which returned the two-sided density and every FFT
# bin, do not apply here.
warnings.filterwarnings("ignore", category=SidednessWarning)

Power Spectrum#

200 Hz signal#

# One 200 Hz sinusoid (one trial, one signal) in white noise of standard
# deviation 4. Both calls share `random_state`, so `signal` is exactly `data`
# without its noise.
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 50)
noise_level = 4
n_time_samples = ((time_extent[1] - time_extent[0]) * sampling_frequency) + 1
time = np.arange(n_time_samples) / sampling_frequency
simulation = dict(
    frequency=frequency_of_interest,
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=1,
    amplitudes=[1.0],
    random_phase_per_trial=False,
    random_state=0,
)
signal = simulate_shared_oscillation(**simulation)  # (n_time_samples, 1, 1)
data = simulate_shared_oscillation(**simulation, noise_levels=noise_level)

# Plot
fig, axes = plt.subplots(1, 2, figsize=(15, 6))

axes[0].plot(time[:100], signal[:100, 0, 0], label="Signal", zorder=3)
axes[0].plot(time[:100], data[:100, 0, 0], label="Signal + Noise")
axes[0].legend()
axes[0].set_title("Time Domain")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axes[1].plot(connectivity.frequencies, connectivity.power().squeeze())
axes[1].set_title("Frequency Domain")
Text(0.5, 1.0, 'Frequency Domain')
../_images/1996af7e9e86d5497eb42d2ba3fe4f291293ee4fbc06e1f237e38d86b2b52f93.png
# The spectrum peaks at 200 Hz (within the frequency resolution, the taper bandwidth) and,
# away from the peak, sits at the white-noise floor 2 * noise_level**2 / fs.
power = connectivity.power()[0, :, 0]
frequencies = connectivity.frequencies
peak_frequency = frequencies[np.argmax(power)]
assert abs(peak_frequency - frequency_of_interest) <= multitaper.frequency_resolution
off_peak = np.abs(frequencies - frequency_of_interest) > 5
np.testing.assert_allclose(
    power[off_peak].mean(), 2 * noise_level**2 / sampling_frequency, rtol=0.05
)

30 Hz signal#

# One 30 Hz sinusoid (one trial, one signal) in white noise of standard
# deviation 4. Both calls share `random_state`, so `signal` is exactly `data`
# without its noise.
frequency_of_interest = 30
sampling_frequency = 1500
time_extent = (0, 50)
noise_level = 4
n_time_samples = ((time_extent[1] - time_extent[0]) * sampling_frequency) + 1
time = np.arange(n_time_samples) / sampling_frequency
simulation = dict(
    frequency=frequency_of_interest,
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=1,
    amplitudes=[1.0],
    random_phase_per_trial=False,
    random_state=0,
)
signal = simulate_shared_oscillation(**simulation)  # (n_time_samples, 1, 1)
data = simulate_shared_oscillation(**simulation, noise_levels=noise_level)

# Plot
fig, axes = plt.subplots(1, 2, figsize=(15, 6))

axes[0].plot(time[:500], signal[:500, 0, 0], label="Signal", zorder=3)
axes[0].plot(time[:500], data[:500, 0, 0], label="Signal + Noise")
axes[0].legend()
axes[0].set_title("Time Domain")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axes[1].plot(connectivity.frequencies, connectivity.power().squeeze())
axes[1].set_title("Frequency Domain")
axes[1].set_xlim((0, 100))
(0.0, 100.0)
../_images/fba50518841ed44c6bdbe3097d736469561cd68e2b6037ae818043a63f3edd8a.png
# The spectrum peaks at 30 Hz (within the frequency resolution, the taper bandwidth) and,
# away from the peak, sits at the white-noise floor 2 * noise_level**2 / fs.
power = connectivity.power()[0, :, 0]
frequencies = connectivity.frequencies
peak_frequency = frequencies[np.argmax(power)]
assert abs(peak_frequency - frequency_of_interest) <= multitaper.frequency_resolution
off_peak = np.abs(frequencies - frequency_of_interest) > 5
np.testing.assert_allclose(
    power[off_peak].mean(), 2 * noise_level**2 / sampling_frequency, rtol=0.05
)

Spectrogram#

No trials, 200 Hz signal with 50 Hz signal starting at 25 seconds#

# Simulate signal: one trial, (n_time_samples, 1, 1)
sampling_frequency = 1500
time_extent = (0, 50)
n_trials = 1
noise_level = 4
onset = 25  # the 50 Hz oscillation starts here
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
# 200 Hz throughout plus 50 Hz from `onset` on; the noise rides on the 200 Hz
# call, and the shared `random_state` makes `signal` exactly `data` without it.
simulation = dict(
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    amplitudes=[1.0],
    random_phase_per_trial=False,
    random_state=0,
)
after_onset = (time >= onset)[:, np.newaxis, np.newaxis]
fifty_hz = after_onset * simulate_shared_oscillation(50, **simulation)
signal = simulate_shared_oscillation(200, **simulation) + fifty_hz
data = simulate_shared_oscillation(200, **simulation, noise_levels=noise_level) + fifty_hz

# Plot
fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9))
axes[0, 0].plot(time, signal[:, 0, 0])
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].set_xlim((24.90, 25.10))
axes[0, 0].set_ylim((-10, 10))

axes[0, 1].plot(time, data[:, 0, 0])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].set_xlim((24.90, 25.10))
axes[0, 1].set_ylim((-10, 10))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(connectivity.frequencies, connectivity.power().squeeze())
axes[1, 0].set_xlabel("Frequency")
axes[1, 0].set_ylabel("Power")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(connectivity.frequencies, connectivity.power().squeeze())
axes[1, 1].set_xlabel("Frequency")
axes[1, 1].set_ylabel("Power")


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    time_window_duration=0.600,
    time_window_step=0.300,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 0].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].axvline(onset, color="black")
axes[2, 0].set_ylabel("Frequency")
axes[2, 0].set_xlabel("Time")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    time_window_duration=0.600,
    time_window_step=0.300,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 1].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].axvline(onset, color="black")
axes[2, 1].set_ylabel("Frequency")
axes[2, 1].set_xlabel("Time")

plt.tight_layout()
cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Power",
)
cb.outline.set_linewidth(0)
../_images/9cb73ee3c661b43f52b4300845d5a54d87cd93ec36edacb9c07378212e75f6ad.png
# Windows wholly before the onset have only noise at 50 Hz (the white-noise
# floor 2 * noise_level**2 / fs); windows wholly after it have 50 Hz power well
# above that floor. 200 Hz is present throughout and is the strongest peak.
power = connectivity.power()[..., 0]  # (n_windows, n_frequencies)
frequencies = connectivity.frequencies
half_window = multitaper.time_window_duration / 2
before = connectivity.time + half_window < onset
after = connectivity.time - half_window > onset
at_50_hz = power[:, np.argmin(np.abs(frequencies - 50))]
at_200_hz = power[:, np.argmin(np.abs(frequencies - 200))]
noise_floor = 2 * noise_level**2 / sampling_frequency
peak_frequency = frequencies[np.argmax(power.mean(axis=0))]
assert abs(peak_frequency - 200) <= multitaper.frequency_resolution
np.testing.assert_allclose(at_50_hz[before].mean(), noise_floor, rtol=0.25)
assert at_50_hz[after].mean() > 3 * noise_floor
assert at_200_hz[before].mean() > 3 * noise_floor
assert at_200_hz[after].mean() > 3 * noise_floor

With trial structure (time x trials)#

time_halfbandwidth_product = 1

sampling_frequency = 1500
time_extent = (0, 0.600)
n_trials = 100
noise_level = 2
onset = 0.300  # the 50 Hz oscillation starts here
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
# 200 Hz throughout plus 50 Hz from `onset` on; the noise rides on the 200 Hz
# call, and the shared `random_state` makes `signal` exactly `data` without it.
simulation = dict(
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    amplitudes=[1.0],
    random_phase_per_trial=False,
    random_state=0,
)
after_onset = (time >= onset)[:, np.newaxis, np.newaxis]
fifty_hz = after_onset * simulate_shared_oscillation(50, **simulation)
signal = simulate_shared_oscillation(200, **simulation) + fifty_hz
data = simulate_shared_oscillation(200, **simulation, noise_levels=noise_level) + fifty_hz

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9))
axes[0, 0].plot(time, signal[:, 0, 0])
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].set_ylim((-10, 10))

axes[0, 1].plot(time, data[:, 0, 0])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-10, 10))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(connectivity.frequencies, connectivity.power().squeeze())

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=3,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(connectivity.frequencies, connectivity.power().squeeze())


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.060,
    time_window_step=0.060,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 0].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].axvline(onset, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.060,
    time_window_step=0.060,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 1].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].axvline(onset, color="black")

plt.tight_layout()
cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Power",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 33.333333333333336
../_images/631d138188c9d38f270f1056cda2c41d4de292765d9244d8a8d107681b58dedb.png
# Windows wholly before the onset have only noise at 50 Hz (the white-noise
# floor 2 * noise_level**2 / fs); windows wholly after it have 50 Hz power well
# above that floor. 200 Hz is present throughout and is the strongest peak.
power = connectivity.power()[..., 0]  # (n_windows, n_frequencies)
frequencies = connectivity.frequencies
half_window = multitaper.time_window_duration / 2
before = connectivity.time + half_window < onset
after = connectivity.time - half_window > onset
at_50_hz = power[:, np.argmin(np.abs(frequencies - 50))]
at_200_hz = power[:, np.argmin(np.abs(frequencies - 200))]
noise_floor = 2 * noise_level**2 / sampling_frequency
peak_frequency = frequencies[np.argmax(power.mean(axis=0))]
assert abs(peak_frequency - 200) <= multitaper.frequency_resolution
np.testing.assert_allclose(at_50_hz[before].mean(), noise_floor, rtol=0.25)
assert at_50_hz[after].mean() > 3 * noise_floor
assert at_200_hz[before].mean() > 3 * noise_floor
assert at_200_hz[after].mean() > 3 * noise_floor

Coarser frequency resolution with a larger time_halfbandwidth_product#

time_halfbandwidth_product = 3

sampling_frequency = 1500
time_extent = (0, 0.600)
n_trials = 100
noise_level = 2
onset = 0.300  # the 50 Hz oscillation starts here
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
# 200 Hz throughout plus 50 Hz from `onset` on; the noise rides on the 200 Hz
# call, and the shared `random_state` makes `signal` exactly `data` without it.
simulation = dict(
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    amplitudes=[1.0],
    random_phase_per_trial=False,
    random_state=0,
)
after_onset = (time >= onset)[:, np.newaxis, np.newaxis]
fifty_hz = after_onset * simulate_shared_oscillation(50, **simulation)
signal = simulate_shared_oscillation(200, **simulation) + fifty_hz
data = simulate_shared_oscillation(200, **simulation, noise_levels=noise_level) + fifty_hz

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9))
axes[0, 0].plot(time, signal[:, 0, 0])
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].set_ylim((-10, 10))

axes[0, 1].plot(time, data[:, 0, 0])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-10, 10))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(connectivity.frequencies, connectivity.power().squeeze())

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(connectivity.frequencies, connectivity.power().squeeze())


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.060,
    time_window_step=0.060,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 0].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].axvline(onset, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.060,
    time_window_step=0.060,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
mesh = axes[2, 1].pcolormesh(
    connectivity.time,
    connectivity.frequencies,
    connectivity.power().squeeze().T,
    vmin=0.0,
    vmax=0.03,
    cmap="viridis",
    shading="auto",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].axvline(onset, color="black")

plt.tight_layout()
cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Power",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 100.0
../_images/6cbb7b5cc02ecd3785f56b32f36c694ac3e793231c30d1e648cba64306bc4195.png
# Windows wholly before the onset have only noise at 50 Hz (the white-noise
# floor 2 * noise_level**2 / fs); windows wholly after it have 50 Hz power well
# above that floor. 200 Hz is present throughout and is the strongest peak.
# With time_halfbandwidth_product = 3 the 60 ms windows have 2W = 100 Hz,
# which spreads each sinusoid's power over a wider band and lowers its peak.
power = connectivity.power()[..., 0]  # (n_windows, n_frequencies)
frequencies = connectivity.frequencies
half_window = multitaper.time_window_duration / 2
before = connectivity.time + half_window < onset
after = connectivity.time - half_window > onset
at_50_hz = power[:, np.argmin(np.abs(frequencies - 50))]
at_200_hz = power[:, np.argmin(np.abs(frequencies - 200))]
noise_floor = 2 * noise_level**2 / sampling_frequency
peak_frequency = frequencies[np.argmax(power.mean(axis=0))]
assert abs(peak_frequency - 200) <= multitaper.frequency_resolution
np.testing.assert_allclose(at_50_hz[before].mean(), noise_floor, rtol=0.25)
assert at_50_hz[after].mean() > 1.5 * noise_floor
assert at_200_hz[before].mean() > 1.5 * noise_floor
assert at_200_hz[after].mean() > 1.5 * noise_floor

# The wider band is visible as broadening: 40 Hz from the 200 Hz peak, outside
# the single-taper band (2W = 33 Hz) but inside this one (2W = 100 Hz), the
# power is well above the noise floor here and at the floor with one taper.
single_taper = Connectivity.from_transform(
    Multitaper(
        data,
        sampling_frequency=sampling_frequency,
        time_halfbandwidth_product=1,
        time_window_duration=0.060,
        time_window_step=0.060,
        start_time=time[0],
    )
)
at_240_hz = np.argmin(np.abs(frequencies - 240))
assert power[:, at_240_hz].mean() > 1.5 * noise_floor
np.testing.assert_allclose(
    single_taper.power()[:, at_240_hz, 0].mean(), noise_floor, rtol=0.25
)

Coherence#

No trials, 200 Hz, \(\pi / 2\) phase offset#

time_halfbandwidth_product = 5
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 50)
noise_level = 4
n_time_samples = ((time_extent[1] - time_extent[0]) * sampling_frequency) + 1
time = np.arange(n_time_samples) / sampling_frequency
# Two signals share one 200 Hz sinusoid; signal 2 leads signal 1 by pi / 2.
# Shape (n_time_samples, 1, 2): a single trial.
simulation = dict(
    frequency=frequency_of_interest,
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=1,
    amplitudes=[1.0, 1.0],
    phase_offsets=[0.0, np.pi / 2],
    random_phase_per_trial=False,
    random_state=0,
)
signal = simulate_shared_oscillation(**simulation)
data = simulate_shared_oscillation(**simulation, noise_levels=noise_level)

plt.figure(figsize=(15, 6))
plt.subplot(2, 2, 1)
plt.title("Signal", fontweight="bold")
plt.plot(time, signal[:, 0, 0], label="Signal1")
plt.plot(time, signal[:, 0, 1], label="Signal2")
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.xlim((0.95, 1.05))
plt.ylim((-10, 10))
plt.legend()

plt.subplot(2, 2, 2)
plt.title("Signal + Noise", fontweight="bold")
plt.plot(time, data[:, 0, :])
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.xlim((0.95, 1.05))
plt.ylim((-10, 10))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
plt.subplot(2, 2, 3)
plt.plot(connectivity.frequencies, connectivity.magnitude_squared_coherence()[0, :, 0, 1])


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
plt.subplot(2, 2, 4)
plt.plot(connectivity.frequencies, connectivity.magnitude_squared_coherence()[0, :, 0, 1]);
../_images/2a64e5d9cee2b32e11e703605ce0007b8a45ecd0ee727dd3db8661dc40e2beaa.png
# Coherence is near 1 at 200 Hz and at the noise level away from it. The
# cross-spectrum [0, 1] is E[X_0 conj(X_1)], so its phase is phase_0 - phase_1:
# signal 2 leads signal 1 by pi / 2, giving -pi / 2.
coherence = connectivity.magnitude_squared_coherence()[0, :, 0, 1]
frequencies = connectivity.frequencies
peak = np.argmin(np.abs(frequencies - frequency_of_interest))
off_peak = np.abs(frequencies - frequency_of_interest) > multitaper.frequency_resolution
assert coherence[peak] > 0.95
# With one trial, each frequency averages only the tapers' estimates; for
# independent signals the expected coherence is 1 / n_tapers.
assert np.median(coherence[off_peak]) < 2 / multitaper.n_tapers
np.testing.assert_allclose(
    connectivity.coherence_phase()[0, peak, 0, 1], -np.pi / 2, atol=0.1
)

With trial structure (time x trials), 200 Hz, \(\pi / 2\) phase offset#

In 0.6 s trials this much noise keeps the coherence well below 1, yet the coherence phase still recovers the \(\pi / 2\) offset: coherence measures how consistent the phase relation is across trials and tapers, not what that relation is.

time_halfbandwidth_product = 5
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 0.600)
n_trials = 100
noise_level = 2
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
# Each trial starts the shared sinusoid at a random phase, but signal 2 always
# leads signal 1 by pi / 2. Shape (n_time_samples, n_trials, 2).
simulation = dict(
    frequency=frequency_of_interest,
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    amplitudes=[1.0, 1.0],
    phase_offsets=[0.0, np.pi / 2],
    random_state=0,
)
signal = simulate_shared_oscillation(**simulation)
data = simulate_shared_oscillation(**simulation, noise_levels=noise_level)

plt.figure(figsize=(15, 6))
plt.subplot(2, 2, 1)
plt.title("Signal", fontweight="bold")
plt.plot(time, signal[:, 0, 0], label="Signal1")
plt.plot(time, signal[:, 0, 1], label="Signal2")
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.xlim(time_extent)
plt.ylim((-2, 2))
plt.legend()

plt.subplot(2, 2, 2)
plt.title("Signal + Noise", fontweight="bold")
plt.plot(time, data[:, 0, :])
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.xlim(time_extent)
plt.ylim((-8, 8))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
plt.subplot(2, 2, 3)
plt.plot(connectivity.frequencies, connectivity.magnitude_squared_coherence()[0, :, 0, 1])


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
plt.subplot(2, 2, 4)
plt.plot(connectivity.frequencies, connectivity.magnitude_squared_coherence()[0, :, 0, 1]);
../_images/2a8fea4ea9e0993f99c041d6724e2ec57a1fa8e3dd341bcd26e18f9cbf86a969.png
# Coherence at 200 Hz is well below 1 but far above the off-peak chance level,
# and its phase is still the planted offset. The cross-spectrum [0, 1] is
# E[X_0 conj(X_1)], so its phase is phase_0 - phase_1: signal 2 leads signal 1
# by pi / 2, giving -pi / 2.
coherence = connectivity.magnitude_squared_coherence()[0, :, 0, 1]
frequencies = connectivity.frequencies
peak = np.argmin(np.abs(frequencies - frequency_of_interest))
off_peak = np.abs(frequencies - frequency_of_interest) > multitaper.frequency_resolution
assert coherence[peak] > 0.5
assert coherence[peak] > 5 * np.median(coherence[off_peak])
np.testing.assert_allclose(
    connectivity.coherence_phase()[0, peak, 0, 1], -np.pi / 2, atol=0.1
)

Coherograms#

This and the following sections use the same pair of 200 Hz signals. Before 1.5 s, signal 2’s phase is drawn independently of signal 1’s on every trial, so the pair has no consistent phase relation across trials; from 1.5 s on, both share each trial’s phase and signal 2 leads by \(\pi / 2\). Within a single trial the two sinusoids keep a fixed phase difference even before the onset, so averaging over time instead of over trials (expectation_type="time") would still see locking there; the default average over trials and tapers is what makes the onset visible. simulate_coupling_onset splices two simulate_shared_oscillation calls to build the pair, and split_at_onset picks out a measure at 200 Hz in the windows wholly before and wholly after the onset for the assert cells.

The phase-locking value, phase lag index, debiased squared phase lag index and pairwise phase consistency sections use a single taper (time_halfbandwidth_product = 1). These measures normalize every trial-and-taper estimate to unit magnitude, so each taper counts equally. The odd-order Slepian tapers have zero gain at the center of their band: for a narrowband rhythm they carry almost none of it at exactly its frequency, their phases there are noise, and with several tapers the measure dips exactly at the oscillation frequency (with time_halfbandwidth_product = 2 here, the phase-locking value is about 0.65 at 200 Hz but 0.93 one bin to either side). Coherence, imaginary coherence, the weighted phase lag index and its debiased version weight each estimate by its magnitude, so the near-empty tapers barely count; those sections keep time_halfbandwidth_product = 2. The habit: for phase-normalized measures of a narrowband rhythm, use one taper, or use the weighted phase lag index. For broadband signals or real data, multiple tapers remain the right default.

def simulate_coupling_onset(
    sampling_frequency,
    n_time_samples,
    n_trials,
    noise_level,
    frequency=200,
    onset=1.5,
    random_state=0,
):
    """Two signals at ``frequency`` that phase-lock (signal 2 leading by pi / 2) at ``onset``.

    Returns shape (n_time_samples, n_trials, 2). The same ``random_state`` with
    ``noise_level=0`` gives the noise-free version.
    """
    rng = np.random.default_rng(random_state)
    simulation = dict(
        frequency=frequency,
        sampling_frequency=sampling_frequency,
        n_time_samples=n_time_samples,
        n_trials=n_trials,
        amplitudes=[1.0, 1.0],
        noise_levels=noise_level,
        random_state=rng,
    )
    coupled = simulate_shared_oscillation(**simulation, phase_offsets=[0.0, np.pi / 2])
    # Its own trial phases: no consistent phase relation to `coupled` across trials.
    unlocked = simulate_shared_oscillation(**simulation)
    time = np.arange(n_time_samples) / sampling_frequency
    before_onset = (time < onset)[:, np.newaxis, np.newaxis] & (np.arange(2) == 1)
    return np.where(before_onset, unlocked, coupled)


def split_at_onset(values, connectivity, multitaper, frequency=200, onset=1.5):
    """Split a (n_windows, n_frequencies) measure around the coupling onset.

    Returns the values at ``frequency`` in windows wholly before and wholly after
    ``onset``, and the values away from ``frequency`` in the windows after it.
    """
    frequencies = connectivity.frequencies
    peak = np.argmin(np.abs(frequencies - frequency))
    off_peak = np.abs(frequencies - frequency) > multitaper.frequency_resolution
    half_window = multitaper.time_window_duration / 2
    before = connectivity.time + half_window < onset
    after = connectivity.time - half_window > onset
    return values[before, peak], values[after, peak], values[after][:, off_peak]
time_halfbandwidth_product = 2
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Coherence",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 50.0
../_images/05c53011354a7175035a196b17ba586cbacad9545f0d2ff3ac7feeb9c94b6edc.png
# After the onset, the pair is coherent at 200 Hz; before it, and away from
# 200 Hz, coherence stays near the chance level.
before, after, off_peak_after = split_at_onset(
    connectivity.magnitude_squared_coherence()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.7)  # about 0.8 at this signal-to-noise ratio
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.01 (squared measure).
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Imaginary Coherence#

time_halfbandwidth_product = 2
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies, connectivity.imaginary_coherence()[..., 0, 1].squeeze()
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies, connectivity.imaginary_coherence()[..., 0, 1].squeeze()
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.imaginary_coherence()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.imaginary_coherence()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Imaginary Coherence",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 50.0
../_images/ccaecd3887336bba366a3228d17caaeb15faf272ee5c7227743d93a5e58ead16.png
# A pi / 2 lead is purely imaginary, so after the onset the imaginary
# coherence at 200 Hz is near 1; before it, and away from 200 Hz, it is near 0.
before, after, off_peak_after = split_at_onset(
    connectivity.imaginary_coherence()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.8)
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.1.
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Phase Locking Value#

time_halfbandwidth_product = 1
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies, connectivity.phase_locking_value()[..., 0, 1].squeeze()
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies, connectivity.phase_locking_value()[..., 0, 1].squeeze()
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.phase_locking_value()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.phase_locking_value()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Phase Locking Value",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 25.0
../_images/419de3b5fe38ccff3de12afb5fe790fd3260b970c250709d3f56f93c326da0e2.png
# After the onset the phase difference is the same on every trial, so the
# phase locking value at 200 Hz is near 1; before it, and away from 200 Hz,
# it stays near the chance level.
before, after, off_peak_after = split_at_onset(
    connectivity.phase_locking_value()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.9)
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.1.
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Phase Lag Index#

time_halfbandwidth_product = 1
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies, connectivity.phase_lag_index()[..., 0, 1].squeeze()
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies, connectivity.phase_lag_index()[..., 0, 1].squeeze()
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=-1.0,
    vmax=1.0,
    cmap="RdBu_r",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=-1.0,
    vmax=1.0,
    cmap="RdBu_r",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Phase Lag Index",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 25.0
../_images/60a2c5c62029bfdd1da5b4345b744ef7a5a695db44168bc71ea11ef3df5ccd9a.png
# Signal 2 leads, so Im(E[X_0 conj(X_1)]) < 0 and the signed phase lag index
# [0, 1] is -1 after the onset ([1, 0] is +1); before it, and away from
# 200 Hz, it is near 0.
values = connectivity.phase_lag_index()
before, after, off_peak_after = split_at_onset(values[..., 0, 1], connectivity, multitaper)
assert np.all(after < -0.9)
# Antisymmetry holds by construction; this line documents the sign convention.
np.testing.assert_allclose(values[..., 1, 0], -values[..., 0, 1])
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.1.
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Weighted Phase Lag Index#

time_halfbandwidth_product = 2
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies,
    connectivity.weighted_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies,
    connectivity.weighted_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.weighted_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=-1.0,
    vmax=1.0,
    cmap="RdBu_r",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.weighted_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=-1.0,
    vmax=1.0,
    cmap="RdBu_r",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Weighted Phase Lag Index",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 50.0
../_images/be8188c49c80f1d5a9491245338140ede037a02ef549730c1c220709d474abeb.png
# Same sign convention as the phase lag index: [0, 1] is -1 after the onset
# because signal 2 leads; before it, and away from 200 Hz, it is near 0.
values = connectivity.weighted_phase_lag_index()
before, after, off_peak_after = split_at_onset(values[..., 0, 1], connectivity, multitaper)
assert np.all(after < -0.9)
# Antisymmetry holds by construction; this line documents the sign convention.
np.testing.assert_allclose(values[..., 1, 0], -values[..., 0, 1])
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.1.
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Debiased Squared Phase Lag Index#

time_halfbandwidth_product = 1
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies,
    connectivity.debiased_squared_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies,
    connectivity.debiased_squared_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.debiased_squared_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.debiased_squared_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Debiased Squared Phase Lag Index",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 25.0
../_images/c77b832950549beaf0291dea9daf4448fdf52352fa5403c0e06207bcca9a63f6.png
# The debiased squared phase lag index is unsigned: near 1 at 200 Hz after
# the onset, near 0 before it and away from 200 Hz.
before, after, off_peak_after = split_at_onset(
    connectivity.debiased_squared_phase_lag_index()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.9)
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.01 (squared measure).
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Debiased Squared Weighted Phase Lag Index#

time_halfbandwidth_product = 2
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies,
    connectivity.debiased_squared_weighted_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies,
    connectivity.debiased_squared_weighted_phase_lag_index()[..., 0, 1].squeeze(),
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.debiased_squared_weighted_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.debiased_squared_weighted_phase_lag_index()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Debiased Weighted Squared Phase Lag Index",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 50.0
../_images/fc430b82e1619dbb18fa5b67e05ffe93dbefe4b0427c1b7545f1adead38a15d8.png
# Near 1 at 200 Hz after the onset, near 0 before it and away from 200 Hz.
before, after, off_peak_after = split_at_onset(
    connectivity.debiased_squared_weighted_phase_lag_index()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.9)
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.01 (squared measure).
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Pairwise Phase Consistency#

time_halfbandwidth_product = 1
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
noise_level = 1
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
signal = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, 0)
data = simulate_coupling_onset(sampling_frequency, n_time_samples, n_trials, noise_level)

fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15, 9), constrained_layout=True)
axes[0, 0].set_title("Signal", fontweight="bold")
axes[0, 0].plot(time, signal[:, 0, 0], label="Signal1")
axes[0, 0].plot(time, signal[:, 0, 1], label="Signal2")
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
axes[0, 0].set_xlim(time_extent)
axes[0, 0].set_ylim((-2, 2))

axes[0, 1].set_title("Signal + Noise", fontweight="bold")
axes[0, 1].plot(time, data[:, 0, :])
axes[0, 1].set_xlabel("Time")
axes[0, 1].set_ylabel("Amplitude")
axes[0, 1].set_xlim(time_extent)
axes[0, 1].set_ylim((-5, 5))

multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 0].plot(
    connectivity.frequencies,
    connectivity.pairwise_phase_consistency()[..., 0, 1].squeeze(),
)
axes[1, 0].set_xlim((0, multitaper.nyquist_frequency))

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
axes[1, 1].plot(
    connectivity.frequencies,
    connectivity.pairwise_phase_consistency()[..., 0, 1].squeeze(),
)
axes[1, 1].set_xlim((0, multitaper.nyquist_frequency))


multitaper = Multitaper(
    signal,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)
time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 0].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.pairwise_phase_consistency()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 0].set_ylim((0, 300))
axes[2, 0].set_xlim(time_extent)
axes[2, 0].axvline(1.5, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

mesh = axes[2, 1].pcolormesh(
    time_grid,
    freq_grid,
    connectivity.pairwise_phase_consistency()[..., 0, 1].squeeze().T,
    vmin=0.0,
    vmax=1.0,
    cmap="viridis",
)
axes[2, 1].set_ylim((0, 300))
axes[2, 1].set_xlim(time_extent)
axes[2, 1].axvline(1.5, color="black")

cb = fig.colorbar(
    mesh,
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Pairwise Phase Consistency",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")
frequency resolution: 25.0
../_images/e0bff213eb4e166fdbe69ac491e72cde89aa799385621cc48038b800183a714b.png
# Pairwise phase consistency is near 1 at 200 Hz after the onset, near 0
# before it and away from 200 Hz.
before, after, off_peak_after = split_at_onset(
    connectivity.pairwise_phase_consistency()[..., 0, 1], connectivity, multitaper
)
assert np.all(after > 0.9)
# Before the onset each trial has its own phase relation, so the chance level
# is set by the 100 trials: ~0.01 (squared measure).
assert np.all(np.abs(before) < 0.3)
assert np.abs(np.median(off_peak_after)) < 0.1

Group Delay#

Group delay is the slope of the coherence phase across frequency, so it needs signals that are coherent across a band: a sinusoid delayed by a whole number of cycles is indistinguishable from the original. Each example here delays copies of one white-noise source by 10 ms with simulate_lagged_broadband, whose lags_samples are whole samples: round(time_lag * sampling_frequency) converts the 10 ms to 10 samples at 1000 Hz. A positive delay[..., i, j] means signal i leads signal j.

Signal #1 leads Signal #2#

sampling_frequency = 1000
time_extent = (0, 1)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 1 leads signal 2 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (0, lag_samples)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(5, 2, figsize=(12, 9), constrained_layout=True)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_xlim((0, 0.1))
axis_handles[0, 0].set_xlabel("Time")

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_xlim((0, 0.1))
axis_handles[0, 1].set_xlabel("Time")

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 0].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 0].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

delay, slope, r_value = connectivity.group_delay()
axis_handles[4, 0].bar(
    [1, 2], [delay[..., 0, 1].squeeze(), delay[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 0].set_xlim((0.5, 2.5))
axis_handles[4, 0].axhline(0, color="black")
axis_handles[4, 0].set_xticks([1])
axis_handles[4, 0].set_xticklabels(["x1 → x2"])


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 1].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 1].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

delay, slope, r_value = connectivity.group_delay()
axis_handles[4, 1].bar(
    [1, 2], [delay[..., 0, 1].squeeze(), delay[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 1].set_xlim((0.5, 2.5))
axis_handles[4, 1].axhline(0, color="black")
axis_handles[4, 1].set_xticks([1])
axis_handles[4, 1].set_xticklabels(["x1 → x2"])
[Text(1, 0, 'x1 → x2')]
../_images/305eb98074472513fe0e2bf3c93be8424a5d3c180b6d242976715e3b73660e69.png
# Signal 1 leads by 10 ms: delay [0, 1] is +10 ms and [1, 0] is -10 ms (to 1 ms).
np.testing.assert_allclose(delay[..., 0, 1], time_lag, atol=1e-3)
np.testing.assert_allclose(delay[..., 1, 0], -time_lag, atol=1e-3)

Signal #2 leads Signal #1#

sampling_frequency = 1000
time_extent = (0, 1)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 2 leads signal 1 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (lag_samples, 0)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(5, 2, figsize=(12, 9), constrained_layout=True)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_xlim((0, 0.1))
axis_handles[0, 0].set_xlabel("Time")

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_xlim((0, 0.1))
axis_handles[0, 1].set_xlabel("Time")

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 0].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 0].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

delay, slope, r_value = connectivity.group_delay()
axis_handles[4, 0].bar(
    [1, 2], [delay[..., 0, 1].squeeze(), delay[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 0].set_xlim((0.5, 2.5))
axis_handles[4, 0].axhline(0, color="black")
axis_handles[4, 0].set_xticks([1])
axis_handles[4, 0].set_xticklabels(["x1 → x2"])


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 1].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 1].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

delay, slope, r_value = connectivity.group_delay()
axis_handles[4, 1].bar(
    [1, 2], [delay[..., 0, 1].squeeze(), delay[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 1].set_xlim((0.5, 2.5))
axis_handles[4, 1].axhline(0, color="black")
axis_handles[4, 1].set_xticks([1])
axis_handles[4, 1].set_xticklabels(["x1 → x2"])
[Text(1, 0, 'x1 → x2')]
../_images/5c4a8044883cf1c0cbdff0e825ae2bffbdfd443d8be5ce517ea6fb02ebdaf27a.png
# Signal 2 leads by 10 ms: delay [0, 1] is -10 ms and [1, 0] is +10 ms (to 1 ms).
np.testing.assert_allclose(delay[..., 0, 1], -time_lag, atol=1e-3)
np.testing.assert_allclose(delay[..., 1, 0], time_lag, atol=1e-3)

Signal #2 leads Signal #1 over time#

sampling_frequency = 1000
time_extent = (0, 2)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 2 leads signal 1 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (lag_samples, 0)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(2, 2, figsize=(12, 9), constrained_layout=True)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_xlabel("Time")
axis_handles[0, 0].set_xlim(time_extent)

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_xlabel("Time")
axis_handles[0, 1].set_xlim(time_extent)

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.500,
    time_window_step=0.100,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

delay, slope, r_value = connectivity.group_delay()
axis_handles[1, 0].plot(
    connectivity.time, delay[..., 0, 1]
)
axis_handles[1, 0].set_xlim(time_extent)

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.500,
    time_window_step=0.100,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

delay, slope, r_value = connectivity.group_delay()
axis_handles[1, 1].plot(
    connectivity.time, delay[..., 0, 1]
)
axis_handles[1, 1].set_xlim(time_extent)
(0.0, 2.0)
../_images/40db852f790ca3132678af11934599845fa623a7d161973d653e0630dab4512f.png
# In every window, signal 2 leads by 10 ms: delay [0, 1] is -10 ms (to 1 ms).
np.testing.assert_allclose(delay[..., 0, 1], -time_lag, atol=1e-3)

Phase Slope Index#

Signal #1 leads Signal #2#

sampling_frequency = 1000
time_extent = (0, 1)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 1 leads signal 2 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (0, lag_samples)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(5, 2, figsize=(12, 9), constrained_layout=True)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_xlim((0, 0.1))
axis_handles[0, 0].set_xlabel("Time")

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_xlim((0, 0.1))
axis_handles[0, 1].set_xlabel("Time")

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 0].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 0].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

psi = connectivity.phase_slope_index()
axis_handles[4, 0].bar(
    [1, 2], [psi[..., 0, 1].squeeze(), psi[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 0].set_xlim((0.5, 2.5))
axis_handles[4, 0].axhline(0, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 1].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 1].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

psi = connectivity.phase_slope_index()
axis_handles[4, 1].bar(
    [1, 2], [psi[..., 0, 1].squeeze(), psi[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 1].set_xlim((0.5, 2.5))
axis_handles[4, 1].axhline(0, color="black");
../_images/f6ad6c56bb27f26a12485b1f27cbc841a78cbbe2df57a6d48bec3ac52cd231c5.png
# Signal 1 leads: the phase slope index [0, 1] is positive and [1, 0] is its negative.
assert np.all(psi[..., 0, 1] > 0)
# Antisymmetry holds by construction; this line documents the sign convention.
np.testing.assert_allclose(psi[..., 1, 0], -psi[..., 0, 1])

Signal #2 leads Signal #1#

sampling_frequency = 1000
time_extent = (0, 1)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 2 leads signal 1 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (lag_samples, 0)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(5, 2, figsize=(12, 9), constrained_layout=True)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_xlim((0, 0.1))
axis_handles[0, 0].set_xlabel("Time")

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_xlim((0, 0.1))
axis_handles[0, 1].set_xlabel("Time")

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 0].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 0].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 0].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

psi = connectivity.phase_slope_index()
axis_handles[4, 0].bar(
    [1, 2], [psi[..., 0, 1].squeeze(), psi[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 0].set_xlim((0.5, 2.5))
axis_handles[4, 0].axhline(0, color="black")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 0].squeeze()
)
axis_handles[1, 1].plot(
    connectivity.frequencies, connectivity.power()[..., 1].squeeze()
)
axis_handles[2, 1].plot(
    connectivity.frequencies, connectivity.magnitude_squared_coherence()[..., 0, 1].squeeze()
)
axis_handles[3, 1].plot(
    connectivity.frequencies,
    connectivity.coherence_phase()[..., 0, 1].squeeze(),
    linestyle="None",
    marker="8",
)

psi = connectivity.phase_slope_index()
axis_handles[4, 1].bar(
    [1, 2], [psi[..., 0, 1].squeeze(), psi[..., 1, 0].squeeze()], color=["b", "g"]
)
axis_handles[4, 1].set_xlim((0.5, 2.5))
axis_handles[4, 1].axhline(0, color="black");
../_images/1eb95a740322dfc22926465b0d367fb82cfb5eedf61c2afeae6186884162f7a8.png
# Signal 2 leads: the phase slope index [0, 1] is negative and [1, 0] is its negative.
assert np.all(psi[..., 0, 1] < 0)
# Antisymmetry holds by construction; this line documents the sign convention.
np.testing.assert_allclose(psi[..., 1, 0], -psi[..., 0, 1])

Signal #2 leads Signal #1 over time#

sampling_frequency = 1000
time_extent = (0, 2)
n_trials = 100
time_halfbandwidth_product = 1
time_lag = 0.010  # signal 2 leads signal 1 by 10 ms
lag_samples = round(time_lag * sampling_frequency)  # seconds to whole samples
lags_samples = (lag_samples, 0)  # samples behind the shared source; the smaller lag leads
noise_levels = [1.0, 0.5]

n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

# Both calls draw the same source (it is drawn before the noise), so `signals`
# is exactly `data` without its noise. Shape (n_time_samples, n_trials, 2).
signals = simulate_lagged_broadband(lags_samples, 0.0, n_time_samples, n_trials, random_state=0)
data = simulate_lagged_broadband(lags_samples, noise_levels, n_time_samples, n_trials, random_state=0)

fig, axis_handles = plt.subplots(
    2, 2, figsize=(12, 9), constrained_layout=True, sharex=True
)
axis_handles[0, 0].plot(time, signals[:, 0, 0], color="blue")
axis_handles[0, 0].plot(time, signals[:, 0, 1], color="green")
axis_handles[0, 0].set_title("Signals")
axis_handles[0, 0].set_xlim(time_extent)

axis_handles[0, 1].plot(time, data[:, 0, 0], color="blue")
axis_handles[0, 1].plot(time, data[:, 0, 1], color="green")
axis_handles[0, 1].set_title("Signals")
axis_handles[0, 1].set_xlim(time_extent)

multitaper = Multitaper(
    signals,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.500,
    time_window_step=0.100,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

psi = connectivity.phase_slope_index()
axis_handles[1, 0].plot(
    connectivity.time,
    psi[..., 0, 1],
    connectivity.time,
    psi[..., 1, 0],
)
axis_handles[1, 0].set_xlim(time_extent)
axis_handles[1, 0].set_xlabel("Time [s]")
axis_handles[1, 0].set_ylabel("Phase Slope Index")

multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.500,
    time_window_step=0.100,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

psi = connectivity.phase_slope_index()
axis_handles[1, 1].plot(
    connectivity.time,
    psi[..., 0, 1],
    connectivity.time,
    psi[..., 1, 0],
)
axis_handles[1, 1].set_xlim(time_extent)
axis_handles[1, 1].set_xlabel("Time [s]")
axis_handles[1, 1].set_ylabel("Phase Slope Index")
Text(0, 0.5, 'Phase Slope Index')
../_images/010abf85d20412c6b321134156525d4d61199d1d410896bc29cb8ebf8a0192a5.png
# In every window signal 2 leads: the phase slope index [0, 1] is negative.
assert np.all(psi[..., 0, 1] < 0)
# Antisymmetry holds by construction; this line documents the sign convention.
np.testing.assert_allclose(psi[..., 1, 0], -psi[..., 0, 1])

Canonical Coherence#

The advantage of canonical coherence is that it can be more statistically powerful than coherence because it is combining coherence from groups.

Every signal carries a shared 20 Hz rhythm, and each group also carries its own 40 Hz rhythm, with trial phases independent of the other group’s. The groups are therefore coherent with each other at 20 Hz; at 40 Hz each group is coherent within itself, but the two groups have no consistent phase relation, so canonical coherence between them is high at 20 Hz and at chance at 40 Hz. Each group’s 40 Hz rhythm is its own simulate_shared_oscillation call, with zero amplitude in the other group, drawn from the same generator.

from itertools import product

time_halfbandwidth_product = 2
sampling_frequency = 500
time_extent = (0, 2.400)
n_trials = 100
n_signals = 4
noise_level = 0.5
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
group_labels = ["a"] * 2 + ["b"] * 2
in_group_a = np.array(group_labels) == "a"
in_group_b = np.array(group_labels) == "b"

rng = np.random.default_rng(0)
simulation = dict(
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    random_state=rng,
)
shared = simulate_shared_oscillation(
    20, **simulation, amplitudes=[1.0] * n_signals, noise_levels=noise_level
)
private_a = simulate_shared_oscillation(40, **simulation, amplitudes=in_group_a * 1.0)
private_b = simulate_shared_oscillation(40, **simulation, amplitudes=in_group_b * 1.0)
data = shared + private_a + private_b  # (n_time_samples, n_trials, n_signals)


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.400,
    time_window_step=0.400,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

fig, axes = plt.subplots(nrows=n_signals, ncols=n_signals, figsize=(15, 9))
meshes = []
for ind1, ind2 in product(range(n_signals), range(n_signals)):
    if ind1 == ind2:
        vmin, vmax = connectivity.power().min(), connectivity.power().max()
    else:
        vmin, vmax = 0, 1
    mesh = axes[ind1, ind2].pcolormesh(
        time_grid,
        freq_grid,
        connectivity.magnitude_squared_coherence()[..., ind1, ind2].squeeze().T,
        vmin=vmin,
        vmax=vmax,
        cmap="viridis",
    )
    meshes.append(mesh)
    axes[ind1, ind2].set_ylim((0, 100))
    axes[ind1, ind2].set_xlim(time_extent)

plt.suptitle("Coherence", y=1.02, fontsize=30)
plt.tight_layout()
cb = fig.colorbar(
    meshes[-2],
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Coherence",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")


canonical_coherence, pair_labels = connectivity.canonical_coherence(group_labels)
fig = plt.figure()
mesh = plt.pcolormesh(
    time_grid,
    freq_grid,
    canonical_coherence[..., 0, 1].squeeze().T,
    vmin=0,
    vmax=1,
    cmap="viridis",
)
plt.ylim((0, 100))
plt.suptitle("Canonical Coherence", y=1.02, fontsize=30)
cb = fig.colorbar(
    mesh,
    ax=plt.gca(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Coherence",
)
cb.outline.set_linewidth(0)
frequency resolution: 10.0
../_images/c968ebf2b6a14ca325463c34e2041bc845e951ca22b20b07c5892981d73f85f1.png ../_images/13eec8c3a2f6d0f1a596b7bfea7ef413622ac2375574c1a2ad56fa7c23e21a62.png
# In every window, canonical coherence between the groups is high at the shared
# 20 Hz and at chance at 40 Hz, where each group is nonetheless coherent within
# itself: the low value reflects no consistent phase relation between the
# groups, not an absence of signal.
frequencies = connectivity.frequencies
at_20_hz = np.argmin(np.abs(frequencies - 20))
at_40_hz = np.argmin(np.abs(frequencies - 40))
assert np.all(canonical_coherence[:, at_20_hz, 0, 1] > 0.95)
assert np.all(canonical_coherence[:, at_40_hz, 0, 1] < 0.1)
coherence_at_40_hz = connectivity.magnitude_squared_coherence()[:, at_40_hz]
for members in (np.flatnonzero(in_group_a), np.flatnonzero(in_group_b)):
    assert np.all(coherence_at_40_hz[:, members[0], members[1]] >= 0.9)

More signals, higher noise#

from itertools import product

time_halfbandwidth_product = 2
sampling_frequency = 500
time_extent = (0, 2.400)
n_trials = 100
n_signals = 6
noise_level = 3
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency
group_labels = ["a"] * 3 + ["b"] * 3
in_group_a = np.array(group_labels) == "a"
in_group_b = np.array(group_labels) == "b"

rng = np.random.default_rng(0)
simulation = dict(
    sampling_frequency=sampling_frequency,
    n_time_samples=n_time_samples,
    n_trials=n_trials,
    random_state=rng,
)
shared = simulate_shared_oscillation(
    20, **simulation, amplitudes=[1.0] * n_signals, noise_levels=noise_level
)
private_a = simulate_shared_oscillation(40, **simulation, amplitudes=in_group_a * 1.0)
private_b = simulate_shared_oscillation(40, **simulation, amplitudes=in_group_b * 1.0)
data = shared + private_a + private_b  # (n_time_samples, n_trials, n_signals)


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.400,
    time_window_step=0.400,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(connectivity.frequencies, multitaper.nyquist_frequency),
)

fig, axes = plt.subplots(nrows=n_signals, ncols=n_signals, figsize=(15, 9))
meshes = []
for ind1, ind2 in product(range(n_signals), range(n_signals)):
    if ind1 == ind2:
        vmin, vmax = connectivity.power().min(), connectivity.power().max()
    else:
        vmin, vmax = 0, 1
    mesh = axes[ind1, ind2].pcolormesh(
        time_grid,
        freq_grid,
        connectivity.magnitude_squared_coherence()[..., ind1, ind2].squeeze().T,
        vmin=vmin,
        vmax=vmax,
        cmap="viridis",
    )
    meshes.append(mesh)
    axes[ind1, ind2].set_ylim((0, 100))
    axes[ind1, ind2].set_xlim(time_extent)

plt.suptitle("Coherence", y=1.02, fontsize=30)
plt.tight_layout()
cb = fig.colorbar(
    meshes[-2],
    ax=axes.ravel().tolist(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Coherence",
)
cb.outline.set_linewidth(0)
print(f"frequency resolution: {multitaper.frequency_resolution}")


canonical_coherence, pair_labels = connectivity.canonical_coherence(group_labels)
fig = plt.figure()
mesh = plt.pcolormesh(
    time_grid,
    freq_grid,
    canonical_coherence[..., 0, 1].squeeze().T,
    vmin=0,
    vmax=1,
    cmap="viridis",
)
plt.xlabel("Time [s]")
plt.ylabel("Frequency [Hz]")
plt.ylim((0, 100))
plt.suptitle("Canonical Coherence", y=1.02, fontsize=30)
cb = fig.colorbar(
    mesh,
    ax=plt.gca(),
    orientation="horizontal",
    shrink=0.5,
    aspect=15,
    pad=0.1,
    label="Coherence",
)
cb.outline.set_linewidth(0)
frequency resolution: 10.0
../_images/c0d0332aaa55c59c50b39cf90165a191d6b87b87e1586f8b43b201b998de124b.png ../_images/a80f63791455eb850197a7d410293fd2b44924b98a0b5000190fc9163145b3c4.png
# With this much noise, every pairwise coherence between the groups at 20 Hz is
# modest, and canonical coherence combines the three signals in each group to
# find a stronger relation. It can never be below the largest pairwise value
# (a single signal is one of the combinations it maximizes over); the margin
# is the gain from combining. At 40 Hz the groups stay at chance.
frequencies = connectivity.frequencies
at_20_hz = np.argmin(np.abs(frequencies - 20))
at_40_hz = np.argmin(np.abs(frequencies - 40))
between_groups = connectivity.magnitude_squared_coherence()[:, at_20_hz][
    :, np.flatnonzero(in_group_a)
][:, :, np.flatnonzero(in_group_b)]  # (n_windows, 3, 3)
largest_pairwise = between_groups.max(axis=(1, 2))
assert np.all(canonical_coherence[:, at_20_hz, 0, 1] > largest_pairwise + 0.1)
assert np.all(canonical_coherence[:, at_40_hz, 0, 1] < 0.1)

Global Coherence#

Global coherence finds the linear combinations of signals that maximizes the power at a given frequency.

Six signals share one 200 Hz oscillation, each with its own amplitude and phase offset, plus independent noise, so a single component captures nearly all of the power at 200 Hz.

time_halfbandwidth_product = 2
frequency_of_interest = 200
sampling_frequency = 1500
time_extent = (0, 2.400)
n_trials = 100
n_signals = 6
n_time_samples = int(((time_extent[1] - time_extent[0]) * sampling_frequency) + 1)
time = np.arange(n_time_samples) / sampling_frequency

data = simulate_shared_oscillation(
    frequency_of_interest,
    sampling_frequency,
    n_time_samples,
    n_trials,
    amplitudes=0.5 + 0.2 * np.arange(n_signals),
    phase_offsets=np.linspace(0, np.pi, n_signals),
    noise_levels=0.5,
    random_state=0,
)  # (n_time_samples, n_trials, n_signals)


multitaper = Multitaper(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    start_time=time[0],
)
connectivity = Connectivity.from_transform(multitaper)

global_coherence, unnormalized_global_coherence = connectivity.global_coherence()
print(global_coherence.shape)  # n_time, n_frequencies, n_components

time_grid, freq_grid = np.meshgrid(
    np.append(connectivity.time, time_extent[-1]),
    np.append(
        connectivity.frequencies, connectivity.frequencies[-1]
    ),  # Add edge for pcolormesh
)
plt.figure()
plt.pcolormesh(
    time_grid,
    freq_grid,
    global_coherence[:, :, 0].T,  # (n_frequencies, n_time)
    shading="flat",
)
plt.title("Global Coherence (1st component)")
plt.xlabel("Time [s]")
plt.ylabel("Frequency [Hz]")
(30, 120, 1)
Text(0, 0.5, 'Frequency [Hz]')
../_images/f6e11a5d3d19cde0fd114525a7e9991ba8589f976de6673b80ca9e3efb325d8c.png
# The leading component carries nearly all of the power at 200 Hz in every
# window; away from it, noise alone gives it only about 1 / n_signals.
frequencies = connectivity.frequencies
peak = np.argmin(np.abs(frequencies - frequency_of_interest))
off_peak = np.abs(frequencies - frequency_of_interest) > multitaper.frequency_resolution
assert np.all(global_coherence[:, peak, 0] > 0.95)
assert np.median(global_coherence[:, off_peak, 0]) < 2 / n_signals

Xarray interface#

The xarray interface provides three things:

  1. a nicely labeled output for the connectivity dimensions

  2. a unified way of estimating the spectral power and connectivity together.

  3. easy and quick plotting

magnitude_squared_coherence = multitaper_connectivity(
    data,
    sampling_frequency=sampling_frequency,
    time_halfbandwidth_product=time_halfbandwidth_product,
    time_window_duration=0.080,
    time_window_step=0.080,
    method="magnitude_squared_coherence",
)

magnitude_squared_coherence
<xarray.DataArray 'magnitude_squared_coherence' (time: 30, frequency: 61,
                                                 source: 6, target: 6)> Size: 527kB
array([[[[           nan, 6.32711081e-03, 3.75905346e-04,
          3.38822772e-03, 1.50668611e-02, 1.31455338e-02],
         [6.32711081e-03,            nan, 5.63342314e-03,
          4.36351149e-05, 1.13507891e-02, 3.09557209e-04],
         [3.75905346e-04, 5.63342314e-03,            nan,
          4.68900524e-03, 2.11576309e-07, 1.49849895e-02],
         [3.38822772e-03, 4.36351149e-05, 4.68900524e-03,
                     nan, 3.84778474e-03, 2.09294368e-02],
         [1.50668611e-02, 1.13507891e-02, 2.11576309e-07,
          3.84778474e-03,            nan, 2.55590371e-02],
         [1.31455338e-02, 3.09557209e-04, 1.49849895e-02,
          2.09294368e-02, 2.55590371e-02,            nan]],

        [[           nan, 6.47201266e-03, 1.92274236e-03,
          1.51302842e-02, 4.83952948e-03, 1.25717943e-02],
         [6.47201266e-03,            nan, 9.02600777e-03,
          3.03439713e-03, 4.59092570e-03, 1.53589431e-03],
         [1.92274236e-03, 9.02600777e-03,            nan,
          2.32039675e-03, 1.37482914e-03, 6.23796850e-03],
         [1.51302842e-02, 3.03439713e-03, 2.32039675e-03,
...
         [1.45590208e-04, 1.63584295e-03, 6.29639602e-05,
                     nan, 2.13966979e-03, 2.25762126e-03],
         [4.99834368e-05, 5.71467526e-03, 8.53970890e-06,
          2.13966979e-03,            nan, 1.02400503e-03],
         [1.50032285e-03, 1.45027832e-03, 2.11415204e-03,
          2.25762126e-03, 1.02400503e-03,            nan]],

        [[           nan, 2.36197128e-03, 4.41778284e-04,
          3.65703812e-03, 5.79575907e-04, 4.98233155e-03],
         [2.36197128e-03,            nan, 2.48434970e-03,
          2.19280271e-02, 1.39815157e-03, 5.98547698e-04],
         [4.41778284e-04, 2.48434970e-03,            nan,
          1.44942652e-03, 8.72545873e-05, 2.10677358e-04],
         [3.65703812e-03, 2.19280271e-02, 1.44942652e-03,
                     nan, 5.58206020e-03, 3.66195007e-03],
         [5.79575907e-04, 1.39815157e-03, 8.72545873e-05,
          5.58206020e-03,            nan, 7.73794867e-03],
         [4.98233155e-03, 5.98547698e-04, 2.10677358e-04,
          3.66195007e-03, 7.73794867e-03,            nan]]]],
      shape=(30, 61, 6, 6))
Coordinates:
  * time       (time) float64 240B 0.03967 0.1197 0.1997 ... 2.2 2.28 2.36
  * frequency  (frequency) float64 488B 0.0 12.5 25.0 37.5 ... 725.0 737.5 750.0
  * source     (source) <U1 24B '0' '1' '2' '3' '4' '5'
  * target     (target) <U1 24B '0' '1' '2' '3' '4' '5'
Attributes: (12/45)
    transform:                      multitaper
    n_signals:                      6
    n_trials:                       100
    nyquist_frequency:              750.0
    sampling_frequency:             1500.0
    spectral_bandwidth:             50.0
    ...                             ...
    value_range_lower:              0.0
    value_range_upper:              1.0
    quantity:                       squared_magnitude
    formula:                        |S_st|^2 / (S_ss * S_tt), where S_st = E[...
    frequency_bin_spacing:          12.5
    frequency_bin_spacing_units:    Hz
magnitude_squared_coherence.plot(col="source", row="target", x="time");
../_images/6d18b472e9e7d80cf3e90c075576b3dcb873764697433d8a9bceff985eb019f4.png
# The labeled result holds the same numbers as `Connectivity.magnitude_squared_coherence`
# for the same data and parameters (the Global Coherence section above).
np.testing.assert_allclose(
    magnitude_squared_coherence.values, connectivity.magnitude_squared_coherence(), equal_nan=True
)