Skip to content

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 as time_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_scale is True, the p_ref value 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 at window_length/2 seconds after the first sample, and samples after n_frames*time_step+window_length seconds are ignored.
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:

>>> freqs,times,psd = multitaper_spectrogram(data,fs,time_step=0.001,window_length=0.005,NW=4)
Source code in src/pymultitaper/spectral.py
def multitaper_spectrogram(
    data: NDArray,
    fs: float,
    time_step: float,
    window_length: Optional[float] = None,
    NW: float = 4.0,
    n_tapers: Optional[int] = None,
    freq_range: Optional[list] = None,
    weight_type: Literal["unity", "eig"] = "unity",
    detrend: Literal["constant", "linear", "off"] = "constant",
    nfft: Optional[int] = None,
    db_scale: bool = True,
    p_ref: float = 2e-5,
    boundary_pad: bool = False,
) -> Tuple[NDArray, NDArray, NDArray]:
    """
    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).

    Args:
        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, optional): Window length in seconds. If `None`, will be set to the same as `time_step`. Defaults to None.
        NW (float, optional): NW value, see notes for details. Defaults to 4.0.
        n_tapers (Optional[int], optional): The max number of tapers, if `None`, will be set to NW*2-1. Defaults to None.
        freq_range (Optional[list], optional): The desired frequency range. If `None`, will be set to [0, fs/2]. Defaults to None.
        weight_type (Literal["unity","eig"], optional): The type of weights among tapers. Defaults to "unity".
        detrend (Literal["constant","linear","off"], optional): Whether and how to detrend the signal. Defaults to "constant".
        nfft (Optional[int], optional): 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, optional): Whether convert the result to db scale, i.e. 10log10(psd/p_ref**2). Defaults to True.
        p_ref (float, optional): If `db_scale` is `True`, the `p_ref` value used in the dB conversion. Defaults to 2e-5.
        boundary_pad (bool, optional): 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 at `window_length/2` seconds after the first sample, and samples after `n_frames*time_step+window_length` seconds are ignored.

    Notes:
        The value of 2W is the regularization bandwidth. Typically, we choose W to be a small multiple of the fundamental frequency 1/(N*dt) (where N is the number of samples in the data), i.e. W=i/(N*dt). 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:
        >>> freqs,times,psd = multitaper_spectrogram(data,fs,time_step=0.001,window_length=0.005,NW=4)
    """
    # (nfft,n_frames)
    if n_tapers is None:
        # Note: NW may be a float number
        # We DONOT need a cupy float here
        n_tapers = np.floor(2 * NW - 1).astype(int)
    window_length = time_step if window_length is None else window_length
    n_winlen = int(window_length * fs)
    tapers, weights = _get_dpss_windows(n_winlen, NW, n_tapers, weight_type, like=data)
    return _spectrogram(
        data=data,
        fs=fs,
        time_step=time_step,
        win=tapers,
        weights=weights,
        freq_range=freq_range,
        detrend=detrend,
        nfft=nfft,
        db_scale=db_scale,
        p_ref=p_ref,
        boundary_pad=boundary_pad,
    )

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 as time_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_scale is True, the p_ref value 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 at window_length/2 seconds after the first sample, and samples after n_frames*time_step+window_length seconds are ignored.

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:

>>> freqs,times,psd = spectrogram(data,fs,time_step=0.001,window_length=0.005)
Source code in src/pymultitaper/spectral.py
def spectrogram(
    data: NDArray,
    fs: float,
    time_step: float,
    window_length: Optional[float] = None,
    window_shape: Union[str, tuple] = "hamming",
    freq_range: Optional[list] = None,
    detrend: Literal["constant", "linear", "off"] = "constant",
    nfft: Optional[int] = None,
    db_scale: bool = True,
    p_ref: float = 2e-5,
    boundary_pad: bool = False,
) -> Tuple[NDArray, NDArray, NDArray]:
    """
    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).

    Args:
        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, optional): Window length in seconds. If `None`, will be set to the same as `time_step`. Defaults to None.
        window_shape (Union[str,tuple], optional): The shape of the window function. Defaults to "hamming".
        freq_range (Optional[list], optional): The desired frequency range. If `None`, will be set to [0, fs/2]. Defaults to None.
        detrend (Literal["constant","linear","off"], optional): Whether and how to detrend the signal. Defaults to "constant".
        nfft (Optional[int], optional): 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, optional): Whether convert the result to db scale, i.e. 10log10(psd/p_ref**2). Defaults to True.
        p_ref (float, optional): If `db_scale` is `True`, the `p_ref` value used in the dB conversion. Defaults to 2e-5.
        boundary_pad (bool, optional): 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 at `window_length/2` seconds after the first sample, and samples after `n_frames*time_step+window_length` seconds are ignored.

    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:
        >>> freqs,times,psd = spectrogram(data,fs,time_step=0.001,window_length=0.005)
    """
    window_length = time_step if window_length is None else window_length
    n_winlen = int(window_length * fs)
    win, weights = _get_1d_window(window_shape, n_winlen, like=data)
    return _spectrogram(
        data=data,
        fs=fs,
        time_step=time_step,
        win=win,
        weights=weights,
        freq_range=freq_range,
        detrend=detrend,
        nfft=nfft,
        db_scale=db_scale,
        p_ref=p_ref,
        boundary_pad=boundary_pad,
    )

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 the chunk_size argument, which defaults to n_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 to time_step.

  • NW (float) –

    Multitaper time-bandwidth parameter. Defaults to 4.0.

  • n_tapers (int) –

    Number of tapers. If None, defaults to floor(2*NW - 1).

  • freq_range (list) –

    Frequency range [fmin, fmax]. If None, 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-5 Pa.

  • 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". If None, defaults to n_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
