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.10 0.250 0.050
stim1 0.15 0.225 0.475
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 306.106340 39.216471 0.0 0.0 0.0 32.680392
0.078540 317.223326 33.019528 0.0 0.0 0.0 34.198797
0.130900 312.188985 73.605533 0.0 0.0 0.0 10.152487
0.183260 296.531985 69.480298 0.0 0.0 0.0 14.888635
0.235619 306.567217 96.155769 0.0 0.0 0.0 6.787466
... ... ... ... ... ... ...
6.047566 281.121502 4.291931 0.0 0.0 0.0 110.517232
6.099926 296.058553 9.868618 0.0 0.0 0.0 59.211711
6.152286 309.585631 19.860210 0.0 0.0 0.0 81.777336
6.204645 309.762293 25.610268 0.0 0.0 0.0 36.586098
6.257005 310.649777 34.654158 0.0 0.0 0.0 44.555347
[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. , 0. , 0. , 3.50877193],
[0. , nan, nan, nan, 1.13636364],
[2.5 , nan, nan, nan, 0. ],
[0. , nan, nan, nan, 2.27272727],
[3.57142857, 2.22222222, 0. , 1.13636364, 1.75438596]]),
1: array([[3.57142857, 1.2345679 , 0. , 1.12359551, 1.75438596],
[2.22222222, nan, nan, nan, 1.13636364],
[2.5 , nan, nan, nan, 0. ],
[2.27272727, nan, nan, nan, 3.40909091],
[3.57142857, 0. , 0. , 2.27272727, 1.75438596]]),
2: array([[ 3.57142857, 1.2345679 , 1.25 , 2.24719101, 3.50877193],
[ 0. , nan, nan, nan, 0. ],
[10. , nan, nan, nan, 3.7037037 ],
[ 2.27272727, nan, nan, nan, 0. ],
[ 3.57142857, 2.22222222, 1.63934426, 1.13636364, 1.75438596]])}
/home/runner/.local/lib/python3.12/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
---------- -------- --------
2.20201 -0.5885 0.8085
4.83117 0.11734 -0.99309
5.40851 0.64239 -0.76638
5.8328 0.89906 -0.43783
6.6736 0.92612 0.37724
7.06295 0.71315 0.70101
7.42538 0.41139 0.91146
7.62195 0.23185 0.97275
8.51432 -0.60997 0.79243
8.76613 -0.79318 0.60898
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 0.927223 -0.051251 0.042653
0.078540 0.981032 -0.023422 -0.083232
0.130900 0.944502 -0.030540 -0.015952
0.183260 0.940489 -0.057758 -0.097482
0.235619 0.832480 0.067899 0.042822
... ... ... ...
6.047566 0.834246 -0.024526 0.037760
6.099926 0.977411 -0.046838 0.109794
6.152286 0.852248 0.055793 -0.037583
6.204645 1.006875 -0.071812 0.018840
6.257005 0.870494 -0.059117 -0.061971
[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.0330075 , -0.01211052, 0.06786628, -0.02696683, 0.01825037],
[ 0.03435193, nan, nan, nan, 0.05395736],
[-0.06072802, nan, nan, nan, 0.0340578 ],
[ 0.00671532, nan, nan, nan, 0.01259036],
[-0.01110221, -0.0409854 , 0.06266782, -0.09247582, -0.00876581]]), 1: array([[-0.04736135, -0.03455984, 0.07903764, 0.01173166, 0.03890872],
[-0.01587163, nan, nan, nan, 0.09664332],
[-0.06392205, nan, nan, nan, -0.05396879],
[-0.08308143, nan, nan, nan, 0.04777149],
[ 0.11493511, -0.10190978, -0.03834621, -0.02497279, -0.03046485]])}
/home/runner/.local/lib/python3.12/site-packages/numpy/_core/fromnumeric.py:3904: RuntimeWarning: Mean of empty slice.
return _methods._mean(a, axis=axis, dtype=dtype,
/home/runner/.local/lib/python3.12/site-packages/numpy/_core/_methods.py:139: 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()
