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

Hide 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 series#

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.0893789
1.0         0.130692
2.0         0.224117
3.0         0.728546
4.0         0.701626
5.0         0.595851
6.0         0.706831
...
93.0        0.610272
94.0        0.232388
95.0        0.723742
96.0        0.126214
97.0        0.637661
98.0        0.358237
99.0        0.143849
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.184137   0.0204201  0.339815
1.0         0.388457   0.250603   0.0816699
2.0         0.127827   0.223713   0.546072
3.0         0.425576   0.802484   0.784805
4.0         0.378513   0.848315   0.653483
5.0         0.817808   0.314032   0.39146
6.0         0.0567891  0.390099   0.440056
...
93.0        0.57734    0.943113   0.0764645
94.0        0.614283   0.175386   0.417993
95.0        0.0521353  0.370572   0.262489
96.0        0.471435   0.858317   0.850212
97.0        0.0149275  0.734364   0.379428
98.0        0.747712   0.107949   0.673644
99.0        0.363297   0.854296   0.488558
dtype: float64, shape: (100, 3)

nap.TsdTensor: n-dimensional 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.483161 ... 0.05736 ] ...]
1.0         [[0.946553 ... 0.857714] ...]
2.0         [[0.03466  ... 0.260169] ...]
3.0         [[0.673934 ... 0.8228  ] ...]
4.0         [[0.56499 ... 0.01466] ...]
5.0         [[0.583806 ... 0.563794] ...]
6.0         [[0.962699 ... 0.104387] ...]
...
93.0        [[0.94408  ... 0.747116] ...]
94.0        [[0.506442 ... 0.941937] ...]
95.0        [[0.34919  ... 0.738882] ...]
96.0        [[0.423621 ... 0.473585] ...]
97.0        [[0.509134 ... 0.388171] ...]
98.0        [[0.333499 ... 0.735796] ...]
99.0        [[0.678567 ... 0.489606] ...]
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#

The 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)
2.955595365
3.465813563
15.84073506
18.908129302
33.096320271
35.949970544
53.127823551
55.74392627
68.227514814
72.153943305
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.0045
      1  20.0091
      2  30.0136 

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.434704
1            0.653997
2           -1.44673
3           -0.730032
4            0.624895
5           -2.49052
6            1.26413
7           -0.451341
8            0.699923
9           -0.849988
dtype: float64, shape: (10,)

to :

new_tsd = tsd.restrict(ep)

print(new_tsd)
Time (s)
----------  ---------
0           -0.434704
1            0.653997
2           -1.44673
3           -0.730032
7           -0.451341
8            0.699923
9           -0.849988
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.7102    0.472807   0.69287   0.149484
1.0         0.682359  0.573472   0.434043  0.470838
2.0         0.441186  0.473458   0.30439   0.472311
3.0         0.419496  0.441449   0.657698  0.628918
4.0         0.536409  0.330603   0.419749  0.51523
5.0         0.314305  0.330107   0.526562  0.377941
6.0         0.483521  0.338551   0.292126  0.48965
...
93.0        0.486664  0.575428   0.721632  0.561119
94.0        0.559806  0.785284   0.580303  0.588849
95.0        0.528555  0.0745228  0.818734  0.577539
96.0        0.78712   0.618035   0.406237  0.621819
97.0        0.409317  0.389361   0.374367  0.688315
98.0        0.23397   0.481374   0.443451  0.577793
99.0        0.591853  0.512419   0.497807  0.273194
dtype: float64, shape: (100, 4)

Averaging along the time axis will return a numpy array object:

print(
    np.mean(tsdtensor, 0)
    )
[[0.50730604 0.45300017 0.52655023 0.54475097]
 [0.50728703 0.55325384 0.49868246 0.55354647]
 [0.53100072 0.47206239 0.51884586 0.48309384]]

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.19531   -0.654594   0.484215   2.47121
0.1          0.264905   0.777814  -1.37379    0.379893
0.2         -0.337285  -1.12022   -0.861719  -0.762151
0.3          0.428158  -0.832944   0.528135  -0.793926
0.4         -0.407982  -0.263438   1.83297   -0.836946
0.5         -0.139909  -1.22952   -0.38496    1.22771
0.6         -1.84924   -0.133612  -0.978535   0.620001
0.7          0.578198  -0.863096   1.21575   -1.65618
0.8          1.19592    0.639959   0.701857   0.349767
0.9          0.479747  -1.46155    1.26756    0.209625
dtype: float64, shape: (10, 4)
print(tsdframe[4:7])
Time (s)            0          1          2          3
----------  ---------  ---------  ---------  ---------
0.4         -0.407982  -0.263438   1.83297   -0.836946
0.5         -0.139909  -1.22952   -0.38496    1.22771
0.6         -1.84924   -0.133612  -0.978535   0.620001
dtype: float64, shape: (3, 4)
print(tsdframe[:,0])
Time (s)
----------  ---------
0            1.19531
0.1          0.264905
0.2         -0.337285
0.3          0.428158
0.4         -0.407982
0.5         -0.139909
0.6         -1.84924
0.7          0.578198
0.8          1.19592
0.9          0.479747
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           -1.38097
1            0.839049
2            0.335367
3           -0.865896
4           -0.0548296
5            1.18124
6            0.883253
7           -0.172648
8           -1.03296
9           -0.384483
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            1.75204     1.3432    1.7389
1            0.0650296  -0.266358  1.62797
2            1.59663    -0.403977  1.4336
3           -0.633762    1.62029   1.00465
dtype: float64, shape: (4, 3) 

[-0.63376177  1.62028825  1.00465486]

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.007364941
0.109168043
0.143357221
0.38952221
0.393523625
0.572389746
0.597404149
...
99.573386406
99.637913419
99.717678977
99.724810712
99.778379751
99.782386567
99.803054982
shape: 1000 

Slicing:

print(tsgroup[[0, 2]])
  Index     rate
-------  -------
      0  10.0045
      2  30.0136

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.507364941    10   17   37
1.507364941    12   24   23
2.507364941    12   24   38
3.507364941     9   15   29
4.507364941     7   24   21
5.507364941    12   35   29
6.507364941     8   22   37
...
93.507364941    8   24   31
94.507364941    4   17   23
95.507364941   15   19   22
96.507364941    2   16   37
97.507364941    8   17   31
98.507364941    9   18   34
99.507364941   10   14   29
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.365383
1           0.713409
2           0.010881
3           0.964423
4           0.214489
5           0.333003
6           0.0554724
7           0.88515
8           0.61843
9           0.9494
dtype: float64, shape: (10,)
Time (s)
----------  --------
1           0.713409
3           0.964423
7           0.88515
8           0.61843
9           0.9494
dtype: float64, shape: (5,)

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      0.5
      1      1.5    2.5
      2      3.5    6.5
shape: (3, 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.62707    -0.723447   0.981741
0.1         -1.03576     0.199773  -1.88803
0.2          1.74036    -0.361826   0.0110863
0.3          0.356622    2.54947    0.242194
0.4         -0.350537    0.714799   1.16195
0.5         -0.0157375   0.922273   0.92116
0.6          0.760248   -0.178507  -0.0211465
...
9.3         -0.756017   -0.691075   0.7184
9.4         -0.214467   -0.8797    -0.143472
9.5          1.97618     1.25533   -0.758067
9.6          0.135882    0.482744   1.0251
9.7         -0.440367    1.22277   -0.54112
9.8          1.06654     0.278583   0.902382
9.9          0.0368128   1.16674   -0.514017
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.0367525   0.176465     0.253507
1.5          0.218624    0.00370841  -0.0455926
2.5          0.131563   -0.0371094    0.35925
3.5         -0.603515    0.397077     0.686371
4.5         -0.13297    -0.473542     0.0694941
5.5         -0.155591    0.679214     0.152188
6.5         -0.208553    0.151156     0.27338
7.5          0.0601465   0.272752     0.679174
8.5          0.275148   -0.148428     0.147613
9.5          0.193371    0.0847044    0.16609
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.

Discrete correlograms & ISI

This module analyses discrete events, specifically correlograms (for example by computing the cross-correlograms of a population of neurons) and interspike interval (ISI) distributions.

Bayesian decoding

The decoding module perfoms bayesian decoding given a set of tuning curves and a TsGroup.

Filtering

Bandpass, lowpass, highpass or bandstop filtering can be done to any time series using either Butterworth filter or windowed-sinc convolution.

Perievent time histogram

The perievent module has a set of functions to center time series and timestamps data around a particular events.

Randomizing

The randomize module holds multiple technique to shuffle timestamps in order to create surrogate datasets.

Spectrum

The spectrum module contains the methods to return the (mean) power spectral density of a time series.

Tuning curves

Tuning curves of neurons based on spiking or calcium activity can be computed.

Wavelets

The wavelets module performs Morlet wavelets decomposition of a time series.

Warping

This module provides methods for building trial-based tensors and time-warped trial-based tensors.