Skip to content

pychronux

dpsschk(tapers, N, Fs)

Check and generate DPSS tapers.

Parameters:

Name Type Description Default
tapers Union[ndarray, Tuple[float, int]]

Input can be either an array representing [NW, K] or a tuple with the number of tapers and the maximum number of tapers.

required
N int

Number of points for FFT.

required
Fs float

Sampling frequency.

required

Returns:

Name Type Description
tapers ndarray

Tapers matrix, shape [tapers, eigenvalues].

Notes

The function computes DPSS (Discrete Prolate Spheroidal Sequences) tapers and scales them by the square root of the sampling frequency.

Source code in neuro_py/process/pychronux.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def dpsschk(
    tapers: Union[np.ndarray, Tuple[float, int]], N: int, Fs: float
) -> np.ndarray:
    """
    Check and generate DPSS tapers.

    Parameters
    ----------
    tapers : Union[np.ndarray, Tuple[float, int]]
        Input can be either an array representing [NW, K] or a tuple with
        the number of tapers and the maximum number of tapers.
    N : int
        Number of points for FFT.
    Fs : float
        Sampling frequency.

    Returns
    -------
    tapers : np.ndarray
        Tapers matrix, shape [tapers, eigenvalues].

    Notes
    -----
    The function computes DPSS (Discrete Prolate Spheroidal Sequences) tapers
    and scales them by the square root of the sampling frequency.
    """
    tapers, eigs = dpss(N, NW=tapers[0], Kmax=tapers[1], sym=False, return_ratios=True)
    tapers = tapers * np.sqrt(Fs)
    tapers = tapers.T
    return tapers

get_tapers(N, bandwidth, *, fs=1.0, min_lambda=0.95, n_tapers=None)

Compute tapers and associated energy concentrations for the Thomson multitaper method.

Parameters:

Name Type Description Default
N int

Length of taper.

required
bandwidth float

Bandwidth of taper, in Hz.

required
fs float

Sampling rate, in Hz. Default is 1 Hz.

1.0
min_lambda float

Minimum energy concentration that each taper must satisfy. Default is 0.95.

0.95
n_tapers Optional[int]

Number of tapers to compute. Default is to use all tapers that satisfy 'min_lambda'.

None

Returns:

Name Type Description
tapers ndarray

Array of tapers with shape (n_tapers, N).

lambdas ndarray

Energy concentrations for each taper with shape (n_tapers,).

Raises:

Type Description
ValueError

If not enough tapers are available or if none of the tapers satisfy the minimum energy concentration criteria.

Source code in neuro_py/process/pychronux.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def get_tapers(
    N: int,
    bandwidth: float,
    *,
    fs: float = 1.0,
    min_lambda: float = 0.95,
    n_tapers: Optional[int] = None,
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Compute tapers and associated energy concentrations for the Thomson
    multitaper method.

    Parameters
    ----------
    N : int
        Length of taper.
    bandwidth : float
        Bandwidth of taper, in Hz.
    fs : float, optional
        Sampling rate, in Hz. Default is 1 Hz.
    min_lambda : float, optional
        Minimum energy concentration that each taper must satisfy. Default is 0.95.
    n_tapers : Optional[int], optional
        Number of tapers to compute. Default is to use all tapers that satisfy 'min_lambda'.

    Returns
    -------
    tapers : np.ndarray
        Array of tapers with shape (n_tapers, N).
    lambdas : np.ndarray
        Energy concentrations for each taper with shape (n_tapers,).

    Raises
    ------
    ValueError
        If not enough tapers are available or if none of the tapers satisfy the
        minimum energy concentration criteria.
    """

    NW = bandwidth * N / fs
    K = int(np.ceil(2 * NW)) - 1
    if n_tapers is not None:
        K = min(K, n_tapers)
    if K < 1:
        raise ValueError(
            f"Not enough tapers, with 'NW' of {NW}. Increase the bandwidth or "
            "use more data points"
        )

    tapers, lambdas = dpss(N, NW=NW, Kmax=K, sym=False, norm=2, return_ratios=True)

    tapers, lambdas = dpss(N, NW=NW, Kmax=K, sym=False, norm=2, return_ratios=True)
    mask = lambdas > min_lambda
    if not np.sum(mask) > 0:
        raise ValueError(
            "None of the tapers satisfied the minimum energy concentration"
            f" criteria of {min_lambda}"
        )
    tapers = tapers[mask]
    lambdas = lambdas[mask]

    if n_tapers is not None:
        if n_tapers > tapers.shape[0]:
            raise ValueError(
                f"'n_tapers' of {n_tapers} is greater than the {tapers.shape[0]}"
                f" that satisfied the minimum energy concentration criteria of {min_lambda}"
            )
        tapers = tapers[:n_tapers]
        lambdas = lambdas[:n_tapers]

    return tapers, lambdas

getfgrid(Fs, nfft, fpass)

Get frequency grid for evaluation.

Parameters:

Name Type Description Default
Fs int

Sampling frequency.

required
nfft int

Number of points for FFT.

required
fpass List[float]

Frequency range to evaluate (as [fmin, fmax]).

required

Returns:

Name Type Description
f ndarray

Frequency vector within the specified range.

findx ndarray

Boolean array indicating the indices of the frequency vector that fall within the specified range.

Notes

The frequency vector is computed based on the sampling frequency and the number of FFT points. Only frequencies within the range defined by fpass are returned.

Source code in neuro_py/process/pychronux.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def getfgrid(Fs: int, nfft: int, fpass: List[float]) -> Tuple[np.ndarray, np.ndarray]:
    """
    Get frequency grid for evaluation.

    Parameters
    ----------
    Fs : int
        Sampling frequency.
    nfft : int
        Number of points for FFT.
    fpass : List[float]
        Frequency range to evaluate (as [fmin, fmax]).

    Returns
    -------
    f : np.ndarray
        Frequency vector within the specified range.
    findx : np.ndarray
        Boolean array indicating the indices of the frequency vector that fall within the specified range.

    Notes
    -----
    The frequency vector is computed based on the sampling frequency and the number of FFT points.
    Only frequencies within the range defined by `fpass` are returned.
    """
    df = Fs / nfft
    f = np.arange(0, Fs + df, df)
    f = f[0:nfft]
    # findx = np.logical_and(f >= fpass[0], f <= fpass[-1])
    findx = (f >= fpass[0]) & (f <= fpass[-1])
    f = f[findx]
    return f, findx

mtfftc(data, tapers, nfft, Fs)

Multitaper FFT for continuous data.

Parameters:

Name Type Description Default
data ndarray

1D array of continuous data (e.g., LFP).

required
tapers ndarray

Tapers array with shape [NW, K] or [tapers, eigenvalues].

required
nfft int

Number of points for FFT.

required
Fs int

Sampling frequency.

required

Returns:

Name Type Description
J ndarray

FFT of the data with shape (nfft, K).

Raises:

Type Description
AssertionError

If the length of tapers is incompatible with the length of data.

Source code in neuro_py/process/pychronux.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def mtfftc(data: np.ndarray, tapers: np.ndarray, nfft: int, Fs: int) -> np.ndarray:
    """
    Multitaper FFT for continuous data.

    Parameters
    ----------
    data : np.ndarray
        1D array of continuous data (e.g., LFP).
    tapers : np.ndarray
        Tapers array with shape [NW, K] or [tapers, eigenvalues].
    nfft : int
        Number of points for FFT.
    Fs : int
        Sampling frequency.

    Returns
    -------
    J : np.ndarray
        FFT of the data with shape (nfft, K).

    Raises
    ------
    AssertionError
        If the length of tapers is incompatible with the length of data.
    """
    NC = len(data)
    NK, K = tapers.shape
    assert NK == NC, "length of tapers is incompatible with length of data"
    tmp = np.repeat(np.atleast_2d(data), K, 0).T
    tmp2 = tmp * tapers
    J = np.fft.fft(tmp2.T, nfft) / float(Fs)
    return J

mtfftpt(data, tapers, nfft, t, f, findx)

Multitaper FFT for point process times.

Parameters:

Name Type Description Default
data ndarray

1D array of spike times (in seconds).

required
tapers ndarray

Tapers from the DPSS method.

required
nfft int

Number of points for FFT.

required
t ndarray

Time vector.

required
f ndarray

Frequency vector.

required
findx list of bool

Frequency index.

required

Returns:

Name Type Description
J ndarray

FFT of the data.

Msp float

Mean spikes per time.

Nsp float

Total number of spikes in data.

Notes

The function computes the multitaper FFT of spike times using the specified tapers and returns the FFT result, mean spikes, and total spike count.

Source code in neuro_py/process/pychronux.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def mtfftpt(
    data: np.ndarray,
    tapers: np.ndarray,
    nfft: int,
    t: np.ndarray,
    f: np.ndarray,
    findx: List[bool],
) -> Tuple[np.ndarray, float, float]:
    """
    Multitaper FFT for point process times.

    Parameters
    ----------
    data : np.ndarray
        1D array of spike times (in seconds).
    tapers : np.ndarray
        Tapers from the DPSS method.
    nfft : int
        Number of points for FFT.
    t : np.ndarray
        Time vector.
    f : np.ndarray
        Frequency vector.
    findx : list of bool
        Frequency index.

    Returns
    -------
    J : np.ndarray
        FFT of the data.
    Msp : float
        Mean spikes per time.
    Nsp : float
        Total number of spikes in data.

    Notes
    -----
    The function computes the multitaper FFT of spike times using
    the specified tapers and returns the FFT result, mean spikes,
    and total spike count.
    """
    K = tapers.shape[1]
    nfreq = len(f)
    H = np.zeros((nfft, K), dtype=np.complex128)
    for i in np.arange(K):
        H[:, i] = np.fft.fft(tapers[:, i], nfft, axis=0)

    H = H[findx, :]
    w = 2 * np.pi * f
    dtmp = data
    indx = np.logical_and(dtmp >= np.min(t), dtmp <= np.max(t))
    if len(indx):
        dtmp = dtmp[indx]
    Nsp = len(dtmp)
    Msp = Nsp / len(t)

    if Msp != 0:
        data_proj = np.empty((len(dtmp), K))
        for i in np.arange(K):
            data_proj[:, i] = np.interp(dtmp, t, tapers[:, i])
        exponential = np.exp(np.atleast_2d(-1j * w).T * (dtmp - t[0]))
        J = np.dot(exponential, data_proj) - H * Msp
    else:
        J = np.zeros((nfreq, K))

    return J, Msp, Nsp

mtspectrumc(data, Fs, fpass, tapers)

Compute the multitaper power spectrum for continuous data.

Parameters:

Name Type Description Default
data ndarray

1D array of continuous data (e.g., LFP).

required
Fs int

Sampling frequency in Hz.

required
fpass list

Frequency range to evaluate as [min_freq, max_freq].

required
tapers ndarray

Tapers array with shape [NW, K] or [tapers, eigenvalues].

required

Returns:

Name Type Description
S Series

Power spectrum with frequencies as the index.

Notes

This function utilizes the multitaper method for spectral estimation and returns the power spectrum as a pandas Series.

Source code in neuro_py/process/pychronux.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def mtspectrumc(
    data: np.ndarray, Fs: int, fpass: list, tapers: np.ndarray
) -> pd.Series:
    """
    Compute the multitaper power spectrum for continuous data.

    Parameters
    ----------
    data : np.ndarray
        1D array of continuous data (e.g., LFP).
    Fs : int
        Sampling frequency in Hz.
    fpass : list
        Frequency range to evaluate as [min_freq, max_freq].
    tapers : np.ndarray
        Tapers array with shape [NW, K] or [tapers, eigenvalues].

    Returns
    -------
    S : pd.Series
        Power spectrum with frequencies as the index.

    Notes
    -----
    This function utilizes the multitaper method for spectral estimation
    and returns the power spectrum as a pandas Series.
    """
    N = len(data)
    nfft = np.max(
        [int(2 ** np.ceil(np.log2(N))), N]
    )  # number of points in fft of prolates
    f, findx = getfgrid(Fs, nfft, fpass)
    tapers = dpsschk(tapers, N, Fs)
    J = mtfftc(data, tapers, nfft, Fs)
    J = J.T[findx, :]
    S = np.real(np.mean(np.conj(J) * J, 1))
    return pd.Series(index=f, data=S)

mtspectrumpt(data, Fs, fpass, NW=2.5, n_tapers=4, time_support=None, tapers=None, tapers_ts=None)

Multitaper power spectrum estimation for point process data.

Parameters:

Name Type Description Default
data ndarray

Array of spike times (in seconds).

required
Fs int

Sampling frequency.

required
fpass list of float

Frequency range to evaluate.

required
NW Union[int, float]

Time-bandwidth product (default is 2.5).

2.5
n_tapers int

Number of tapers (default is 4).

4
time_support Union[list, None]

Time range to evaluate (default is None).

None
tapers Union[ndarray, None]

Precomputed tapers, given as [NW, K] or [tapers, eigenvalues] (default is None).

None
tapers_ts Union[ndarray, None]

Taper time series (default is None).

None

Returns:

Type Description
DataFrame

DataFrame containing the power spectrum.

Examples:

>>> spec = pychronux.mtspectrumpt(
>>>    st.data,
>>>    1250,
>>>    [1, 20],
>>>    NW=3,
>>>    n_tapers=5,
>>>    time_support=[st.support.start, st.support.stop],
>>> )
Source code in neuro_py/process/pychronux.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def mtspectrumpt(
    data: np.ndarray,
    Fs: int,
    fpass: list,
    NW: Union[int, float] = 2.5,
    n_tapers: int = 4,
    time_support: Union[list, None] = None,
    tapers: Union[np.ndarray, None] = None,
    tapers_ts: Union[np.ndarray, None] = None,
) -> pd.DataFrame:
    """
    Multitaper power spectrum estimation for point process data.

    Parameters
    ----------
    data : np.ndarray
        Array of spike times (in seconds).
    Fs : int
        Sampling frequency.
    fpass : list of float
        Frequency range to evaluate.
    NW : Union[int, float], optional
        Time-bandwidth product (default is 2.5).
    n_tapers : int, optional
        Number of tapers (default is 4).
    time_support : Union[list, None], optional
        Time range to evaluate (default is None).
    tapers : Union[np.ndarray, None], optional
        Precomputed tapers, given as [NW, K] or [tapers, eigenvalues] (default is None).
    tapers_ts : Union[np.ndarray, None], optional
        Taper time series (default is None).

    Returns
    -------
    pd.DataFrame
        DataFrame containing the power spectrum.


    Examples
    -------
    >>> spec = pychronux.mtspectrumpt(
    >>>    st.data,
    >>>    1250,
    >>>    [1, 20],
    >>>    NW=3,
    >>>    n_tapers=5,
    >>>    time_support=[st.support.start, st.support.stop],
    >>> )
    """
    if time_support is not None:
        mintime, maxtime = time_support
    else:
        mintime = np.min(data)
        maxtime = np.max(data)
    dt = 1 / Fs

    if tapers is None:
        tapers_ts = np.arange(mintime - dt, maxtime + dt, dt)
        N = len(tapers_ts)
        tapers, eigens = dpss(N, NW, n_tapers, return_ratios=True)
        tapers = tapers.T

    N = len(tapers_ts)
    # number of points in fft of prolates
    nfft = np.max([int(2 ** np.ceil(np.log2(N))), N])
    f, findx = getfgrid(Fs, nfft, fpass)

    spec = np.zeros((len(f), len(data)))
    for i, d in enumerate(data):
        J, Msp, Nsp = mtfftpt(d, tapers, nfft, tapers_ts, f, findx)
        spec[:, i] = np.real(np.mean(np.conj(J) * J, 1))

    spectrum_df = pd.DataFrame(index=f, columns=np.arange(len(data)), dtype=np.float64)
    spectrum_df[:] = spec
    return spectrum_df

point_spectra(times, Fs=1250, freq_range=[1, 20], tapers0=[3, 5], pad=0)

Compute point spectra for a set of spike times.

Parameters:

Name Type Description Default
times ndarray

Array of spike times (in seconds).

required
Fs int

Sampling frequency in Hz (default is 1250).

1250
freq_range list

Frequency range to evaluate as [min_freq, max_freq] (default is [1, 20]).

[1, 20]
tapers0 list

Tapers configuration as [NW, K] or [tapers, eigenvalues] (default is [3, 5]).

[3, 5]
pad int

Number of points to pad for FFT (default is 0).

0

Returns:

Name Type Description
spectra ndarray

Power spectrum.

f ndarray

Frequencies corresponding to the power spectrum.

Notes

This function computes the point spectra for spike times using the multitaper method. The power spectrum is returned along with the associated frequencies. By Ryan H, converted from PointSpectra.m by Ralitsa Todorova.

Source code in neuro_py/process/pychronux.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def point_spectra(
    times: np.ndarray,
    Fs: int = 1250,
    freq_range: List[float] = [1, 20],
    tapers0: List[int] = [3, 5],
    pad: int = 0,
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Compute point spectra for a set of spike times.

    Parameters
    ----------
    times : np.ndarray
        Array of spike times (in seconds).
    Fs : int, optional
        Sampling frequency in Hz (default is 1250).
    freq_range : list, optional
        Frequency range to evaluate as [min_freq, max_freq] (default is [1, 20]).
    tapers0 : list, optional
        Tapers configuration as [NW, K] or [tapers, eigenvalues] (default is [3, 5]).
    pad : int, optional
        Number of points to pad for FFT (default is 0).

    Returns
    -------
    spectra : np.ndarray
        Power spectrum.
    f : np.ndarray
        Frequencies corresponding to the power spectrum.

    Notes
    -----
    This function computes the point spectra for spike times using the multitaper method.
    The power spectrum is returned along with the associated frequencies.
    By Ryan H, converted from PointSpectra.m by Ralitsa Todorova.
    """

    timesRange = [min(times), max(times)]
    window = np.floor(np.diff(timesRange))
    nSamplesPerWindow = int(np.round(Fs * window))  # number of samples in window
    nfft = np.max(
        [(int(2 ** np.ceil(np.log2(nSamplesPerWindow))) + pad), nSamplesPerWindow]
    )
    fAll = np.linspace(0, Fs, int(nfft))
    ok = (fAll >= freq_range[0]) & (fAll <= freq_range[1])
    Nf = sum(ok)
    tapers, _ = dpss(nSamplesPerWindow, tapers0[0], tapers0[1], return_ratios=True)
    tapers = tapers * np.sqrt(Fs)
    spectra = np.zeros(Nf)
    H = np.fft.fft(tapers.T, int(nfft), 1)  # fft of tapers
    # restrict fft of tapers to required frequencies
    f = fAll[ok]
    H = H[:, ok]
    w = 2 * np.pi * f  # angular frequencies at which ft is to be evaluated
    timegrid = np.linspace(timesRange[0], timesRange[1], nSamplesPerWindow)

    # make sure times are within the range of timegrid
    data = times[(times >= timegrid[0]) & (times <= timegrid[-1])]
    data_proj = [np.interp(data, timegrid, taper) for taper in tapers.T]
    data_proj = np.vstack(data_proj)
    exponential = np.exp(np.outer(-1j * w, (data - timegrid[0])))
    J = exponential @ data_proj.T - H.T * len(data) / len(timegrid)
    spectra = np.squeeze(np.mean(np.real(np.conj(J) * J), axis=1))
    return spectra, f