Analysing head-direction cells#
This tutorial demonstrates how we use Pynapple to generate Figure 4a in the publication. The NWB file for the example is hosted on OSF. We show below how to stream it. The entire dataset can be downloaded here.
import numpy as np
import pandas as pd
import pynapple as nap
import scipy.ndimage
import matplotlib.pyplot as plt
import seaborn as sns
import requests, math, os
import tqdm
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#
It’s a small NWB file.
path = "Mouse32-140822.nwb"
if path not in os.listdir("."):
r = requests.get(f"https://osf.io/jb2gd/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/34.0 [00:00<?, ?MB/s]
12%|█▏ | 4.00/34.0 [00:00<00:00, 37.8MB/s]
26%|██▋ | 9.00/34.0 [00:00<00:00, 44.3MB/s]
50%|█████ | 17.0/34.0 [00:00<00:00, 59.8MB/s]
71%|███████ | 24.0/34.0 [00:00<00:00, 60.0MB/s]
94%|█████████▍| 32.0/34.0 [00:00<00:00, 65.0MB/s]
35.0MB [00:00, 61.2MB/s]
Parsing the data#
The first step is to load the data and other relevant variables of interest
data = nap.load_file(path) # Load the NWB file for this dataset
/home/runner/.local/lib/python3.10/site-packages/hdmf/spec/namespace.py:535: UserWarning: Ignoring cached namespace 'hdmf-common' version 1.5.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.4.0 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.1.0 because version 0.5.0 is already loaded.
warn("Ignoring cached namespace '%s' version %s because version %s is already loaded."
What does this look like ?
print(data)
Mouse32-140822
┍━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┑
│ Keys │ Type │
┝━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━┥
│ units │ TsGroup │
│ sws │ IntervalSet │
│ rem │ IntervalSet │
│ position_time_support │ IntervalSet │
│ epochs │ IntervalSet │
│ ry │ Tsd │
┕━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┙
Head-Direction Tuning Curves#
To plot Head-Direction Tuning curves, we need the spike timings and the orientation of the animal. These quantities are stored in the variables ‘units’ and ‘ry’.
spikes = data["units"] # Get spike timings
epochs = data["epochs"] # Get the behavioural epochs (in this case, sleep and wakefulness)
angle = data["ry"] # Get the tracked orientation of the animal
What does this look like ?
print(spikes)
Index rate location group
------- ------- ---------- -------
0 2.96981 thalamus 1
1 2.42638 thalamus 1
2 5.93417 thalamus 1
3 5.04432 thalamus 1
4 0.30207 adn 2
5 0.87042 adn 2
6 0.36154 adn 2
... ... ... ...
42 1.02061 thalamus 5
43 6.84913 thalamus 6
44 0.94002 thalamus 6
45 0.55768 thalamus 6
46 1.15056 thalamus 6
47 0.46084 thalamus 6
48 0.19287 thalamus 7
Here, rate is the mean firing rate of the unit. Location indicates the brain region the unit was recorded from, and group refers to the shank number on which the cell was located.
This dataset contains units recorded from the anterior thalamus. Head-direction (HD) cells are found in the anterodorsal nucleus of the thalamus (henceforth referred to as ADn). Units were also recorded from nearby thalamic nuclei in this animal. For the purposes of our tutorial, we are interested in the units recorded in ADn. We can restrict ourselves to analysis of these units rather easily, using Pynapple.
spikes_adn = spikes.getby_category("location")["adn"] # Select only those units that are in ADn
What does this look like ?
print(spikes_adn)
Index rate location group
------- -------- ---------- -------
4 0.30207 adn 2
5 0.87042 adn 2
6 0.36154 adn 2
7 10.51737 adn 2
8 2.62475 adn 2
9 2.55818 adn 2
10 7.06715 adn 2
... ... ... ...
28 1.78011 adn 4
29 4.23006 adn 4
30 2.15215 adn 4
31 0.58829 adn 4
32 1.12899 adn 4
33 5.26316 adn 4
34 1.57122 adn 4
Let’s compute some head-direction tuning curves. To do this in Pynapple, all you need is a single line of code!
Plot firing rate of ADn units as a function of heading direction, i.e. a head-direction tuning curve
tuning_curves = nap.compute_1d_tuning_curves(
group=spikes_adn,
feature=angle,
nb_bins=61,
ep = epochs['wake'],
minmax=(0, 2 * np.pi)
)
What does this look like ?
tuning_curves
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ... | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0.051502 | 0.255172 | 0.127586 | 0.170115 | 5.316080 | 0.000000 | 0.722987 | 5.231023 | 0.467815 | 0.680458 | 9.313772 | ... | 0.722987 | 2.636776 | 0.000000 | 0.000000 | 0.297700 | 0.850573 | 0.552872 | 0.467815 | 5.273551 | 1.786203 |
0.154505 | 0.300635 | 0.000000 | 0.187897 | 8.305042 | 0.037579 | 0.338214 | 3.194247 | 0.338214 | 0.751587 | 8.718415 | ... | 0.338214 | 1.691072 | 0.000000 | 0.000000 | 0.375794 | 0.751587 | 1.014643 | 0.375794 | 8.380200 | 1.954127 |
0.257508 | 0.189885 | 0.094943 | 0.094943 | 11.867814 | 0.158238 | 0.094943 | 3.671110 | 0.316475 | 0.569655 | 9.430956 | ... | 0.632950 | 1.107663 | 0.031648 | 0.000000 | 0.348123 | 1.076015 | 1.677318 | 0.158238 | 10.506971 | 3.892643 |
0.360511 | 0.498062 | 0.052428 | 0.078641 | 16.724387 | 0.052428 | 0.314565 | 4.534983 | 0.340779 | 0.655344 | 10.170944 | ... | 0.498062 | 1.992247 | 0.078641 | 0.000000 | 0.366993 | 0.629131 | 1.782537 | 0.235924 | 12.556397 | 5.321396 |
0.463514 | 0.362941 | 0.111674 | 0.139593 | 20.631824 | 0.055837 | 0.335023 | 4.411134 | 0.279186 | 0.725883 | 11.502451 | ... | 0.335023 | 0.530453 | 0.055837 | 0.000000 | 0.418779 | 0.642127 | 2.456834 | 0.307104 | 15.271458 | 8.431408 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
5.819672 | 0.063460 | 0.158650 | 0.190380 | 1.491313 | 0.793252 | 0.507681 | 5.584491 | 0.444221 | 1.554773 | 2.284565 | ... | 1.015362 | 12.565105 | 0.095190 | 0.000000 | 0.095190 | 2.221104 | 0.095190 | 0.253841 | 0.285571 | 0.507681 |
5.922675 | 0.024772 | 0.123861 | 0.123861 | 1.337703 | 0.569762 | 0.445901 | 4.558100 | 0.371584 | 0.990891 | 3.146080 | ... | 1.040436 | 10.032774 | 0.049545 | 0.074317 | 0.099089 | 1.535882 | 0.049545 | 0.396357 | 0.767941 | 0.272495 |
6.025678 | 0.000000 | 0.112276 | 0.028069 | 1.936754 | 0.533309 | 0.224551 | 4.406818 | 0.392965 | 1.263101 | 5.333091 | ... | 0.926274 | 6.427778 | 0.000000 | 0.084207 | 0.112276 | 1.038549 | 0.084207 | 0.364896 | 0.954343 | 0.196482 |
6.128681 | 0.000000 | 0.138009 | 0.165611 | 2.152940 | 0.220814 | 0.386425 | 4.223075 | 0.441629 | 1.076470 | 4.637101 | ... | 0.634841 | 6.265607 | 0.055204 | 0.027602 | 0.027602 | 0.938461 | 0.055204 | 0.331222 | 1.021266 | 0.441629 |
6.231684 | 0.067699 | 0.101548 | 0.135397 | 2.504850 | 0.000000 | 0.304644 | 3.791124 | 0.372343 | 0.541589 | 5.720536 | ... | 0.473891 | 3.892672 | 0.000000 | 0.033849 | 0.101548 | 0.812384 | 0.304644 | 0.541589 | 2.234055 | 0.609288 |
61 rows × 31 columns
Each row indicates an angular bin (in radians), and each column corresponds to a single unit. Let’s compute the preferred angle quickly as follows:
pref_ang = tuning_curves.idxmax()
For easier visualization, we will colour our plots according to the preferred angle of the cell. To do so, we will normalize the range of angles we have, over a colourmap.
norm = plt.Normalize() # Normalizes data into the range [0,1]
color = plt.cm.hsv(norm([i / (2 * np.pi) for i in pref_ang.values])) # Assigns a colour in the HSV colourmap for each value of preferred angle
color = pd.DataFrame(index=pref_ang.index, data = color, columns = ['r', 'g', 'b', 'a'])
To make the tuning curves look nice, we will smooth them before plotting, using this custom function:
from scipy.ndimage import gaussian_filter1d
def smoothAngularTuningCurves(tuning_curves, sigma=2):
tmp = np.concatenate((tuning_curves.values, tuning_curves.values, tuning_curves.values))
tmp = gaussian_filter1d(tmp, sigma=sigma, axis=0)
return pd.DataFrame(index = tuning_curves.index,
data = tmp[tuning_curves.shape[0]:tuning_curves.shape[0]*2],
columns = tuning_curves.columns
)
Therefore, we have:
smoothcurves = smoothAngularTuningCurves(tuning_curves, sigma=3)
What does this look like? Let’s plot the tuning curves!
plt.figure(figsize=(12, 9))
for i, n in enumerate(pref_ang.sort_values().index.values):
plt.subplot(8, 4, i + 1, projection='polar') # Plot the curves in 8 rows and 4 columns
plt.plot(
smoothcurves[n], color=color.loc[n]
) # Colour of the curves determined by preferred angle
plt.xticks([])
plt.show()
Awesome!
Decoding#
Now that we have HD tuning curves, we can go one step further. Using only the population activity of ADn units, we can decode the direction the animal is looking in. We will then compare this to the real head direction of the animal, and discover that population activity in the ADn indeed codes for HD.
To decode the population activity, we will be using a Bayesian Decoder as implemented in Pynapple. Just a single line of code!
decoded, proba_feature = nap.decode_1d(
tuning_curves=tuning_curves,
group=spikes_adn,
ep=epochs["wake"],
bin_size=0.1, # second
feature=angle,
)
What does this look like ?
print(decoded)
Time (s)
---------- ---------
8812.35 0.772523
8812.45 0.66952
8812.55 0.463514
8812.65 0.66952
8812.75 0.66952
8812.85 0.66952
8812.95 0.566517
...
10770.65 0.0515015
10770.75 5.92267
10770.85 5.71667
10770.95 5.92267
10771.05 5.92267
10771.15 5.92267
10771.25 5.92267
dtype: float64, shape: (19590,)
The variable ‘decoded’ indicates the most probable angle in which the animal was looking. There is another variable, ‘proba_feature’ that denotes the probability of a given angular bin at a given time point. We can look at it below:
print(proba_feature)
Time (s) 0.05150151891130808 0.15450455673392424 0.2575075945565404 0.3605106323791566 0.4635136702017727 ...
---------- --------------------- --------------------- -------------------- -------------------- -------------------- -----
8812.35 0 0.00022 0.00372 0.0177 0.07205 ...
8812.45 0 1e-05 0.00186 0.00931 0.09217 ...
8812.55 0.00042 0.02271 0.19166 0.19196 0.24892 ...
8812.65 1e-05 0.00016 0.00566 0.01974 0.10971 ...
8812.75 4e-05 0.00137 0.02089 0.03928 0.13386 ...
8812.85 1e-05 0.00036 0.02056 0.0518 0.1563 ...
8812.95 1e-05 0.00113 0.03198 0.06256 0.2143 ...
...
10770.65 0.35186 0.17771 0.07297 0.02443 0.00802 ...
10770.75 0.01448 0.00716 0.00084 0.00026 1e-05 ...
10770.85 7e-05 0 0 0 0 ...
10770.95 0.00029 0 0 0 0 ...
10771.05 0.00109 0.00012 1e-05 0 0 ...
10771.15 0.00554 0.00124 0.00012 2e-05 0 ...
10771.25 0.0006 6e-05 0 0 0 ...
dtype: float64, shape: (19590, 61)
Each row is a time bin, and each column is an angular bin. The sum of all values in a row add up to 1.
Now, let’s plot the raster plot for a given period of time, and overlay the actual and decoded HD on the population activity.
ep = nap.IntervalSet(
start=10717, end=10730
) # Select an arbitrary interval for plotting
plt.figure()
plt.rc("font", size=12)
for i, n in enumerate(spikes_adn.keys()):
plt.plot(
spikes[n].restrict(ep).fillna(pref_ang[n]), "|", color=color.loc[n]
) # raster plot for each cell
plt.plot(
decoded.restrict(ep), "--", color="grey", linewidth=2, label="decoded HD"
) # decoded HD
plt.legend(loc="upper left")
plt.xlabel("Time (s)")
plt.ylabel("Neurons")
Text(0, 0.5, 'Neurons')
From this plot, we can see that the decoder is able to estimate the head-direction based on the population activity in ADn. Amazing!
What does the probability distribution in this example event look like? Ideally, the bins with the highest probability will correspond to the bins having the most spikes. Let’s plot the probability matrix to visualize this.
smoothed = scipy.ndimage.gaussian_filter(
proba_feature, 1
) # Smoothening the probability distribution
# Create a DataFrame with the smoothed distribution
p_feature = pd.DataFrame(
index=proba_feature.index.values,
columns=proba_feature.columns.values,
data=smoothed,
)
p_feature = nap.TsdFrame(p_feature) # Make it a Pynapple TsdFrame
plt.figure()
plt.plot(
angle.restrict(ep), "w", linewidth=2, label="actual HD", zorder=1
) # Actual HD, in white
plt.plot(
decoded.restrict(ep), "--", color="grey", linewidth=2, label="decoded HD", zorder=1
) # Decoded HD, in grey
# Plot the smoothed probability distribution
plt.imshow(
np.transpose(p_feature.restrict(ep).values),
aspect="auto",
interpolation="bilinear",
extent=[ep["start"][0], ep["end"][0], 0, 2 * np.pi],
origin="lower",
cmap="viridis",
)
plt.xlabel("Time (s)") # X-axis is time in seconds
plt.ylabel("Angle (rad)") # Y-axis is the angle in radian
plt.colorbar(label="probability")
<matplotlib.colorbar.Colorbar at 0x7f44f5db7610>
From this probability distribution, we observe that the decoded HD very closely matches the actual HD. Therefore, the population activity in ADn is a reliable estimate of the heading direction of the animal.
I hope this tutorial was helpful. If you have any questions, comments or suggestions, please feel free to reach out to the Pynapple Team!
Authors
Dhruv Mehrotra
Guillaume Viejo