Esempio n. 1
0
    def process(self, trials, metadata=None):
        # expecting trials in b01c format with tf layout for 01-axes
        assert trials.shape[2] == 1

        from mne.time_frequency import cwt_morlet

        tfr_trials = []
        for trial in trials:
#             print trial.shape
            trial = trial[:,0,:]            # get rid of 1-axis
            trial = trial.T                 # put channels first

            tfr = cwt_morlet(trial,
                             sfreq=self.sfreq,
                             freqs=self.freqs,
                             use_fft=self.use_fft,
                             n_cycles=self.n_cycles,
                             zero_mean=self.zero_mean)

            tfr = abs(tfr) ** 2

            # tfr format: channels x freqs x samples
            # desired output format: samples x freqs x channels
            tfr = np.swapaxes(tfr, 0, 2)

#             print tfr.shape
            tfr_trials.append(tfr)

        tfr_trials = np.asarray(tfr_trials)
#         print tfr_trials.shape
        return tfr_trials
def single_epoch_tf_source(epochs, inv, src, label):
    """Calculates single trail power

    Parameter
    ---------
    epochs : ???
        The subject number to use.
    inv = inverse_operator
        ...
    src : source space
        ...
    label : label
        ...
    """
    snr = 1.0
    lambda2 = 1.0 / snr ** 2
    method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

    frequencies = np.arange(8, 13, 1)
    stcs = apply_inverse_epochs(epochs, inv, lambda2=lambda2, method=method,
                                label=None, pick_ori=None)
    time_series = [stc.extract_label_time_course(labels=label, src=src,
                                                 mode="pca_flip")[0]
                   for stc in stcs]

    ts_signed = []
    for j in range(len(time_series)):
        tmp = time_series[j]
        tmp *= np.sign(tmp[np.argmax(np.abs(tmp))])
        ts_signed.append(tmp)

    tfr = cwt_morlet(np.asarray(ts_signed), epochs.info["sfreq"], frequencies,
                     use_fft=True, n_cycles=4)

    return tfr
def single_trial_tf(epochs, frequencies, n_cycles=4.):
    """


    Parameters
    ----------
    epochs : Epochs object
        The epochs to calculate TF analysis on.
    frequencies : numpy array
    n_cycles : int
        The number of cycles for the Morlet wavelets.

    Returns
    -------
    results : numpy array
    """
    results = []

    for j in range(len(epochs)):
        tfr = cwt_morlet(epochs.get_data()[j],
                         sfreq=epochs.info["sfreq"],
                         freqs=frequencies,
                         use_fft=True,
                         n_cycles=n_cycles,
                         # decim=2,
                         zero_mean=False)
        results.append(tfr)
    return results
def single_trial_tf(epochs, frequencies, n_cycles):
    """Something here.

    Parameters
    ----------
    epochs : Epochs object
        The epochs to calculate TF analysis on.
    n_cycles : int or numpy array
        The number of cycles for the Morlet wavelets.

    Returns
    -------
    results : numpy array
    """
    results = []

    for j in range(len(epochs)):
        tfr = cwt_morlet(epochs.get_data()[j],
                         sfreq=epochs.info["sfreq"],
                         freqs=frequencies,
                         use_fft=True,
                         n_cycles=n_cycles,
                         zero_mean=False)
        results.append(tfr)
    return results
Esempio n. 5
0
    def process(self, trials, metadata=None):
        # expecting trials in b01c format with tf layout for 01-axes
        assert trials.shape[2] == 1

        from mne.time_frequency import cwt_morlet

        tfr_trials = []
        for trial in trials:
            #             print trial.shape
            trial = trial[:, 0, :]  # get rid of 1-axis
            trial = trial.T  # put channels first

            tfr = cwt_morlet(trial,
                             sfreq=self.sfreq,
                             freqs=self.freqs,
                             use_fft=self.use_fft,
                             n_cycles=self.n_cycles,
                             zero_mean=self.zero_mean)

            tfr = abs(tfr)**2

            # tfr format: channels x freqs x samples
            # desired output format: samples x freqs x channels
            tfr = np.swapaxes(tfr, 0, 2)

            #             print tfr.shape
            tfr_trials.append(tfr)

        tfr_trials = np.asarray(tfr_trials)
        #         print tfr_trials.shape
        return tfr_trials
