Tuning curves#
Pynapple can compute 1 dimension tuning curves (for example firing rate as a function of angular direction) and 2 dimension tuning curves ( for example firing rate as a function of position). It can also compute average firing rate for different epochs (for example firing rate for different epochs of stimulus presentation).
Important
If you are using calcium imaging data with the activity of the cell as a continuous transient, the function to call ends with _continuous
for continuous time series (e.g. compute_1d_tuning_curves_continuous
).
Show code cell content
import pynapple as nap
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pprint import pprint
custom_params = {"axes.spines.right": False, "axes.spines.top": False}
sns.set_theme(style="ticks", palette="colorblind", font_scale=1.5, rc=custom_params)
Show code cell content
group = {
0: nap.Ts(t=np.sort(np.random.uniform(0, 100, 10))),
1: nap.Ts(t=np.sort(np.random.uniform(0, 100, 20))),
2: nap.Ts(t=np.sort(np.random.uniform(0, 100, 30))),
}
tsgroup = nap.TsGroup(group)
from epochs#
The epochs should be stored in a dictionnary :
dict_ep = {
"stim0": nap.IntervalSet(start=0, end=20),
"stim1":nap.IntervalSet(start=30, end=70)
}
nap.compute_discrete_tuning_curves
takes a TsGroup
for spiking activity and a dictionary of epochs.
The output is a pandas DataFrame where each column is a unit in the TsGroup
and each row is one IntervalSet
type.
The value is the mean firing rate of the neuron during this set of intervals.
mean_fr = nap.compute_discrete_tuning_curves(tsgroup, dict_ep)
pprint(mean_fr)
0 1 2
stim0 0.100 0.300 0.400
stim1 0.075 0.075 0.225
from timestamps activity#
1-dimension tuning curves#
Show code cell content
from scipy.ndimage import gaussian_filter1d
# Fake Tuning curves
N = 6 # Number of neurons
bins = np.linspace(0, 2*np.pi, 61)
x = np.linspace(-np.pi, np.pi, len(bins)-1)
tmp = np.roll(np.exp(-(1.5*x)**2), (len(bins)-1)//2)
generative_tc = np.array([np.roll(tmp, i*(len(bins)-1)//N) for i in range(N)]).T
# Feature
T = 50000
dt = 0.002
timestep = np.arange(0, T)*dt
feature = nap.Tsd(
t=timestep,
d=gaussian_filter1d(np.cumsum(np.random.randn(T)*0.5), 20)%(2*np.pi)
)
index = np.digitize(feature, bins)-1
# Spiking activity
count = np.random.poisson(generative_tc[index])>0
tsgroup = nap.TsGroup(
{i:nap.Ts(timestep[count[:,i]]) for i in range(N)},
time_support = nap.IntervalSet(0, 100)
)
Mandatory arguments are TsGroup
, Tsd
(or TsdFrame
with 1 column only)
and nb_bins
for number of bins of the tuning curves.
If an IntervalSet
is passed with ep
, everything is restricted to ep
otherwise the time support of the feature is used.
The min and max of the tuning curve is by default the min and max of the feature. This can be tweaked with the argument minmax
.
The output is a pandas DataFrame. Each column is a unit from TsGroup
argument. The index of the DataFrame carries the center of the bin in feature space.
tuning_curve = nap.compute_1d_tuning_curves(
group=tsgroup,
feature=feature,
nb_bins=120,
minmax=(0, 2*np.pi)
)
print(tuning_curve)
0 1 2 3 4 5
0.026180 299.579552 42.644776 0.0 0.0 0.000000 25.586866
0.078540 314.934724 51.125767 0.0 0.0 0.000000 24.540368
0.130900 299.570262 82.790327 0.0 0.0 0.000000 18.518889
0.183260 305.561667 70.989074 0.0 0.0 0.000000 11.317099
0.235619 301.711791 101.281343 0.0 0.0 0.000000 4.264478
... ... ... ... ... ... ...
6.047566 265.828101 11.392633 0.0 0.0 1.265848 112.660481
6.099926 293.532656 15.625313 0.0 0.0 0.000000 74.778281
6.152286 301.155448 12.643931 0.0 0.0 0.000000 60.920759
6.204645 313.090374 32.710935 0.0 0.0 0.000000 37.383925
6.257005 306.895491 27.140418 0.0 0.0 0.000000 39.666764
[120 rows x 6 columns]
plt.figure()
plt.plot(tuning_curve)
plt.xlabel("Feature space")
plt.ylabel("Firing rate (Hz)")
plt.show()
Internally, the function is calling the method value_from
which maps a timestamps
to its closest value in time from a Tsd
object.
It is then possible to validate the tuning curves by displaying the
timestamps as well as their associated values.
Show code cell source
plt.figure()
plt.subplot(121)
plt.plot(tsgroup[3].value_from(feature), 'o')
plt.plot(feature, label="feature")
plt.ylabel("Feature")
plt.xlim(0, 2)
plt.xlabel("Time (s)")
plt.subplot(122)
plt.plot(tuning_curve[3].values, tuning_curve[3].index.values, label="Tuning curve (unit=3)")
plt.xlabel("Firing rate (Hz)")
plt.legend()
plt.show()
2-dimension tuning curves#
Show code cell content
dt = 0.01
T = 10
epoch = nap.IntervalSet(start=0, end=T, time_units="s")
features = np.vstack((np.cos(np.arange(0, T, dt)), np.sin(np.arange(0, T, dt)))).T
features = nap.TsdFrame(
t=np.arange(0, T, dt),
d=features,
time_units="s",
time_support=epoch,
columns=["a", "b"],
)
tsgroup = nap.TsGroup({
0: nap.Ts(t=np.sort(np.random.uniform(0, T, 10))),
1: nap.Ts(t=np.sort(np.random.uniform(0, T, 15))),
2: nap.Ts(t=np.sort(np.random.uniform(0, T, 20))),
}, time_support=epoch)
The group
argument must be a TsGroup
object.
The features
argument must be a 2-columns TsdFrame
object.
nb_bins
can be an int or a tuple of 2 ints.
tcurves2d, binsxy = nap.compute_2d_tuning_curves(
group=tsgroup,
features=features,
nb_bins=(5,5),
minmax=(-1, 1, -1, 1)
)
pprint(tcurves2d)
{0: array([[0. , 0. , 1.25 , 1.12359551, 1.75438596],
[2.22222222, nan, nan, nan, 1.13636364],
[0. , nan, nan, nan, 2.4691358 ],
[0. , nan, nan, nan, 2.27272727],
[0. , 0. , 0. , 0. , 1.75438596]]),
1: array([[0. , 1.2345679 , 0. , 2.24719101, 3.50877193],
[6.66666667, nan, nan, nan, 0. ],
[0. , nan, nan, nan, 2.4691358 ],
[0. , nan, nan, nan, 1.13636364],
[0. , 4.44444444, 1.63934426, 0. , 1.75438596]]),
2: array([[3.57142857, 1.2345679 , 2.5 , 0. , 7.01754386],
[2.22222222, nan, nan, nan, 0. ],
[0. , nan, nan, nan, 1.2345679 ],
[4.54545455, nan, nan, nan, 3.40909091],
[0. , 0. , 3.27868852, 3.40909091, 0. ]])}
/home/runner/.local/lib/python3.10/site-packages/pynapple/process/tuning_curves.py:269: RuntimeWarning: invalid value encountered in divide
count = count / occupancy
tcurves2d
is a dictionnary with each key a unit in TsGroup
. binsxy
is a numpy array representing the centers of the bins and is useful for plotting tuning curves. Bins that have never been visited by the feature have been assigned a NaN value.
Checking the accuracy of the tuning curves can be bone by displaying the spikes aligned to the features with the function value_from
which assign to each spikes the corresponding features value for unit 0.
ts_to_features = tsgroup[0].value_from(features)
print(ts_to_features)
Time (s) a b
---------- -------- --------
1.00538 0.53186 0.84683
1.77133 -0.19789 0.98022
1.88781 -0.31381 0.94949
4.23436 -0.4639 -0.88589
6.95072 0.7858 0.61849
7.34017 0.49165 0.87079
7.94666 -0.09587 0.99539
8.51527 -0.61786 0.78629
8.84999 -0.83931 0.54365
9.32134 -0.99452 0.10459
dtype: float64, shape: (10, 2)
tsgroup[0]
which is a Ts
object has been transformed to a TsdFrame
object with each timestamps (spike times) being associated with a features value.
Show code cell source
plt.figure()
plt.subplot(121)
plt.plot(features["b"], features["a"], label="features")
plt.plot(ts_to_features["b"], ts_to_features["a"], "o", color="red", markersize=4, label="spikes")
plt.xlabel("feature b")
plt.ylabel("feature a")
[plt.axvline(b, linewidth=0.5, color='grey') for b in np.linspace(-1, 1, 6)]
[plt.axhline(b, linewidth=0.5, color='grey') for b in np.linspace(-1, 1, 6)]
plt.subplot(122)
extents = (
np.min(features["a"]),
np.max(features["a"]),
np.min(features["b"]),
np.max(features["b"]),
)
plt.imshow(tcurves2d[0],
origin="lower", extent=extents, cmap="viridis",
aspect='auto'
)
plt.title("Tuning curve unit 0")
plt.xlabel("feature b")
plt.ylabel("feature a")
plt.grid(False)
plt.colorbar()
plt.tight_layout()
plt.show()
from continuous activity#
Tuning curves compute with the following functions are usually made with data from calcium imaging activities.
1-dimension tuning curves#
Show code cell content
from scipy.ndimage import gaussian_filter1d
# Fake Tuning curves
N = 3 # Number of neurons
bins = np.linspace(0, 2*np.pi, 61)
x = np.linspace(-np.pi, np.pi, len(bins)-1)
tmp = np.roll(np.exp(-(1.5*x)**2), (len(bins)-1)//2)
generative_tc = np.array([np.roll(tmp, i*(len(bins)-1)//N) for i in range(N)]).T
# Feature
T = 50000
dt = 0.002
timestep = np.arange(0, T)*dt
feature = nap.Tsd(
t=timestep,
d=gaussian_filter1d(np.cumsum(np.random.randn(T)*0.5), 20)%(2*np.pi)
)
index = np.digitize(feature, bins)-1
tmp = generative_tc[index]
tmp = tmp + np.random.randn(*tmp.shape)*1
# Calcium activity
tsdframe = nap.TsdFrame(
t=timestep,
d=tmp
)
Arguments are TsdFrame
(for example continuous calcium data), Tsd
or TsdFrame
for the 1-d feature and nb_bins
for the number of bins.
tuning_curves = nap.compute_1d_tuning_curves_continuous(
tsdframe=tsdframe,
feature=feature,
nb_bins=120,
minmax=(0, 2*np.pi)
)
print(tuning_curves)
0 1 2
0.026180 1.009431 0.097413 0.002980
0.078540 0.969451 0.039247 0.052911
0.130900 0.932242 0.017739 -0.107303
0.183260 0.942690 0.007109 0.015666
0.235619 0.916330 -0.037062 0.044159
... ... ... ...
6.047566 0.888909 0.022497 0.017480
6.099926 0.914400 0.050240 -0.043806
6.152286 1.044069 -0.023993 0.032036
6.204645 1.003635 -0.051960 -0.067883
6.257005 1.061270 -0.043382 -0.022050
[120 rows x 3 columns]
plt.figure()
plt.plot(tuning_curves)
plt.xlabel("Feature space")
plt.ylabel("Mean activity")
plt.show()
2-dimension tuning curves#
Show code cell content
dt = 0.01
T = 10
epoch = nap.IntervalSet(start=0, end=T, time_units="s")
features = np.vstack((np.cos(np.arange(0, T, dt)), np.sin(np.arange(0, T, dt)))).T
features = nap.TsdFrame(
t=np.arange(0, T, dt),
d=features,
time_units="s",
time_support=epoch,
columns=["a", "b"],
)
# Calcium activity
tsdframe = nap.TsdFrame(
t=timestep,
d=np.random.randn(len(timestep), 2)
)
Arguments are TsdFrame
(for example continuous calcium data), Tsd
or TsdFrame
for the 1-d feature and nb_bins
for the number of bins.
tuning_curves, xy = nap.compute_2d_tuning_curves_continuous(
tsdframe=tsdframe,
features=features,
nb_bins=5,
)
print(tuning_curves)
{0: array([[-0.00443023, -0.03561127, 0.03641463, 0.01685678, -0.04471645],
[-0.09965156, nan, nan, nan, -0.07400481],
[ 0.2106301 , nan, nan, nan, -0.05158883],
[-0.06636167, nan, nan, nan, -0.07457431],
[ 0.00098127, 0.04642678, 0.01162619, -0.00726884, -0.05475807]]), 1: array([[ 0.11356423, -0.11542559, 0.03849253, 0.07902 , -0.05408887],
[ 0.02313956, nan, nan, nan, 0.00780415],
[ 0.02110394, nan, nan, nan, -0.05001222],
[ 0.03645972, nan, nan, nan, -0.00918081],
[-0.11297162, -0.11973048, 0.01287164, 0.03870288, -0.07966151]])}
/home/runner/.local/lib/python3.10/site-packages/numpy/_core/fromnumeric.py:3596: RuntimeWarning: Mean of empty slice.
return _methods._mean(a, axis=axis, dtype=dtype,
/home/runner/.local/lib/python3.10/site-packages/numpy/_core/_methods.py:130: RuntimeWarning: invalid value encountered in divide
ret = um.true_divide(
plt.figure()
plt.subplot(121)
plt.plot(features["b"], features["a"], label="features")
plt.xlabel("feature b")
plt.ylabel("feature a")
[plt.axvline(b, linewidth=0.5, color='grey') for b in np.linspace(-1, 1, 6)]
[plt.axhline(b, linewidth=0.5, color='grey') for b in np.linspace(-1, 1, 6)]
plt.subplot(122)
extents = (
np.min(features["a"]),
np.max(features["a"]),
np.min(features["b"]),
np.max(features["b"]),
)
plt.imshow(tuning_curves[0],
origin="lower", extent=extents, cmap="viridis",
aspect='auto'
)
plt.title("Tuning curve unit 0")
plt.xlabel("feature b")
plt.ylabel("feature a")
plt.grid(False)
plt.colorbar()
plt.tight_layout()
plt.show()