Spikes-phase coupling#

In this tutorial we will learn how to isolate phase information using band-pass filtering and combine it with spiking data, to find phase preferences of spiking units.

Specifically, we will examine LFP and spiking data from a period of REM sleep, after traversal of a linear track.

import math
import os

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import scipy
import seaborn as sns
import tqdm
import pynapple as nap

custom_params = {"axes.spines.right": False, "axes.spines.top": False}
sns.set_theme(style="ticks", palette="colorblind", font_scale=1.5, rc=custom_params)

Downloading the data#

Let’s download the data and save it locally

path = "Achilles_10252013_EEG.nwb"
if path not in os.listdir("."):
    r = requests.get(f"https://osf.io/2dfvp/download", stream=True)
    block_size = 1024 * 1024
    with open(path, "wb") as f:
        for data in tqdm.tqdm(
            r.iter_content(block_size),
            unit="MB",
            unit_scale=True,
            total=math.ceil(int(r.headers.get("content-length", 0)) // block_size),
        ):
            f.write(data)
  0%|          | 0.00/425 [00:00<?, ?MB/s]
  1%|          | 3.00/425 [00:00<00:18, 22.3MB/s]
  2%|▏         | 9.00/425 [00:00<00:10, 41.6MB/s]
  4%|▎         | 15.0/425 [00:00<00:08, 46.2MB/s]
  5%|▍         | 20.0/425 [00:00<00:09, 44.6MB/s]
  6%|▋         | 27.0/425 [00:00<00:08, 47.7MB/s]
  8%|▊         | 34.0/425 [00:00<00:07, 53.2MB/s]
 10%|▉         | 41.0/425 [00:00<00:06, 54.9MB/s]
 11%|█▏        | 48.0/425 [00:00<00:06, 56.6MB/s]
 13%|█▎        | 54.0/425 [00:01<00:06, 56.8MB/s]
 14%|█▍        | 60.0/425 [00:01<00:06, 54.5MB/s]
 16%|█▌        | 66.0/425 [00:01<00:07, 51.1MB/s]
 17%|█▋        | 74.0/425 [00:01<00:06, 56.3MB/s]
 19%|█▉        | 80.0/425 [00:01<00:06, 56.1MB/s]
 20%|██        | 87.0/425 [00:01<00:06, 53.2MB/s]
 23%|██▎       | 96.0/425 [00:01<00:05, 60.6MB/s]
 24%|██▍       | 103/425 [00:01<00:05, 59.7MB/s] 
 26%|██▌       | 111/425 [00:02<00:04, 64.4MB/s]
 28%|██▊       | 118/425 [00:02<00:05, 59.9MB/s]
 29%|██▉       | 125/425 [00:02<00:05, 58.4MB/s]
 31%|███       | 132/425 [00:02<00:04, 59.0MB/s]
 33%|███▎      | 139/425 [00:02<00:04, 58.3MB/s]
 34%|███▍      | 145/425 [00:02<00:05, 49.9MB/s]
 36%|███▌      | 151/425 [00:02<00:05, 49.5MB/s]
 37%|███▋      | 157/425 [00:02<00:05, 49.5MB/s]
 39%|███▉      | 165/425 [00:03<00:04, 56.9MB/s]
 40%|████      | 171/425 [00:03<00:04, 55.6MB/s]
 42%|████▏     | 177/425 [00:03<00:04, 52.3MB/s]
 43%|████▎     | 184/425 [00:03<00:04, 50.6MB/s]
 45%|████▌     | 192/425 [00:03<00:04, 57.0MB/s]
 47%|████▋     | 199/425 [00:03<00:03, 57.5MB/s]
 48%|████▊     | 206/425 [00:03<00:03, 58.9MB/s]
 50%|█████     | 214/425 [00:03<00:03, 60.8MB/s]
 52%|█████▏    | 221/425 [00:04<00:03, 60.8MB/s]
 54%|█████▎    | 228/425 [00:04<00:03, 56.3MB/s]
 56%|█████▌    | 237/425 [00:04<00:02, 62.7MB/s]
 57%|█████▋    | 244/425 [00:04<00:03, 58.1MB/s]
 59%|█████▉    | 251/425 [00:04<00:03, 55.7MB/s]
 61%|██████    | 259/425 [00:04<00:02, 60.0MB/s]
 63%|██████▎   | 266/425 [00:04<00:02, 54.0MB/s]
 64%|██████▍   | 274/425 [00:04<00:02, 58.6MB/s]
 66%|██████▌   | 281/425 [00:05<00:02, 58.0MB/s]
 68%|██████▊   | 287/425 [00:05<00:02, 52.2MB/s]
 69%|██████▉   | 294/425 [00:05<00:02, 55.2MB/s]
 71%|███████   | 300/425 [00:05<00:02, 54.1MB/s]
 72%|███████▏  | 308/425 [00:05<00:02, 58.0MB/s]
 74%|███████▍  | 314/425 [00:05<00:01, 57.5MB/s]
 76%|███████▌  | 321/425 [00:05<00:01, 58.4MB/s]
 77%|███████▋  | 329/425 [00:05<00:01, 63.2MB/s]
 79%|███████▉  | 336/425 [00:06<00:01, 60.1MB/s]
 81%|████████  | 343/425 [00:06<00:01, 60.5MB/s]
 82%|████████▏ | 350/425 [00:06<00:01, 60.0MB/s]
 84%|████████▍ | 357/425 [00:06<00:01, 59.8MB/s]
 86%|████████▌ | 365/425 [00:06<00:00, 63.1MB/s]
 88%|████████▊ | 372/425 [00:06<00:00, 59.5MB/s]
 89%|████████▉ | 379/425 [00:06<00:00, 60.5MB/s]
 91%|█████████ | 387/425 [00:06<00:00, 63.1MB/s]
 93%|█████████▎| 394/425 [00:06<00:00, 64.3MB/s]
 94%|█████████▍| 401/425 [00:07<00:00, 61.9MB/s]
 96%|█████████▌| 408/425 [00:07<00:00, 63.5MB/s]
 98%|█████████▊| 415/425 [00:07<00:00, 64.1MB/s]
100%|█████████▉| 423/425 [00:07<00:00, 66.8MB/s]
426MB [00:07, 57.4MB/s]                         


Loading the data#

Let’s load and print the full dataset.

data = nap.load_file(path)
FS = 1250  # We know from the methods of the paper
print(data)
/home/runner/.local/lib/python3.10/site-packages/hdmf/spec/namespace.py:535: UserWarning: Ignoring cached namespace 'hdmf-common' version 1.7.0 because version 1.8.0 is already loaded.
  warn("Ignoring cached namespace '%s' version %s because version %s is already loaded."
/home/runner/.local/lib/python3.10/site-packages/hdmf/spec/namespace.py:535: UserWarning: Ignoring cached namespace 'core' version 2.6.0-alpha because version 2.7.0 is already loaded.
  warn("Ignoring cached namespace '%s' version %s because version %s is already loaded."
/home/runner/.local/lib/python3.10/site-packages/hdmf/spec/namespace.py:535: UserWarning: Ignoring cached namespace 'hdmf-experimental' version 0.4.0 because version 0.5.0 is already loaded.
  warn("Ignoring cached namespace '%s' version %s because version %s is already loaded."
Achilles_10252013_EEG
┍━━━━━━━━━━━━━┯━━━━━━━━━━━━━┑
│ Keys        │ Type        │
┝━━━━━━━━━━━━━┿━━━━━━━━━━━━━┥
│ units       │ TsGroup     │
│ rem         │ IntervalSet │
│ nrem        │ IntervalSet │
│ forward_ep  │ IntervalSet │
│ eeg         │ TsdFrame    │
│ theta_phase │ Tsd         │
│ position    │ Tsd         │
┕━━━━━━━━━━━━━┷━━━━━━━━━━━━━┙

Selecting slices#

For later visualization, we define an interval of 3 seconds of data during REM sleep.

ep_ex_rem = nap.IntervalSet(
    data["rem"]["start"][0] + 97.0,
    data["rem"]["start"][0] + 100.0,
)

Here we restrict the lfp to the REM epochs.

tsd_rem = data["eeg"][:,0].restrict(data["rem"])

# We will also extract spike times from all units in our dataset
# which occur during REM sleep
spikes = data["units"].restrict(data["rem"])

Plotting the LFP Activity#

We should first plot our REM Local Field Potential data.

fig, ax = plt.subplots(1, constrained_layout=True, figsize=(10, 3))
ax.plot(tsd_rem.restrict(ep_ex_rem))
ax.set_title("REM Local Field Potential")
ax.set_ylabel("LFP (a.u.)")
ax.set_xlabel("time (s)")
Text(0.5, 0, 'time (s)')
../_images/be53eca6a6345ef6f279647fd718bda5625c2b687157e341edde7ce61996dd23.png

Getting the Wavelet Decomposition#

As we would expect, it looks like we have a very strong theta oscillation within our data

  • this is a common feature of REM sleep. Let’s perform a wavelet decomposition, as we did in the last tutorial, to see get a more informative breakdown of the frequencies present in the data.

We must define the frequency set that we’d like to use for our decomposition.

freqs = np.geomspace(5, 200, 25)

We compute the wavelet transform on our LFP data (only during the example interval).

cwt_rem = nap.compute_wavelet_transform(tsd_rem.restrict(ep_ex_rem), fs=FS, freqs=freqs)

Now let’s plot the calculated wavelet scalogram.

# Define wavelet decomposition plotting function
def plot_timefrequency(freqs, powers, ax=None):
    im = ax.imshow(np.abs(powers), aspect="auto")
    ax.invert_yaxis()
    ax.set_xlabel("Time (s)")
    ax.set_ylabel("Frequency (Hz)")
    ax.get_xaxis().set_visible(False)
    ax.set(yticks=np.arange(len(freqs))[::2], yticklabels=np.rint(freqs[::2]))
    ax.grid(False)
    return im

fig = plt.figure(constrained_layout=True, figsize=(10, 6))
fig.suptitle("Wavelet Decomposition")
gs = plt.GridSpec(2, 1, figure=fig, height_ratios=[1.0, 0.3])

ax0 = plt.subplot(gs[0, 0])
im = plot_timefrequency(freqs, np.transpose(cwt_rem[:, :].values), ax=ax0)
cbar = fig.colorbar(im, ax=ax0, orientation="vertical")

ax1 = plt.subplot(gs[1, 0])
ax1.plot(tsd_rem.restrict(ep_ex_rem))
ax1.set_ylabel("LFP (a.u.)")
ax1.set_xlabel("Time (s)")
ax1.margins(0)
../_images/753445189480b14154d588cc90706a8e48b1e2a13a913446f0c3fae72b68f300.png

Filtering Theta#

As expected, there is a strong 8Hz component during REM sleep. We can filter it using the function nap.apply_bandpass_filter.

theta_band = nap.apply_bandpass_filter(tsd_rem, cutoff=(6.0, 10.0), fs=FS)

We can plot the original signal and the filtered signal.

plt.figure(constrained_layout=True, figsize=(12, 3))
plt.plot(tsd_rem.restrict(ep_ex_rem), alpha=0.5)
plt.plot(theta_band.restrict(ep_ex_rem))
plt.xlabel("Time (s)")
plt.show()
../_images/52292bdcf507d20f8eebc382e5afcf71cbbef22e80f86054fbeb3b39587dce03.png

Computing phase#

From the filtered signal, it is easy to get the phase using the Hilbert transform. Here we use scipy Hilbert method.

from scipy import signal

theta_phase = nap.Tsd(t=theta_band.t, d=np.angle(signal.hilbert(theta_band)))

Let’s plot the phase.

plt.figure(constrained_layout=True, figsize=(12, 3))
plt.subplot(211)
plt.plot(tsd_rem.restrict(ep_ex_rem), alpha=0.5)
plt.plot(theta_band.restrict(ep_ex_rem))
plt.subplot(212)
plt.plot(theta_phase.restrict(ep_ex_rem), color='r')
plt.ylabel("Phase (rad)")
plt.xlabel("Time (s)")
plt.show()
../_images/537d1ec612242220c232233225eff3374ed5a8272a24a0a0d8dbc0056f5fe785.png

Finding Phase of Spikes#

Now that we have the phase of our theta wavelet, and our spike times, we can find the phase firing preferences of each of the units using the compute_1d_tuning_curves function.

We will start by throwing away cells which do not have a high enough firing rate during our interval.

spikes = spikes[spikes.rate > 5.0]

The feature is the theta phase during REM sleep.

phase_modulation = nap.compute_1d_tuning_curves(
    group=spikes, feature=theta_phase, nb_bins=61, minmax=(-np.pi, np.pi)
)

Let’s plot the first 3 neurons.

plt.figure(constrained_layout=True, figsize = (12, 3))
for i in range(3):
    plt.subplot(1,3,i+1)
    plt.plot(phase_modulation.iloc[:,i])
    plt.xlabel("Phase (rad)")
    plt.ylabel("Firing rate (Hz)")
plt.show()
../_images/9ce85a83fcc3a452cb09c3de71057f434edde5844b96357ae129ca3c40f20016.png

There is clearly a strong modulation for the third neuron. Finally, we can use the function value_from to align each spikes to the corresponding phase position and overlay it with the LFP.

spike_phase = spikes[spikes.index[3]].value_from(theta_phase)

Let’s plot it.

plt.figure(constrained_layout=True, figsize=(12, 3))
plt.subplot(211)
plt.plot(tsd_rem.restrict(ep_ex_rem), alpha=0.5)
plt.plot(theta_band.restrict(ep_ex_rem))
plt.subplot(212)
plt.plot(theta_phase.restrict(ep_ex_rem), alpha=0.5)
plt.plot(spike_phase.restrict(ep_ex_rem), 'o')
plt.ylabel("Phase (rad)")
plt.xlabel("Time (s)")
plt.show()
../_images/12eae8e8d089b0b4a7373ff7402cfddac831613ab4bace1e9fb3945da4749c29.png

Authors

Kipp Freud (https://kippfreud.com/)

Guillaume Viejo