Exemplo n.º 1
0
def compute_spectrum_wavelet(sig, fs, freqs, avg_type='mean', **kwargs):
    """Compute the power spectral density using wavelets.

    Parameters
    ----------
    sig : 1d or 2d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    avg_type : {'mean', 'median'}, optional
        Method to average across the windows.
    **kwargs
        Optional inputs for using wavelets.

    Returns
    -------
    freqs : 1d array
        Frequencies at which the measure was calculated.
    spectrum : 1d or 2d array
        Power spectral density.
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)

    mwt = compute_wavelet_transform(sig, fs, freqs, **kwargs)
    spectrum = get_avg_func(avg_type)(mwt, axis=0)

    return freqs, spectrum
Exemplo n.º 2
0
def compute_wavelet_transform(sig, fs, freqs, n_cycles=7, scaling=0.5):
    """Compute the time-frequency representation of a signal using morlet wavelets.

    Parameters
    ----------
    sig : 1d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    n_cycles : float
        Length of the filter, as the number of cycles for each frequency.
    scaling : float
        Scaling factor.

    Returns
    -------
    mwt : 2d array
        Time frequency representation of the input signal.
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)
    n_cycles = check_n_cycles(n_cycles, len(freqs))

    mwt = np.zeros([len(sig), len(freqs)], dtype=complex)
    for ind, (freq, n_cycle) in enumerate(zip(freqs, n_cycles)):
        mwt[:, ind] = convolve_wavelet(sig, fs, freq, n_cycle, scaling)

    return mwt
Exemplo n.º 3
0
def compute_lagged_coherence(sig, fs, freqs, n_cycles=3, return_spectrum=False):
    """Compute lagged coherence, reflecting the rhythmicity across a frequency range.

    Parameters
    ----------
    sig : 1d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    n_cycles : float or list of float, default: 3
        Number of cycles of each frequency to use to compute lagged coherence.
        If a single value, the same number of cycles is used for each frequency value.
        If a list or list_like, then should be a n_cycles corresponding to each frequency.
    return_spectrum : bool, optional, default: False
        If True, return the lagged coherence for all frequency values.
        Otherwise, only the mean lagged coherence value across the frequency range is returned.

    Returns
    -------
    lcs : float or 1d array
        If `return_spectrum` is False: mean lagged coherence value across the frequency range.
        If `return_spectrum` is True: lagged coherence values for all frequencies.
    freqs : 1d array
        Frequencies, corresponding to the lagged coherence values, in Hz.
        Only returned if `return_spectrum` is True.

    References
    ----------
    .. [1] Fransen, A. M., van Ede, F., & Maris, E. (2015).
           Identifying neuronal oscillations using rhythmicity.
           Neuroimage, 118, 256-267. DOI: 10.1016/j.neuroimage.2015.06.003
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)
    n_cycles = check_n_cycles(n_cycles, len(freqs))

    # Calculate lagged coherence for each frequency
    lcs = np.zeros(len(freqs))
    for ind, (freq, n_cycle) in enumerate(zip(freqs, n_cycles)):
        lcs[ind] = lagged_coherence_1freq(sig, fs, freq, n_cycles=n_cycle)

    # Check if all values were properly estimated
    if sum(np.isnan(lcs)) > 0:
        warn("NEURODSP - LAGGED COHERENCE WARNING:"
             "\nLagged coherence could not be estimated for at least some requested frequencies."
             "\nThis happens, especially with low frequencies, when there are not enough samples "
             "per segment and/or not enough segments available to estimate the measure."
             "\nTry using a greater number of cycles and/or a longer signal length, and/or "
             "adjust the frequency range.")

    if return_spectrum:
        return lcs, freqs
    else:
        return np.mean(lcs)
Exemplo n.º 4
0
def compute_spectrum_wavelet(sig, fs, freqs, avg_type='mean', **kwargs):
    """Compute the power spectral density using wavelets.

    Parameters
    ----------
    sig : 1d or 2d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    avg_type : {'mean', 'median'}, optional
        Method to average across the windows.
    **kwargs
        Optional inputs for using wavelets.

    Returns
    -------
    freqs : 1d array
        Frequencies at which the measure was calculated.
    spectrum : 1d or 2d array
        Power spectral density.

    Examples
    --------
    Compute the power spectrum of a simulated time series using wavelets:

    >>> from neurodsp.sim import sim_combined
    >>> sig = sim_combined(n_seconds=10, fs=500,
    ...                    components={'sim_powerlaw': {}, 'sim_oscillation' : {'freq': 10}})
    >>> freqs, spectrum = compute_spectrum_wavelet(sig, fs=500, freqs=[1, 30])
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)

    # Compute the wavelet transform
    mwt = compute_wavelet_transform(sig, fs, freqs, **kwargs)

    # Convert the wavelet coefficient outputs to units of power
    mwt_power = abs(mwt)**2

    # Create the power spectrum by averaging across the time dimension
    spectrum = get_avg_func(avg_type)(mwt_power, axis=1)

    return freqs, spectrum