def 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 the ``chunk_size`` argument, which defaults to ``n_signals // 10``.

    Spectrogram computation is otherwise identical to
    [`multitaper_spectrogram`][src.pymultitaper.spectral.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.

    Args:
        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, optional): Window length in seconds. If ``None``,
            defaults to ``time_step``.
        NW (float, optional): Multitaper time-bandwidth parameter. Defaults
            to ``4.0``.
        n_tapers (int, optional): Number of tapers. If ``None``, defaults to
            ``floor(2*NW - 1)``.
        freq_range (list, optional): Frequency range ``[fmin, fmax]``. If
            ``None``, defaults to ``[0, fs/2]``.
        weight_type (str, optional): Taper weighting: ``"unity"`` or ``"eig"``.
            Defaults to ``"unity"``.
        detrend (str, optional): Detrending method: ``"constant"``,
            ``"linear"``, or ``"off"``. Defaults to ``"off"`` (no detrending).
        nfft (int, optional): Number of FFT points.
        db_scale (bool, optional): Whether to scale to dB. Defaults to
            ``True``.
        p_ref (float, optional): Reference pressure for dB conversion.
            Defaults to ``2e-5`` Pa.
        boundary_pad (bool, optional): Whether to pad data at boundaries.
            Defaults to ``False``.
        mode (Literal["auto", "loop", "batched", "chunk_batched"], optional):
            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, optional): Number of signals per chunk when using
            ``mode="chunk_batched"``. If ``None``, defaults to ``n_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)
    """
    return multitaper_spectrogram(*args, **kwargs)

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 the chunk_size argument, which defaults to n_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 to time_step.

  • window_shape (Union[str, tuple]) –

    Window function shape. Defaults to "hamming".

  • freq_range (list) –

    Frequency range [fmin, fmax]. If None, 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-5 Pa.

  • 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". If None, defaults to n_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
@_batched
def 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 the ``chunk_size`` argument, which defaults to ``n_signals // 10``.

    Spectrogram computation is otherwise identical to
    [`spectrogram`][src.pymultitaper.spectral.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.

    Args:
        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, optional): Window length in seconds. If ``None``,
            defaults to ``time_step``.
        window_shape (Union[str, tuple], optional): Window function shape.
            Defaults to ``"hamming"``.
        freq_range (list, optional): Frequency range ``[fmin, fmax]``. If
            ``None``, defaults to ``[0, fs/2]``.
        detrend (str, optional): Detrending method: ``"constant"``,
            ``"linear"``, or ``"off"``. Defaults to ``"off"`` (no detrending).
        nfft (int, optional): Number of FFT points.
        db_scale (bool, optional): Whether to scale to dB. Defaults to
            ``True``.
        p_ref (float, optional): Reference pressure for dB conversion.
            Defaults to ``2e-5`` Pa.
        boundary_pad (bool, optional): Whether to pad data at boundaries.
            Defaults to ``False``.
        mode (Literal["auto", "loop", "batched", "chunk_batched"], optional):
            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, optional): Number of signals per chunk when using
            ``mode="chunk_batched"``. If ``None``, defaults to ``n_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)
    """
    return spectrogram(*args, **kwargs)

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:

>>> f,ax = plt.subplots(1,1)
>>> plot_spectrogram(times,freqs,psd,ax=ax,cmap="viridis")
Source code in src/pymultitaper/plot.py
def plot_spectrogram(
    times: NDArray,
    freqs: NDArray,
    psd: NDArray,
    ax: Optional[plt.Axes] = None,
    **kwargs,
) -> tuple:
    """
    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.

    Args:
        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[plt.Axes], optional): 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 (plt.Figure): The figure object
        ax (plt.Axes): The Axes object

    Examples:
        >>> f,ax = plt.subplots(1,1)
        >>> plot_spectrogram(times,freqs,psd,ax=ax,cmap="viridis")
    """
    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure
    times, freqs, psd = map(_as_np, [times, freqs, psd])
    mesh = ax.pcolormesh(times, freqs, psd, **kwargs)
    ax.set_xlabel("Time (s)")
    ax.set_ylabel("Frequency (Hz)")
    fig.colorbar(mesh, ax=ax)
    return fig, ax

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:

>>> f,ax = plt.subplots(1,1)
>>> plot_spectrum(times,freqs,psd,time=0.7,ax=ax)
Source code in src/pymultitaper/plot.py
def plot_spectrum(
    times: NDArray,
    freqs: NDArray,
    psd: NDArray,
    time: float,
    ax: Optional[plt.Axes] = None,
    **kwargs,
) -> tuple:
    """

    Plot the spectrum at a specific time point.

    Args:
        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[plt.Axes], optional): 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 (plt.Figure): The figure object
        ax (plt.Axes): The Axes object

    Examples:
        >>> f,ax = plt.subplots(1,1)
        >>> plot_spectrum(times,freqs,psd,time=0.7,ax=ax)
    """
    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure
    times, freqs, psd = map(_as_np, [times, freqs, psd])
    idx = np.argmin(np.abs(times - time))
    ax.plot(freqs, psd[:, idx], **kwargs)
    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("PSD")
    ax.set_title(f"Spectrum at time {time}s")
    return fig, ax