Introduction to pynapple#
The goal of this tutorial is to quickly learn enough about pynapple to get started with data analysis. This tutorial assumes familiarity with the basics functionalities of numpy.
You can check how to install pynapple here.
Important
By default, pynapple will assume a time units in seconds when passing timestamps array or time parameters such as bin size (unless specified with the time_units
argument)
Importing pynapple#
The convention is to import pynapple with a namespace:
import pynapple as nap
Show code cell content
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
custom_params = {"axes.spines.right": False, "axes.spines.top": False}
sns.set_theme(style="ticks", palette="colorblind", font_scale=1.5, rc=custom_params)
Instantiating pynapple objects#
nap.Tsd
: 1-dimensional time serie#
If you have a 1-dimensional time series, you use the nap.Tsd
object. The arguments t
and d
are the arguments for timestamps and data.
tsd = nap.Tsd(t=np.arange(100), d=np.random.rand(100))
print(tsd)
Time (s)
---------- ---------
0.0 0.787317
1.0 0.626252
2.0 0.725629
3.0 0.246867
4.0 0.166072
5.0 0.0990362
6.0 0.218081
...
93.0 0.864106
94.0 0.7525
95.0 0.74245
96.0 0.836141
97.0 0.303721
98.0 0.816026
99.0 0.295663
dtype: float64, shape: (100,)
nap.TsdFrame
: 2-dimensional time series#
If you have a 2-dimensional time series, you use the nap.TsdFrame
object. The arguments t
and d
are the arguments for timestamps and data. You can add the argument columns
to label each columns.
tsdframe = nap.TsdFrame(
t=np.arange(100), d=np.random.rand(100, 3), columns=["a", "b", "c"]
)
print(tsdframe)
Time (s) a b c
---------- ------- ------- -------
0.0 0.51685 0.47093 0.71099
1.0 0.78874 0.42908 0.21785
2.0 0.59716 0.70813 0.42858
3.0 0.31166 0.41025 0.85901
4.0 0.48602 0.15773 0.8736
5.0 0.51764 0.1497 0.501
6.0 0.64059 0.87013 0.92878
... ... ... ...
93.0 0.18437 0.27729 0.53595
94.0 0.87854 0.18794 0.61
95.0 0.60944 0.25596 0.0237
96.0 0.64157 0.6688 0.69801
97.0 0.7194 0.67419 0.94062
98.0 0.94303 0.89275 0.47146
99.0 0.94466 0.46369 0.11867
dtype: float64, shape: (100, 3)
nap.TsdTensor
: n-dimensionals time series#
If you have larger than 2 dimensions time series (typically movies), you use the nap.TsdTensor
object . The arguments t
and d
are the arguments for timestamps and data.
tsdtensor = nap.TsdTensor(
t=np.arange(100), d=np.random.rand(100, 3, 4)
)
print(tsdtensor)
Time (s)
---------- -----------------------------
0.0 [[0.17442 ... 0.376123] ...]
1.0 [[0.148637 ... 0.195937] ...]
2.0 [[0.316655 ... 0.667776] ...]
3.0 [[0.909602 ... 0.771974] ...]
4.0 [[0.332214 ... 0.878352] ...]
5.0 [[0.064537 ... 0.604505] ...]
6.0 [[0.681991 ... 0.726183] ...]
...
93.0 [[0.932137 ... 0.417608] ...]
94.0 [[0.476354 ... 0.711229] ...]
95.0 [[0.60655 ... 0.915432] ...]
96.0 [[0.265446 ... 0.079151] ...]
97.0 [[0.996566 ... 0.159479] ...]
98.0 [[0.080024 ... 0.338885] ...]
99.0 [[0.697716 ... 0.308827] ...]
dtype: float64, shape: (100, 3, 4)
nap.IntervalSet
: intervals#
The IntervalSet
object stores multiple epochs with a common time unit in a table format. The epochs are strictly non-overlapping. Both start
and end
arguments are necessary.
epochs = nap.IntervalSet(start=[0, 10], end=[5, 15])
print(epochs)
index start end
0 0 5
1 10 15
shape: (2, 2), time unit: sec.
nap.Ts
: timestamps#
Ts
object stores timestamps data (typically spike times or reward times). The argument t
for timestamps is necessary.
ts = nap.Ts(t=np.sort(np.random.uniform(0, 100, 10)))
print(ts)
Time (s)
0.117598086
22.147076159
35.338396644
46.424335061
53.134182614
60.478569047
60.64238112
89.965188132
93.798755334
94.262909674
shape: 10
nap.TsGroup
: group of timestamps#
TsGroup
is a dictionnary that stores multiple time series with different time stamps (.i.e. a group of neurons with different spike times from one session). The first argument data
can be a dictionnary of Ts
, Tsd
or numpy 1d array.
data = {
0: nap.Ts(t=np.sort(np.random.uniform(0, 100, 1000))),
1: nap.Ts(t=np.sort(np.random.uniform(0, 100, 2000))),
2: nap.Ts(t=np.sort(np.random.uniform(0, 100, 3000))),
}
tsgroup = nap.TsGroup(data)
print(tsgroup, "\n")
Index rate
------- -------
0 10.0009
1 20.0018
2 30.0027
Interaction between pynapple objects#
Time support : attribute of time series#
A key feature of how pynapple manipulates time series is an inherent time support object defined for Ts
, Tsd
, TsdFrame
and TsGroup
objects. The time support object is defined as an IntervalSet
that provides the time serie with a context. For example, the restrict operation will automatically update the time support object for the new time series. Ideally, the time support object should be defined for all time series when instantiating them. If no time series is given, the time support is inferred from the start and end of the time series.
In this example, a Tsd
is instantiated with and without a time support of intervals 0 to 5 seconds. Notice how the shape of the Tsd
varies.
time_support = nap.IntervalSet(start=0, end=2)
print(time_support)
index start end
0 0 2
shape: (1, 2), time unit: sec.
Without time support :
print(nap.Tsd(t=[0, 1, 2, 3, 4], d=[0, 1, 2, 3, 4]))
Time (s)
---------- --
0 0
1 1
2 2
3 3
4 4
dtype: int64, shape: (5,)
With time support :
print(
nap.Tsd(
t=[0, 1, 2, 3, 4], d=[0, 1, 2, 3, 4],
time_support = time_support
)
)
Time (s)
---------- --
0 0
1 1
2 2
dtype: int64, shape: (3,)
The time support object has become an attribute of the time series. Depending on the operation applied to the time series, it will be updated.
tsd = nap.Tsd(
t=np.arange(10), d=np.random.randn(10),
time_support = time_support
)
print(tsd.time_support)
index start end
0 0 2
shape: (1, 2), time unit: sec.
Restricting time series to epochs#
The central function of pynapple is the restrict
method of Ts
, Tsd
, TsdFrame
and TsGroup
. The argument is an IntervalSet
object. Only time points within the intervals of the IntervalSet
object are returned. The time support of the time series is updated accordingly.
tsd = nap.Tsd(t=np.arange(10), d=np.random.randn(10))
ep = nap.IntervalSet(start=[0, 7], end=[3.5, 12.4])
print(ep)
index start end
0 0 3.5
1 7 12.4
shape: (2, 2), time unit: sec.
From :
print(tsd)
Time (s)
---------- -----------
0 0.530704
1 0.00562868
2 -0.0104584
3 0.295738
4 -1.98688
5 0.176271
6 2.98987
7 -0.798552
8 -0.00314753
9 -2.80976
dtype: float64, shape: (10,)
to :
new_tsd = tsd.restrict(ep)
print(new_tsd)
Time (s)
---------- -----------
0 0.530704
1 0.00562868
2 -0.0104584
3 0.295738
7 -0.798552
8 -0.00314753
9 -2.80976
dtype: float64, shape: (7,)
Numpy & pynapple#
Pynapple relies on numpy to store the data. Pynapple objects behave very similarly to numpy and numpy functions can be applied directly
tsdtensor = nap.TsdTensor(t=np.arange(100), d=np.random.rand(100, 3, 4))
If a numpy function preserves the time axis, a pynapple object is returned.
In this example, averaging a TsdTensor
along the second dimension returns a TsdFrame
:
print(
np.mean(tsdtensor, 1)
)
Time (s) 0 1 2 3
---------- ------- ------- ------- -------
0.0 0.62657 0.44319 0.63395 0.32428
1.0 0.50899 0.26164 0.56047 0.56699
2.0 0.23501 0.53698 0.58703 0.78813
3.0 0.69693 0.66846 0.33253 0.33756
4.0 0.36762 0.76685 0.65614 0.46954
5.0 0.32268 0.45354 0.4521 0.60153
6.0 0.5978 0.85769 0.40341 0.55558
... ... ... ... ...
93.0 0.63614 0.15276 0.28612 0.2748
94.0 0.24955 0.37172 0.43635 0.27844
95.0 0.60258 0.72558 0.60812 0.4015
96.0 0.75899 0.59683 0.75653 0.49547
97.0 0.56619 0.58056 0.1566 0.72015
98.0 0.44142 0.624 0.2811 0.68922
99.0 0.76199 0.83967 0.32597 0.58067
dtype: float64, shape: (100, 4)
Averaging along the time axis will return a numpy array object:
print(
np.mean(tsdtensor, 0)
)
[[0.50487152 0.52418152 0.51804437 0.46061806]
[0.48638238 0.50953479 0.4855246 0.52121712]
[0.48293323 0.55466866 0.52132184 0.48299307]]
Slicing objects#
Slicing time series and intervals#
Like numpy array#
Ts
, Tsd
, TsdFrame
, TsdTensor
and IntervalSet
can be sliced similar to numpy array:
tsdframe = nap.TsdFrame(t=np.arange(10)/10, d=np.random.randn(10,4))
print(tsdframe)
Time (s) 0 1 2 3
---------- -------- -------- -------- --------
0 -1.85868 1.5643 0.9748 0.64646
0.1 -0.16701 0.36965 -0.83144 -1.4139
0.2 0.93942 0.33838 0.26002 1.1505
0.3 -0.04458 -1.02764 -0.15891 0.78925
0.4 0.322 -0.78266 -0.8248 1.65738
0.5 -0.96615 -1.28187 1.37883 -1.5937
0.6 -0.21013 0.41958 -1.58897 -2.05812
0.7 0.6131 -1.18742 -0.33517 -0.21555
0.8 -1.75023 0.31872 0.95131 -0.75299
0.9 -0.18534 -1.00566 -2.88107 -1.35075
dtype: float64, shape: (10, 4)
print(tsdframe[4:7])
Time (s) 0 1 2 3
---------- -------- -------- -------- --------
0.4 0.322 -0.78266 -0.8248 1.65738
0.5 -0.96615 -1.28187 1.37883 -1.5937
0.6 -0.21013 0.41958 -1.58897 -2.05812
dtype: float64, shape: (3, 4)
print(tsdframe[:,0])
Time (s)
---------- ----------
0 -1.85868
0.1 -0.167013
0.2 0.939423
0.3 -0.0445778
0.4 0.322002
0.5 -0.966148
0.6 -0.210131
0.7 0.6131
0.8 -1.75023
0.9 -0.185343
dtype: float64, shape: (10,)
ep = nap.IntervalSet(start=[0, 10, 20], end=[4, 15, 25])
print(ep)
index start end
0 0 4
1 10 15
2 20 25
shape: (3, 2), time unit: sec.
print(ep[0:2])
index start end
0 0 4
1 10 15
shape: (2, 2), time unit: sec.
print(ep[1])
index start end
0 10 15
shape: (1, 2), time unit: sec.
Like pandas DataFrame#
Important
This page references all the way to slice TsdFrame
TsdFrame
can be sliced like pandas DataFrame when the columns have been labelled with strings :
tsdframe = nap.TsdFrame(t=np.arange(10), d=np.random.randn(10,3), columns=['a', 'b', 'c'])
print(tsdframe['a'])
Time (s)
---------- ----------
0 -0.357325
1 1.49216
2 -1.16998
3 1.82958
4 1.0915
5 0.130118
6 0.640777
7 -1.2818
8 -0.496415
9 -0.0408864
dtype: float64, shape: (10,)
but integer-indexing only works like numpy if a list of integers is used to label columns :
tsdframe = nap.TsdFrame(t=np.arange(4), d=np.random.randn(4,3), columns=[3, 2, 1])
print(tsdframe, "\n")
print(tsdframe[3])
Time (s) 3 2 1
---------- -------- -------- -------
0 0.21406 -0.15187 0.1365
1 0.63149 -1.38505 0.75179
2 1.09133 0.59002 0.44767
3 -0.73867 -0.28893 0.242
dtype: float64, shape: (4, 3)
[-0.73866505 -0.28892672 0.2419972 ]
The loc
method can be used to slice column-based only :
print(tsdframe.loc[3])
Slicing TsGroup#
TsGroup
object can be indexed to return directly the timestamp object or sliced to return a new TsGroup
.
Indexing :
print(tsgroup[0], "\n")
Time (s)
0.135866548
0.161328797
0.486745531
0.606808485
0.667487346
0.718369939
0.798959722
...
99.436028418
99.650481845
99.683281103
99.703285082
99.843818368
99.932756303
99.979426264
shape: 1000
Slicing :
print(tsgroup[[0, 2]])
Index rate
------- -------
0 10.0009
2 30.0027
Core functions#
Objects have methods that can help transform and refine time series. This is a non exhaustive list.
Binning : counting events#
Time series objects have the count
method that count the number of timestamps. This is typically used when counting number of spikes within a particular bin over multiple intervals. The returned object is a Tsd
or TsdFrame
with the timestamps being the center of the bins.
count = tsgroup.count(1)
print(count)
Time (s) 0 1 2
------------ --- --- ---
0.500086828 10 21 36
1.500086828 12 20 24
2.500086828 9 23 12
3.500086828 9 18 39
4.500086828 14 18 20
5.500086828 3 17 23
6.500086828 7 26 34
... ... ... ...
93.500086828 15 18 26
94.500086828 13 13 26
95.500086828 11 16 25
96.500086828 12 19 29
97.500086828 7 21 26
98.500086828 8 25 26
99.500086828 11 23 25
dtype: int64, shape: (100, 3)
Thresholding#
Some time series have specific methods. The threshold
method of Tsd
returns a new Tsd
with all the data above or below a given value.
tsd = nap.Tsd(t=np.arange(10), d=np.random.rand(10))
print(tsd)
print(tsd.threshold(0.5))
Time (s)
---------- --------
0 0.694509
1 0.131665
2 0.551927
3 0.293833
4 0.501712
5 0.898976
6 0.670509
7 0.209272
8 0.652607
9 0.269692
dtype: float64, shape: (10,)
Time (s)
---------- --------
0 0.694509
2 0.551927
4 0.501712
5 0.898976
6 0.670509
8 0.652607
dtype: float64, shape: (6,)
An important aspect of the tresholding is that the time support get updated based on the time points remaining. To get the epochs above/below a certain threshold, you can access the time support of the returned object.
print(tsd.time_support)
print(tsd.threshold(0.5, "below").time_support)
index start end
0 0 9
shape: (1, 2), time unit: sec.
index start end
0 0.5 1.5
1 2.5 3.5
2 6.5 7.5
3 8.5 9
shape: (4, 2), time unit: sec.
Time-bin averaging of data#
Many analyses requires to bring time series to the same rates and same dimensions. A quick way to downsample a time series to match in size for example a count array is to bin average. The bin_average
method takes a bin size in unit of time.
tsdframe = nap.TsdFrame(t=np.arange(0, 100)/10, d=np.random.randn(100,3))
print(tsdframe)
Time (s) 0 1 2
---------- -------- -------- --------
0.0 1.43247 0.40745 -0.99639
0.1 1.56087 -0.1918 -0.46572
0.2 -1.15256 0.73285 -0.68566
0.3 1.81508 0.64316 -1.60723
0.4 0.6814 0.86057 0.65339
0.5 -1.15944 0.63739 0.44699
0.6 -0.71868 -1.02563 -0.4489
... ... ... ...
9.3 0.05683 0.19529 1.14955
9.4 -0.17604 2.34177 1.09624
9.5 0.31812 0.47713 0.5773
9.6 -1.15992 -0.5747 0.80213
9.7 -0.22 1.82475 0.9023
9.8 1.44871 1.08258 0.09255
9.9 0.20472 1.72384 -0.75568
dtype: float64, shape: (100, 3)
Here we go from a timepoint every 100ms to a timepoint every second.
print(tsdframe.bin_average(1))
Time (s) 0 1 2
---------- -------- -------- --------
0.5 -0.0321 0.29837 -0.37349
1.5 0.22519 0.55282 0.56284
2.5 -0.18571 0.19384 -0.64622
3.5 -0.11154 0.03159 -0.4276
4.5 0.4213 -0.03227 0.06737
5.5 -0.25777 -0.05746 0.41794
6.5 0.14389 -0.1931 -0.19348
7.5 0.08173 -0.59836 -0.11789
8.5 -0.16846 0.06979 0.03938
9.5 0.25632 0.6424 0.31869
dtype: float64, shape: (10, 3)
Loading data#
See here for more details about loading data.
Loading NWB#
Pynapple supports by default the NWB standard.
NWB files can be loaded with :
nwb = nap.load_file("path/to/my.nwb")
or directly with the NWBFile
class:
nwb = nap.NWBFile("path/to/my.nwb")
print(nwb)
my.nwb
┍━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┑
│ Keys │ Type │
┝━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━┥
│ units │ TsGroup │
┕━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┙
The returned object behaves like a dictionnary. The first column indicates the keys. The second column indicate the object type.
print(nwb['units'])
Index rate location group
------- ------ ---------- -------
0 1.0 brain 0
1 1.0 brain 0
2 1.0 brain 0
Overview of advanced analysis#
The process
module of pynapple contains submodules that group methods that can be applied for high level analysis. All of the method are directly available from the nap
namespace.
Important
Some functions have been doubled given the nature of the data. For instance, computing a 1d tuning curves from spiking activity requires the nap.compute_1d_tuning_curves
. The same function for calcium imaging data which is a continuous time series is available with nap.compute_1d_tuning_curves_continuous
.
This module computes correlograms of discrete events, for example the cross-correlograms of a population of neurons.
The decoding module perfoms bayesian decoding given a set of tuning curves and a TsGroup
.
Bandpass, lowpass, highpass or bandstop filtering can be done to any time series using either Butterworth filter or windowed-sinc convolution.
The perievent module has a set of functions to center time series and timestamps data around a particular events.
The randomize module holds multiple technique to shuffle timestamps in order to create surrogate datasets.
The spectrum module contains the methods to return the (mean) power spectral density of a time series.
Tuning curves of neurons based on spiking or calcium activity can be computed.
The wavelets module performs Morlet wavelets decomposition of a time series.
This module provides methods for building trial-based tensors and time-warped trial-based tensors.