Exemplo n.º 5
0
def compute_wavelet_transform(sig, fs, freqs, n_cycles=7, scaling=0.5):
    """Compute the time-frequency representation of a signal using morlet wavelets.

    Parameters
    ----------
    sig : 1d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    n_cycles : float
        Length of the filter, as the number of cycles for each frequency.
    scaling : float
        Scaling factor.

    Returns
    -------
    mwt : 2d array
        Time frequency representation of the input signal.

    Examples
    --------
    Compute a Morlet wavelet time-frequency representation of a signal:

    >>> from neurodsp.sim import sim_combined
    >>> sig = sim_combined(n_seconds=10, fs=500,
    ...                    components={'sim_powerlaw': {}, 'sim_oscillation' : {'freq': 10}})
    >>> mwt = compute_wavelet_transform(sig, fs=500, freqs=[1, 30])
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)
    n_cycles = check_n_cycles(n_cycles, len(freqs))

    mwt = np.zeros([len(sig), len(freqs)], dtype=complex)
    for ind, (freq, n_cycle) in enumerate(zip(freqs, n_cycles)):
        mwt[:, ind] = convolve_wavelet(sig, fs, freq, n_cycle, scaling)

    return mwt
Exemplo n.º 6
0
def compute_wavelet_transform(sig,
                              fs,
                              freqs,
                              n_cycles=7,
                              scaling=0.5,
                              norm='amp'):
    """Compute the time-frequency representation of a signal using morlet wavelets.

    Parameters
    ----------
    sig : 1d array
        Time series.
    fs : float
        Sampling rate, in Hz.
    freqs : 1d array or list of float
        If array, frequency values to estimate with morlet wavelets.
        If list, define the frequency range, as [freq_start, freq_stop, freq_step].
        The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
    n_cycles : float or 1d array
        Length of the filter, as the number of cycles for each frequency.
        If 1d array, this defines n_cycles for each frequency.
    scaling : float
        Scaling factor.
    norm : {'sss', 'amp'}, optional
        Normalization method:

        * 'sss' - divide by the square root of the sum of squares
        * 'amp' - divide by the sum of amplitudes

    Returns
    -------
    mwt : 2d array
        Time frequency representation of the input signal.

    Notes
    -----
    This computes the continuous wavelet transform at specified frequencies across time.

    Examples
    --------
    Compute a Morlet wavelet time-frequency representation of a signal:

    >>> from neurodsp.sim import sim_combined
    >>> sig = sim_combined(n_seconds=10, fs=500,
    ...                    components={'sim_powerlaw': {}, 'sim_oscillation' : {'freq': 10}})
    >>> mwt = compute_wavelet_transform(sig, fs=500, freqs=[1, 30])
    """

    if isinstance(freqs, (tuple, list)):
        freqs = create_freqs(*freqs)
    n_cycles = check_n_cycles(n_cycles, len(freqs))

    mwt = np.zeros([len(freqs), len(sig)], dtype=complex)
    for ind, (freq, n_cycle) in enumerate(zip(freqs, n_cycles)):
        mwt[ind, :] = convolve_wavelet(sig,
                                       fs,
                                       freq,
                                       n_cycle,
                                       scaling,
                                       norm=norm)

    return mwt