Esempio n. 6
0
def tft_transofrm(source,freqs):
    # average : bool - averaging of output data in sliding windows
    # average_w_width sliding window width
    # average_w_step sliding window step

    sfreq = 1000
    res = np.zeros((source.shape[0],source.shape[1],len(freqs),source.shape[2]),dtype=np.float32)
    for i in xrange(source.shape[0]):
         res[i,:,:,:] = np.absolute(cwt_morlet(source[i,:,:], sfreq, freqs, use_fft=True, n_cycles=7.0, zero_mean=True, decim=1)).astype('float32',casting='same_kind')
    return res
Esempio n. 7
0
def _extract_phase_and_amp(data_phase, data_amp, sfreq, freqs_phase,
                           freqs_amp, scale=True):
    """Extract the phase and amplitude of two signals for PAC viz.
    data should be shape (n_epochs, n_times)"""
    from sklearn.preprocessing import scale

    # Morlet transform to get complex representation
    band_ph = cwt_morlet(data_phase, sfreq, freqs_phase)
    band_amp = cwt_morlet(data_amp, sfreq, freqs_amp)

    # Calculate the phase/amplitude of relevant signals across epochs
    band_ph_stacked = np.hstack(np.real(band_ph))
    angle_ph = np.hstack(np.angle(band_ph))
    amp = np.hstack(np.abs(band_amp) ** 2)

    # Scale the amplitude for viz so low freqs don't dominate highs
    if scale is True:
        amp = scale(amp, axis=1)
    return angle_ph, band_ph_stacked, amp
Esempio n. 8
0
def extract_amplitude(inst, freqs, n_cycles=7, normalize=False):
    """Extract the time-varying amplitude for a frequency band.

    If multiple freqs are given, the amplitude is calculated at each frequency
    and then averaged across frequencies.

    Parameters
    ----------
    inst : instance of Raw
        The data to have amplitude extracted
    freqs : array of ints/floats, shape (n_freqs)
        The frequencies to use. If multiple frequency bands given, amplitude
        will be extracted at each and then averaged between frequencies. The
        structure of each band is fmin, fmax.
    n_cycles : int
        The number of cycles to include in the filter length for the wavelet.
    normalize : bool
        Normalize the power of each band by its mean before combining.

    Returns
    -------
    inst : mne instance, same type as input 'inst'
        The MNE instance with channels replaced with their time-varying
        amplitude for the supplied frequency range.
    """

    # Data checks
    freqs = np.atleast_1d(freqs)
    picks = range(len(inst.ch_names))
    if inst.preload is False:
        raise ValueError('Data must be preloaded.')

    # Filter for HFB and extract amplitude
    bands = np.zeros([len(picks), inst.n_times])
    for ifreq in tqdm(freqs):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            # Extract power for this frequency + modify in place to save mem
            band = np.abs(cwt_morlet(inst._data, inst.info['sfreq'], [ifreq]))
        band = band[:, 0, :]

        if normalize is True:
            # Scale frequency band so that the ratios of all are the same
            band /= band.mean()
        bands += np.abs(band)

    # Convert into an average
    bands /= len(freqs)
    inst = inst.copy()
    inst._data = bands
    return inst
Esempio n. 9
0
def extract_amplitude(inst, freqs, n_cycles=7, normalize=False):
    """Extract the time-varying amplitude for a frequency band.

    If multiple freqs are given, the amplitude is calculated at each frequency
    and then averaged across frequencies.

    Parameters
    ----------
    inst : instance of Raw
        The data to have amplitude extracted
    freqs : array of ints/floats, shape (n_freqs)
        The frequencies to use. If multiple frequency bands given, amplitude
        will be extracted at each and then averaged between frequencies. The
        structure of each band is fmin, fmax.
    n_cycles : int
        The number of cycles to include in the filter length for the wavelet.
    normalize : bool
        Normalize the power of each band by its mean before combining.

    Returns
    -------
    inst : mne instance, same type as input 'inst'
        The MNE instance with channels replaced with their time-varying
        amplitude for the supplied frequency range.
    """

    # Data checks
    freqs = np.atleast_1d(freqs)
    picks = range(len(inst.ch_names))
    if inst.preload is False:
        raise ValueError('Data must be preloaded.')

    # Filter for HFB and extract amplitude
    bands = np.zeros([len(picks), inst.n_times])
    for ifreq in tqdm(freqs):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            # Extract power for this frequency + modify in place to save mem
            band = np.abs(cwt_morlet(inst._data, inst.info['sfreq'], [ifreq]))
        band = band[:, 0, :]

        if normalize is True:
            # Scale frequency band so that the ratios of all are the same
            band /= band.mean()
        bands += np.abs(band)

    # Convert into an average
    bands /= len(freqs)
    inst = inst.copy()
    inst._data = bands
    return inst
Esempio n. 10
0
def _extract_phase_and_amp(data_phase,
                           data_amp,
                           sfreq,
                           freqs_phase,
                           freqs_amp,
                           scale=True):
    """Extract the phase and amplitude of two signals for PAC viz.
    data should be shape (n_epochs, n_times)"""
    from sklearn.preprocessing import scale

    # Morlet transform to get complex representation
    band_ph = cwt_morlet(data_phase, sfreq, freqs_phase)
    band_amp = cwt_morlet(data_amp, sfreq, freqs_amp)

    # Calculate the phase/amplitude of relevant signals across epochs
    band_ph_stacked = np.hstack(np.real(band_ph))
    angle_ph = np.hstack(np.angle(band_ph))
    amp = np.hstack(np.abs(band_amp)**2)

    # Scale the amplitude for viz so low freqs don't dominate highs
    if scale is True:
        amp = scale(amp, axis=1)
    return angle_ph, band_ph_stacked, amp
Esempio n. 11
0
def single_epoch_tf_source(epochs, inv, src, label):
    """Calculates single trail power

    Parameter
    ---------
    epochs : ???
        The subject number to use.
    inv = inverse_operator
        ...
    src : source space
        ...
    label : label
        ...
    """
    snr = 1.0
    lambda2 = 1.0 / snr**2
    method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

    frequencies = np.arange(8, 13, 1)
    stcs = apply_inverse_epochs(epochs,
                                inv,
                                lambda2=lambda2,
                                method=method,
                                label=None,
                                pick_ori=None)
    time_series = [
        stc.extract_label_time_course(labels=label, src=src,
                                      mode="pca_flip")[0] for stc in stcs
    ]

    ts_signed = []
    for j in range(len(time_series)):
        tmp = time_series[j]
        tmp *= np.sign(tmp[np.argmax(np.abs(tmp))])
        ts_signed.append(tmp)

    tfr = cwt_morlet(np.asarray(ts_signed),
                     epochs.info["sfreq"],
                     frequencies,
                     use_fft=True,
                     n_cycles=4)

    return tfr
Esempio n. 12
0
import numpy as np
import sys

from mne.time_frequency import cwt_morlet

from my_settings import *

subject = sys.argv[1]

sfreq = 500
frequencies = np.arange(4, 90, 2)
n_cycles = frequencies / 3.

for condition in conditions:
    ts = np.load(source_folder + "ave_ts/%s_%s_ts-epo.npy" % (subject,
                                                              condition))

    tfr_all = np.empty(
        [ts.shape[0], ts.shape[1], frequencies.shape[0], ts.shape[2]],
        dtype="complex128")
    for j, t in enumerate(ts):
        tfr = cwt_morlet(t,
                         sfreq=sfreq,
                         freqs=frequencies,
                         use_fft=True,
                         n_cycles=n_cycles)
        tfr_all[j] = tfr
    np.save(source_folder + "source_TF/%s_%s_tfr-extract.npy" % (subject,
                                                                 condition),
                                                                 tfr_all)
Esempio n. 13
0
def tfr_morlet(data,
               sfreq,
               freqs,
               kind='amplitude',
               n_cycles=3.,
               use_fft=True,
               decimate=1,
               average=False):
    """Calculate the time-frequency representation of a signal.

    Parameters
    ----------
    data : array, shape (n_signals, n_times) | (n_epochs, n_signals, n_times)
        The data to calculate the TFR.
    sfreq : float | int
        The sampling frequency of the data
    freqs : array, shape (n_frequencies)
        The frequencies to calculate for the TFR.
    kind : string, 'filter', 'amplitude'
        What kind of TFR to output. If "filter", then the output will be a
        band pass filter of the signal. If "amplitude", the output will be
        the amplitude at each frequency band.
    n_cycles : int | array, shape (n_frequencies)
        The number of cycles for each frequency to include.
    use_fft : bool
        Whether to use an FFT to calculate the wavelet transform
    decimate : int
        The amount to decimate the output. If 1, no decimation will be done.
    average : bool
        Whether to average across the first dimension before returning results.

    Returns
    -------
    tfr : array, shape ([n_epochs], n_channels, n_frequencies, n_times)
        The time-frequency data calculated from inputs. If `average=True`, the
        output will be averaged across the first dimension (epochs).
    """
    # Loop through our data
    if average is True:
        if data.ndim < 3:
            raise ValueError('If averaging, data should have at least 3 dims')
        n_ep, n_sig, n_times = data.shape[-3:]
        n_freqs = len(freqs)
        tfr = np.zeros([n_sig, n_freqs, int(np.round(n_times / decimate))])
    else:
        tfr = []
    for i_data in tqdm(data):
        # Calculate the wavelet transform for each iteration and stack
        i_data = np.atleast_2d(i_data)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            this_tfr = cwt_morlet(i_data,
                                  sfreq,
                                  freqs,
                                  n_cycles=n_cycles,
                                  use_fft=use_fft)
        if kind == 'filter':
            # In this case, we'll just take the real values
            this_tfr = np.real(this_tfr)

            if decimate != 1:
                warn('Decimating band-passed data may cause artifacts.')
        elif kind == 'amplitude':
            # Now take the absolute value so it's only amplitude
            this_tfr = np.abs(this_tfr)
        else:
            raise ValueError('kind must be one of "filter" | "amplitude"')
        this_tfr = this_tfr[..., ::decimate]

        if average is True:
            tfr += this_tfr
        else:
            tfr.append(this_tfr)

    if average is True:
        tfr /= n_ep
    else:
        tfr = np.asarray(tfr)
    return tfr.squeeze()
Esempio n. 14
0
def tfr_morlet(data, sfreq, freqs, kind='amplitude', n_cycles=3.,
               use_fft=True, decimate=1, average=False):
    """Calculate the time-frequency representation of a signal.

    Parameters
    ----------
    data : array, shape (n_signals, n_times) | (n_epochs, n_signals, n_times)
        The data to calculate the TFR.
    sfreq : float | int
        The sampling frequency of the data
    freqs : array, shape (n_frequencies)
        The frequencies to calculate for the TFR.
    kind : string, 'filter', 'amplitude'
        What kind of TFR to output. If "filter", then the output will be a
        band pass filter of the signal. If "amplitude", the output will be
        the amplitude at each frequency band.
    n_cycles : int | array, shape (n_frequencies)
        The number of cycles for each frequency to include.
    use_fft : bool
        Whether to use an FFT to calculate the wavelet transform
    decimate : int
        The amount to decimate the output. If 1, no decimation will be done.
    average : bool
        Whether to average across the first dimension before returning results.

    Returns
    -------
    tfr : array, shape ([n_epochs], n_channels, n_frequencies, n_times)
        The time-frequency data calculated from inputs. If `average=True`, the
        output will be averaged across the first dimension (epochs).
    """
    # Loop through our data
    if average is True:
        if data.ndim < 3:
            raise ValueError('If averaging, data should have at least 3 dims')
        n_ep, n_sig, n_times = data.shape[-3:]
        n_freqs = len(freqs)
        tfr = np.zeros([n_sig, n_freqs, int(np.round(n_times / decimate))])
    else:
        tfr = []
    for i_data in tqdm(data):
        # Calculate the wavelet transform for each iteration and stack
        i_data = np.atleast_2d(i_data)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            this_tfr = cwt_morlet(i_data, sfreq,
                                  freqs, n_cycles=n_cycles,
                                  use_fft=use_fft)
        if kind == 'filter':
            # In this case, we'll just take the real values
            this_tfr = np.real(this_tfr)

            if decimate != 1:
                warn('Decimating band-passed data may cause artifacts.')
        elif kind == 'amplitude':
            # Now take the absolute value so it's only amplitude
            this_tfr = np.abs(this_tfr)
        else:
            raise ValueError('kind must be one of "filter" | "amplitude"')
        this_tfr = this_tfr[..., ::decimate]

        if average is True:
            tfr += this_tfr
        else:
            tfr.append(this_tfr)

    if average is True:
        tfr /= n_ep
    else:
        tfr = np.asarray(tfr)
    return tfr.squeeze()
Esempio n. 15
0
                                    method,
                                    pick_ori=None)

        for label in labels_sel:
            label_ts = []
            for j in range(len(stcs)):
                ts = mne.extract_label_time_course(stcs[j],
                                                   labels=label,
                                                   src=src,
                                                   mode="pca_flip")
                ts = np.squeeze(ts)
                ts *= np.sign(ts[np.argmax(np.abs(ts))])
                label_ts.append(ts)

            label_ts = np.asarray(label_ts)
            tfr = cwt_morlet(label_ts, epochs.info["sfreq"], freqs,
                             use_fft=True, n_cycles=n_cycle)

            np.save(tf_folder + "%s_%s_%s_%s_%s_sf-tfr" % (subject,
                                                           condition[:3],
                                                           condition[4:],
                                                           label.name, method),
                    tfr)
            np.save(tf_folder + "%s_%s_%s_%s_%s_sf-ts" % (subject,
                                                          condition[:3],
                                                          condition[4:],
                                                          label.name, method),
                    label_ts)

        del stcs
        del tfr
Esempio n. 16
0
initOSCServer(ip=ip, port=6400, mode=1)

# and now set it into action
startOSCServer()

# get measurement info guessed by MNE-Python
ch_names = ['EEG-%i' % i for i in np.arange(n_eeg)]
raw_info = mne.create_info(ch_names, sfreq)

with FieldTripClient(info=raw_info, host='localhost', port=1972,
                     tmax=150, wait_max=10) as rt_client:

    tstart = time.time()
    told = tstart
    for ii in range(100):
        epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks)
        filt = band_pass_filter(epoch.get_data(), sfreq, fmin, fmax)
        # compute band power features
        bp = np.log10(np.abs(cwt_morlet(filt[0], sfreq, [(fmin + fmax) / 2.])))
        if told - tstart < baseline:
            bp_base.append(bp[:, 0, n_samples/2].mean())
        else:
            bp_sample = bp[:, 0, n_samples/2].mean()
            bp_ratio = (np.mean(bp_base) - bp_sample) / np.mean(bp_base)
            sendOSCMsg("/nmx/bandpower/", [bp_ratio])
            print "%i - sending /nmx/bandpower/%i" %(ii, bp_ratio)

        tcurrent = time.time()
        time.sleep(.5)
        told = tcurrent
Esempio n. 17
0
startOSCServer()

# get measurement info guessed by MNE-Python
ch_names = ['EEG-%i' % i for i in np.arange(n_eeg)]
raw_info = mne.create_info(ch_names, sfreq)

with FieldTripClient(info=raw_info,
                     host='localhost',
                     port=1972,
                     tmax=150,
                     wait_max=10) as rt_client:

    tstart = time.time()
    told = tstart
    for ii in range(100):
        epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks)
        filt = band_pass_filter(epoch.get_data(), sfreq, fmin, fmax)
        # compute band power features
        bp = np.log10(np.abs(cwt_morlet(filt[0], sfreq, [(fmin + fmax) / 2.])))
        if told - tstart < baseline:
            bp_base.append(bp[:, 0, n_samples / 2].mean())
        else:
            bp_sample = bp[:, 0, n_samples / 2].mean()
            bp_ratio = (np.mean(bp_base) - bp_sample) / np.mean(bp_base)
            sendOSCMsg("/nmx/bandpower/", [bp_ratio])
            print "%i - sending /nmx/bandpower/%i" % (ii, bp_ratio)

        tcurrent = time.time()
        time.sleep(.5)
        told = tcurrent
Esempio n. 18
0
subject = 1

epochs = mne.read_epochs(data_folder + "sub_%s-epo.fif" % subject)

freqs = np.arange(4, 90, 3)
n_cycles = freqs / 3.

data_target = epochs["Happiness"].get_data()
data_nontarget = epochs["non-target"].get_data()

tfr_target = []
tfr_nontarget = []

for j in range(len(data_target)):
    tfr_target.append(cwt_morlet(data_target[j, :, :],
                                 sfreq=125,
                                 freqs=freqs,
                                 n_cycles=n_cycles))

for j in range(len(data_nontarget)):
    tfr_nontarget.append(cwt_morlet(data_nontarget[j, :, :],
                                    sfreq=125,
                                    freqs=freqs,
                                    n_cycles=n_cycles))

# Convert to numpy arrays
tfr_target = np.asarray(tfr_target)
tfr_nontarget = np.asarray(tfr_nontarget)

# Take power of signal
pow_target = np.abs(tfr_target)**2
pow_nontarget = np.abs(tfr_nontarget)**2