API Reference
Main
multitaper_spectrogram(data, fs, time_step, window_length=None, NW=4.0, n_tapers=None, freq_range=None, weight_type='unity', detrend='constant', nfft=None, db_scale=True, p_ref=2e-05, boundary_pad=False)
Compute the multitaper PSD of the input data.
The computation backend (CPU or GPU) is automatically determined by the type of the input arrays (numpy or cupy).
Parameters:
-
data(NDArray) –(..., n_samples) Input data:
- Can be of any shape (including 1d array), as long as the last dimension is the time dimension (n_samples). The spectrogram computation will be applied to the last dimension, and the other dimensions will be treated as batch dimensions and preserved in the output.
- Can be either a numpy array or a cupy array. The backend (CPU or GPU) will be automatically determined based on the type of the input data.
-
fs(float) –Sampling frequency
-
time_step(float) –Time step between frames in seconds
-
window_length(float, default:None) –Window length in seconds. If
None, will be set to the same astime_step. Defaults to None. -
NW(float, default:4.0) –NW value, see notes for details. Defaults to 4.0.
-
n_tapers(Optional[int], default:None) –The max number of tapers, if
None, will be set to NW*2-1. Defaults to None. -
freq_range(Optional[list], default:None) –The desired frequency range. If
None, will be set to [0, fs/2]. Defaults to None. -
weight_type(Literal['unity', 'eig'], default:'unity') –The type of weights among tapers. Defaults to "unity".
-
detrend(Literal['constant', 'linear', 'off'], default:'constant') –Whether and how to detrend the signal. Defaults to "constant".
-
nfft(Optional[int], default:None) –The number of FFT points. If
None, will be set to the smallest power of 2 that is larger than the window length. Defaults to None. -
db_scale(bool, default:True) –Whether convert the result to db scale, i.e. 10log10(psd/p_ref**2). Defaults to True.
-
p_ref(float, default:2e-05) –If
db_scaleisTrue, thep_refvalue used in the dB conversion. Defaults to 2e-5. -
boundary_pad(bool, default:False) –Whether to pad the data with zeros at the beginning and end. This is useful when the data is not evenly divisible by the window length and time step. By default
False.- If
True, the data will be padded with zeros at the beginning and end, so that the first frame is centered on the first sample of data, and all samples are included in (at least) one frame. - If
False, the first frame is centered atwindow_length/2seconds after the first sample, and samples aftern_frames*time_step+window_lengthseconds are ignored.
- If
Notes
The value of 2W is the regularization bandwidth. Typically, we choose W to be a small multiple of the fundamental frequency 1/(Ndt) (where N is the number of samples in the data), i.e. W=i/(Ndt). The value of the parameter NW here is in fact the value of i (when dt is seen as 1). There's a trade-off between frequency resolution and variance reduction: A larger NW will reduce the variance of the PSD estimate, but also reduce the frequency resolution.
Returns:
-
freqs(NDArray) –(n_freqs,) Frequency points of the spectrogram.
-
times(NDArray) –(n_frames,) Time points of each frame.
-
psd(NDArray) –(..., n_freqs, n_frames) PSD spectrogram. The shape of the output PSD is the same as the input data, except that the last dimension (time) is replaced by the frequency and time dimensions.
Examples:
Source code in src/pymultitaper/spectral.py
spectrogram(data, fs, time_step, window_length=None, window_shape='hamming', freq_range=None, detrend='constant', nfft=None, db_scale=True, p_ref=2e-05, boundary_pad=False)
Compute the ordinary (single-taper) PSD of the input data.
This is similar to scipy.signal.spectrogram except that it supports also GPU computation. The computation backend (CPU or GPU) is automatically determined by the type of the input arrays (numpy or cupy).
Parameters:
-
data(NDArray) –(..., n_samples) Input data:
- Can be of any shape (including 1d array), as long as the last dimension is the time dimension (n_samples). The spectrogram computation will be applied to the last dimension, and the other dimensions will be treated as batch dimensions and preserved in the output.
- Can be either a numpy array or a cupy array. The backend (CPU or GPU) will be automatically determined based on the type of the input data.
-
fs(float) –Sampling frequency
-
time_step(float) –Time step between frames in seconds
-
window_length(float, default:None) –Window length in seconds. If
None, will be set to the same astime_step. Defaults to None. -
window_shape(Union[str, tuple], default:'hamming') –The shape of the window function. Defaults to "hamming".
-
freq_range(Optional[list], default:None) –The desired frequency range. If
None, will be set to [0, fs/2]. Defaults to None. -
detrend(Literal['constant', 'linear', 'off'], default:'constant') –Whether and how to detrend the signal. Defaults to "constant".
-
nfft(Optional[int], default:None) –The number of FFT points. If
None, will be set to the smallest power of 2 that is larger than the window length. Defaults to None. -
db_scale(bool, default:True) –Whether convert the result to db scale, i.e. 10log10(psd/p_ref**2). Defaults to True.
-
p_ref(float, default:2e-05) –If
db_scaleisTrue, thep_refvalue used in the dB conversion. Defaults to 2e-5. -
boundary_pad(bool, default:False) –Whether to pad the data with zeros at the beginning and end. This is useful when the data is not evenly divisible by the window length and time step. By default
False.- If
True, the data will be padded with zeros at the beginning and end, so that the first frame is centered on the first sample of data, and all samples are included in (at least) one frame. - If
False, the first frame is centered atwindow_length/2seconds after the first sample, and samples aftern_frames*time_step+window_lengthseconds are ignored.
- If
Returns:
-
freqs(NDArray) –(n_freqs,) Frequency points of the spectrogram.
-
times(NDArray) –(n_frames,) Time points of each frame.
-
psd(NDArray) –(..., n_freqs, n_frames) PSD spectrogram. The shape of the output PSD is the same as the input data, except that the last dimension (time) is replaced by the frequency and time dimensions.
Examples:
Source code in src/pymultitaper/spectral.py
Batched
batched_multitaper_spectrogram(*args, **kwargs)
Compute multitaper spectrograms for a list of signals with selectable execution mode.
This function accepts a list of 1D signals of varying lengths and supports
four execution strategies through mode:
"auto": automatically select"loop"for NumPy or"chunk_batched"for CuPy."loop": compute each signal independently."batched": pad all signals to a common length and run one batched call."chunk_batched": split signals into chunks of similar lengths, and batch-process each chunk to minimize padding overhead. Chunk size can be controlled with thechunk_sizeargument, which defaults ton_signals // 10.
Spectrogram computation is otherwise identical to
multitaper_spectrogram,
and returned results correspond to each input signal's valid frames.
The computation backend (CPU or GPU) is determined by the input array type.
Parameters:
-
signal_list(list) –A list of 1D NumPy or CuPy arrays of any length.
-
fs(float) –Sampling frequency.
-
time_step(float) –Time step between frames in seconds.
-
window_length(float) –Window length in seconds. If
None, defaults totime_step. -
NW(float) –Multitaper time-bandwidth parameter. Defaults to
4.0. -
n_tapers(int) –Number of tapers. If
None, defaults tofloor(2*NW - 1). -
freq_range(list) –Frequency range
[fmin, fmax]. IfNone, defaults to[0, fs/2]. -
weight_type(str) –Taper weighting:
"unity"or"eig". Defaults to"unity". -
detrend(str) –Detrending method:
"constant","linear", or"off". Defaults to"off"(no detrending). -
nfft(int) –Number of FFT points.
-
db_scale(bool) –Whether to scale to dB. Defaults to
True. -
p_ref(float) –Reference pressure for dB conversion. Defaults to
2e-5Pa. -
boundary_pad(bool) –Whether to pad data at boundaries. Defaults to
False. -
mode(Literal['auto', 'loop', 'batched', 'chunk_batched']) –Execution mode for list processing.
"auto"selects automatically based on backend."loop"runs per-signal computation."batched"pads all signals to a common length."chunk_batched"splits into chunks for memory-efficient batch processing. Defaults to"auto". -
chunk_size(int) –Number of signals per chunk when using
mode="chunk_batched". IfNone, defaults ton_signals // 10.
Returns:
-
freqs(NDArray) –(n_freqs,) Frequency points.
-
time_list(list) –List of time arrays, one per input signal.
-
psd_list(list) –List of multitaper PSD arrays
(n_freqs, n_frames_i), one per input signal, with invalid/padded frames removed.
Examples:
>>> from pymultitaper import batched_multitaper_spectrogram
>>> n_samples = cp.random.randint(100, 200, size=100)
>>> signals = [cp.random.randn(n) for n in n_samples]
>>> freqs, times, specs = batched_multitaper_spectrogram(signals, mode="chunk_batched",chunk_size=10, fs=1000, time_step=0.01, NW=4)
>>> len(specs), len(times)
(2, 2)
Source code in src/pymultitaper/batched.py
batched_spectrogram(*args, **kwargs)
Compute spectrograms for a list of signals with selectable execution mode.
This function accepts a list of 1D signals of varying lengths and supports
four execution strategies through mode:
"auto": select"loop"for NumPy or"chunk_batched"for CuPy."loop": compute each signal independently."batched": pad all signals to a common length and run one batched call."chunk_batched": split signals into chunks of similar lengths, and batch-process each chunk to minimize padding overhead. Chunk size can be controlled with thechunk_sizeargument, which defaults ton_signals // 10.
Spectrogram computation is otherwise identical to
spectrogram, and returned results
correspond to each input signal's valid frames.
The computation backend (CPU or GPU) is determined by the input array type.
Parameters:
-
signal_list(list) –A list of 1D NumPy or CuPy arrays of any length.
-
fs(float) –Sampling frequency.
-
time_step(float) –Time step between frames in seconds.
-
window_length(float) –Window length in seconds. If
None, defaults totime_step. -
window_shape(Union[str, tuple]) –Window function shape. Defaults to
"hamming". -
freq_range(list) –Frequency range
[fmin, fmax]. IfNone, defaults to[0, fs/2]. -
detrend(str) –Detrending method:
"constant","linear", or"off". Defaults to"off"(no detrending). -
nfft(int) –Number of FFT points.
-
db_scale(bool) –Whether to scale to dB. Defaults to
True. -
p_ref(float) –Reference pressure for dB conversion. Defaults to
2e-5Pa. -
boundary_pad(bool) –Whether to pad data at boundaries. Defaults to
False. -
mode(Literal['auto', 'loop', 'batched', 'chunk_batched']) –Execution mode for list processing.
"auto"selects automatically based on backend."loop"runs per-signal computation."batched"pads all signals to a common length."chunk_batched"splits into chunks for memory-efficient batch processing. Defaults to"auto". -
chunk_size(int) –Number of signals per chunk when using
mode="chunk_batched". IfNone, defaults ton_signals // 10.
Returns:
-
freqs(NDArray) –(n_freqs,) Frequency points.
-
time_list(list) –List of time arrays, one per input signal.
-
spec_list(list) –List of PSD arrays
(n_freqs, n_frames_i), one per input signal, with invalid/padded frames removed.
Examples:
>>> from pymultitaper import batched_spectrogram
>>> n_samples = cp.random.randint(100, 200, size=100)
>>> signals = [cp.random.randn(n) for n in n_samples]
>>> freqs, times, specs = batched_spectrogram(signals, mode="chunk_batched",chunk_size=10, fs=1000, time_step=0.01)
>>> len(specs), len(times)
(2, 2)
Source code in src/pymultitaper/batched.py
Plotting
plot_spectrogram(times, freqs, psd, ax=None, **kwargs)
Plot the spectrogram.
Note: Convert the spectrogram to dB scale (set db_scale to True in the spectrogram functions, or convert it manually) before plotting, otherwise the plot may not be very informative.
Parameters:
-
times((n_frames,)) –Time points of each frame
-
freqs((n_freqs,)) –Frequency points of the spectrogram
-
psd((n_freqs, n_frames)) –PSD spectrogram
-
ax(Optional[Axes], default:None) –The Axes object to plot the spectrogram. If
None, a new figure will be created. Defaults to None. -
**kwargs–Additional arguments to
ax.pcolormesh
Returns:
-
fig(Figure) –The figure object
-
ax(Axes) –The Axes object
Examples:
Source code in src/pymultitaper/plot.py
plot_spectrum(times, freqs, psd, time, ax=None, **kwargs)
Plot the spectrum at a specific time point.
Parameters:
-
times((n_frames,)) –Time points of each frame
-
freqs((n_freqs,)) –Frequency points of the spectrogram
-
psd((n_freqs, n_frames)) –PSD spectrogram
-
time(float) –The time point to plot the spectrum
-
ax(Optional[Axes], default:None) –The Axes object to plot the spectrum. If
None, a new figure will be created. Defaults to None. -
**kwargs–Additional arguments to
ax.plot
Returns:
-
fig(Figure) –The figure object
-
ax(Axes) –The Axes object
Examples: