Example #1
0
def calc_power(subject, epochs, condition=None, label=None, save=True):
    """Calculate induced power and ITC.

    Does TF...

    Parameters
    ----------
    subject : string
        the subject number.
    epochs : ???  # TODO give proper name for epochs file
        the epochs to calculate power from.
    label : string
        restrict to a label.
    condition : string
        the condition to use if there several in the epochs file.
    save : bool
        whether for save the results. Defaults to True.
    """
    frequencies = np.arange(8, 13, 1)  # define frequencies of interest
    n_cycles = frequencies / 3.
    inverse_operator = read_inverse_operator(mne_folder +
                                             "%s-inv.fif" % subject)
    snr = 1.0
    lambda2 = 1.0 / snr**2
    method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

    if condition:
        epochs_test = epochs[condition]
    else:
        epochs_test = epochs

    power, phase_lock = source_induced_power(epochs_test,
                                             inverse_operator,
                                             frequencies,
                                             label=label,
                                             method=method,
                                             lambda2=lambda2,
                                             n_cycles=n_cycles,
                                             use_fft=True,
                                             pick_ori=None,
                                             baseline=(None, -0.3),
                                             baseline_mode='zscore',
                                             pca=True,
                                             n_jobs=2)

    if save:
        np.save(
            tf_folder + "pow_%s_%s-%s_%s_%s_%s.npy" %
            (subject, frequencies[0], frequencies[-1], label.name, condition,
             method), power)
        np.save(
            tf_folder + "itc_%s_%s-%s_%s_%s_%s.npy" %
            (subject, frequencies[0], frequencies[-1], label.name, condition,
             method), phase_lock)

    return power, phase_lock
Example #2
0
def tfr_roi(i, subjects, MRI_sub, roi, freq, n_cycles):
    X = np.zeros([2 * len(roi), len(freq), 600])
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    print('Participant : ', i)

    # morphing ROIs from fsaverage to each individual
    morphed_labels = mne.morph_labels(roi,
                                      subject_to=sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)
    # Reading epochs for SD(n=0)/LD(n=1)
    for n in np.array([0, 1]):
        epo_name = data_path + meg + epochs_names[n]
        epochs = mne.read_epochs(epo_name, preload=True)
        epochs = epochs['words'].resample(500)

        # Reading inverse operator
        inv_fname = data_path + meg + inv_op_name[n]
        inv_op = read_inverse_operator(inv_fname)

        # Computing the power and phase lock value for each ROI
        for j in np.arange(0, len(morphed_labels)):
            print('Participant: ', i, '/ condition: ', n, '/ ROI: ', j)
            power, itc = source_induced_power(epochs,
                                              inverse_operator=inv_op,
                                              freqs=freq,
                                              label=morphed_labels[j],
                                              lambda2=C.lambda2,
                                              method='MNE',
                                              baseline=(-.300, 0),
                                              baseline_mode='percent',
                                              n_jobs=-1,
                                              n_cycles=n_cycles,
                                              zero_mean=True)
            # Averaging across vertices
            # Power
            X[i, n * len(morphed_labels) + j, :, :] = power.copy().mean(0)
    return X
Example #3
0
label = mne.read_label(fname_label)
n_cycles = frequencies / 3.  # different number of cycle per frequency

# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()

import matplotlib.pyplot as plt
plt.close('all')

for ii, (this_epochs, title) in enumerate(
        zip([epochs, epochs_induced], ['evoked + induced', 'induced only'])):
    # compute the source space power and phase lock
    power, phase_lock = source_induced_power(this_epochs,
                                             inverse_operator,
                                             frequencies,
                                             label,
                                             baseline=(-0.1, 0),
                                             baseline_mode='percent',
                                             n_cycles=n_cycles,
                                             n_jobs=1)

    power = np.mean(power, axis=0)  # average over sources
    phase_lock = np.mean(phase_lock, axis=0)  # average over sources
    times = epochs.times

    ##########################################################################
    # View time-frequency plots
    plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.43)
    plt.subplot(2, 2, 2 * ii + 1)
    plt.imshow(20 * power,
               extent=[times[0], times[-1], frequencies[0], frequencies[-1]],
               aspect='auto',
frequencies = np.arange(7, 30, 2)  # define frequencies of interest
label = mne.read_label(fname_label)
n_cycles = frequencies / 3.  # different number of cycle per frequency

# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()

import matplotlib.pyplot as plt
plt.close('all')

for ii, (this_epochs, title) in enumerate(zip([epochs, epochs_induced],
                                              ['evoked + induced',
                                               'induced only'])):
    # compute the source space power and phase lock
    power, phase_lock = source_induced_power(this_epochs, inverse_operator,
        frequencies, label, baseline=(-0.1, 0), baseline_mode='percent',
        n_cycles=n_cycles, n_jobs=1)

    power = np.mean(power, axis=0)  # average over sources
    phase_lock = np.mean(phase_lock, axis=0)  # average over sources
    times = epochs.times

    ##########################################################################
    # View time-frequency plots
    plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.43)
    plt.subplot(2, 2, 2 * ii + 1)
    plt.imshow(20 * power,
               extent=[times[0], times[-1], frequencies[0], frequencies[-1]],
               aspect='auto', origin='lower', vmin=0., vmax=30.)
    plt.xlabel('Time (s)')
    plt.ylabel('Frequency (Hz)')
Example #5
0
def source_induced_power(epochs='epochs', x=None, ds=None, src='ico-4',
                         label=None, sub=None, inv=None, subjects_dir=None,
                         frequencies='4:40:0.1', *args, **kwargs):
    """Compute source induced power and phase locking from mne Epochs

    Parameters
    ----------
    epochs : str | mne.Epochs
        Epochs with sensor space data.
    x : None | str | categorial
        Categories for which to compute power and phase locking (if None the
        grand average is used).
    ds : None | Dataset
        Dataset containing the relevant data objects.
    src : str
        How to handle the source dimension: either a source space (the one on
        which the inverse operator is based, e.g. 'ico-4') or the name of a
        numpy function that reduces the dimensionality (e.g., 'mean').
    label : Label
        Restricts the source estimates to a given label.
    sub : str | index
        Subset of Dataset rows to use.
    inv : None | dict
        The inverse operator (or None if the inverse operator is in
        ``ds.info['inv']``.
    subjects_dir : str
        subjects_dir.
    frequencies : str | array_like
        Array of frequencies of interest. A 'low:high' string is interpreted as
        logarithmically increasing range.
    lambda2 : float
        The regularization parameter of the minimum norm.
    method : "MNE" | "dSPM" | "sLORETA"
        Use mininum norm, dSPM or sLORETA.
    nave : int
        The number of averages used to scale the noise covariance matrix.
    n_cycles : float | array of float
        Number of cycles. Fixed number or one per frequency.
    decim : int
        Temporal decimation factor.
    use_fft : bool
        Do convolutions in time or frequency domain with FFT.
    pick_ori : None | "normal"
        If "normal", rather than pooling the orientations by taking the norm,
        only the radial component is kept. This is only implemented
        when working with loose orientations.
    baseline : None (default) or tuple of length 2
        The time interval to apply baseline correction.
        If None do not apply it. If baseline is (a, b)
        the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used
        and if b is None then b is set to the end of the interval.
        If baseline is equal ot (None, None) all the time
        interval is used.
    baseline_mode : None | 'logratio' | 'zscore'
        Do baseline correction with ratio (power is divided by mean
        power during baseline) or zscore (power is divided by standard
        deviation of power during baseline after subtracting the mean,
        power = [power - mean(power_baseline)] / std(power_baseline)).
    pca : bool
        If True, the true dimension of data is estimated before running
        the time frequency transforms. It reduces the computation times
        e.g. with a dataset that was maxfiltered (true dim is 64). Default is
        False.
    n_jobs : int
        Number of jobs to run in parallel.
    zero_mean : bool
        Make sure the wavelets are zero mean.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see mne.verbose).
    """
    epochs = asepochs(epochs, sub, ds)
    if x is not None:
        x = ascategorial(x, sub, ds)
    if inv is None:
        inv = ds.info.get('inv', None)
    if inv is None:
        msg = ("No inverse operator specified. Either specify the inv "
               "parameter or provide it in ds.info['inv']")
        raise ValueError(msg)

    # set pca to False
    if len(args) < 10 and 'pca' not in kwargs:
        kwargs['pca'] = False

    subject = inv['src'][0]['subject_his_id']
    if label is None:
        vertices = [inv['src'][0]['vertno'], inv['src'][1]['vertno']]
    else:
        vertices, _ = label_src_vertno_sel(label, inv['src'])

    # find frequencies
    if isinstance(frequencies, basestring):
        m = re.match("(\d+):(\d+):([\d.]+)", frequencies)
        if not m:
            raise ValueError("Invalid frequencies parameter: %r" % frequencies)
        low = log(float(m.group(1)))
        high = log(float(m.group(2)))
        step = float(m.group(3))
        frequencies = np.e ** np.arange(low, high, step)
    else:
        frequencies = np.asarray(frequencies)

    # prepare output dimensions
    frequency = Ordered('frequency', frequencies, 'Hz')
    if len(args) >= 5:
        decim = args[4]
    else:
        decim = kwargs.get('decim', 1)
    tmin = epochs.tmin
    tstep = 1. / epochs.info['sfreq'] / decim
    nsamples = int(ceil(float(len(epochs.times)) / decim))
    time = UTS(tmin, tstep, nsamples)
    src_fun = getattr(np, src, None)
    if src_fun is None:
        source = SourceSpace(vertices, subject, src, subjects_dir, None)
        dims = (source, frequency, time)
    else:
        dims = (frequency, time)

    if x is None:
        cells = (None,)
    else:
        cells = x.cells
    shape = (len(cells),) + tuple(len(dim) for dim in dims)
    dims = ('case',) + dims
    p = np.empty(shape)
    pl = np.empty(shape)
    for i, cell in enumerate(cells):
        if cell is None:
            epochs_ = epochs
        else:
            idx = (x == cell)
            epochs_ = epochs[idx]

        p_, pl_ = mn.source_induced_power(epochs_, inv, frequencies, label,
                                          *args, **kwargs)
        if src_fun is None:
            p[i] = p_
            pl[i] = pl_
        else:
            src_fun(p_, axis=0, out=p[i])
            src_fun(pl_, axis=0, out=pl[i])

    out = Dataset()
    out['power'] = NDVar(p, dims)
    out['phase_locking'] = NDVar(pl, dims)
    if x is None:
        pass
    elif isfactor(x):
        out[x.name] = Factor(cells)
    elif isinteraction(x):
        for i, name in enumerate(x.cell_header):
            out[name] = Factor((cell[i] for cell in cells))
    else:
        raise TypeError("x=%s" % repr(x))
    return out
Example #6
0
def source_induced_power(epochs='epochs', x=None, ds=None, src='ico-4',
                         label=None, sub=None, inv=None, subjects_dir=None,
                         frequencies='4:40:0.1', *args, **kwargs):
    """Compute source induced power and phase locking from mne Epochs

    Parameters
    ----------
    epochs : str | mne.Epochs
        Epochs with sensor space data.
    x : None | str | categorial
        Categories for which to compute power and phase locking (if None the
        grand average is used).
    ds : None | Dataset
        Dataset containing the relevant data objects.
    src : str
        How to handle the source dimension: either a source space (the one on
        which the inverse operator is based, e.g. 'ico-4') or the name of a
        numpy function that reduces the dimensionality (e.g., 'mean').
    label : Label
        Restricts the source estimates to a given label.
    sub : str | index
        Subset of Dataset rows to use.
    inv : None | dict
        The inverse operator (or None if the inverse operator is in
        ``ds.info['inv']``.
    subjects_dir : str
        subjects_dir.
    frequencies : str | array_like
        Array of frequencies of interest. A 'low:high' string is interpreted as
        logarithmically increasing range.
    lambda2 : float
        The regularization parameter of the minimum norm.
    method : "MNE" | "dSPM" | "sLORETA"
        Use mininum norm, dSPM or sLORETA.
    nave : int
        The number of averages used to scale the noise covariance matrix.
    n_cycles : float | array of float
        Number of cycles. Fixed number or one per frequency.
    decim : int
        Temporal decimation factor.
    use_fft : bool
        Do convolutions in time or frequency domain with FFT.
    pick_ori : None | "normal"
        If "normal", rather than pooling the orientations by taking the norm,
        only the radial component is kept. This is only implemented
        when working with loose orientations.
    baseline : None (default) or tuple of length 2
        The time interval to apply baseline correction.
        If None do not apply it. If baseline is (a, b)
        the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used
        and if b is None then b is set to the end of the interval.
        If baseline is equal ot (None, None) all the time
        interval is used.
    baseline_mode : None | 'logratio' | 'zscore'
        Do baseline correction with ratio (power is divided by mean
        power during baseline) or zscore (power is divided by standard
        deviation of power during baseline after subtracting the mean,
        power = [power - mean(power_baseline)] / std(power_baseline)).
    pca : bool
        If True, the true dimension of data is estimated before running
        the time frequency transforms. It reduces the computation times
        e.g. with a dataset that was maxfiltered (true dim is 64). Default is
        False.
    n_jobs : int
        Number of jobs to run in parallel.
    zero_mean : bool
        Make sure the wavelets are zero mean.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see mne.verbose).
    """
    epochs = asepochs(epochs, sub, ds)
    if x is not None:
        x = ascategorial(x, sub, ds)
    if inv is None:
        inv = ds.info.get('inv', None)
    if inv is None:
        msg = ("No inverse operator specified. Either specify the inv "
               "parameter or provide it in ds.info['inv']")
        raise ValueError(msg)

    # set pca to False
    if len(args) < 10 and 'pca' not in kwargs:
        kwargs['pca'] = False

    subject = inv['src'][0]['subject_his_id']
    if label is None:
        vertices = [inv['src'][0]['vertno'], inv['src'][1]['vertno']]
    else:
        vertices, _ = label_src_vertno_sel(label, inv['src'])

    # find frequencies
    if isinstance(frequencies, basestring):
        m = re.match("(\d+):(\d+):([\d.]+)", frequencies)
        if not m:
            raise ValueError("Invalid frequencies parameter: %r" % frequencies)
        low = log(float(m.group(1)))
        high = log(float(m.group(2)))
        step = float(m.group(3))
        frequencies = np.e ** np.arange(low, high, step)
    else:
        frequencies = np.asarray(frequencies)

    # prepare output dimensions
    frequency = Ordered('frequency', frequencies, 'Hz')
    if len(args) >= 5:
        decim = args[4]
    else:
        decim = kwargs.get('decim', 1)
    tmin = epochs.tmin
    tstep = 1. / epochs.info['sfreq'] / decim
    nsamples = int(ceil(float(len(epochs.times)) / decim))
    time = UTS(tmin, tstep, nsamples)
    src_fun = getattr(np, src, None)
    if src_fun is None:
        source = SourceSpace(vertices, subject, src, subjects_dir, None)
        dims = (source, frequency, time)
    else:
        dims = (frequency, time)

    if x is None:
        cells = (None,)
    else:
        cells = x.cells
    shape = (len(cells),) + tuple(len(dim) for dim in dims)
    dims = ('case',) + dims
    p = np.empty(shape)
    pl = np.empty(shape)
    for i, cell in enumerate(cells):
        if cell is None:
            epochs_ = epochs
        else:
            idx = (x == cell)
            epochs_ = epochs[idx]

        p_, pl_ = mn.source_induced_power(epochs_, inv, frequencies, label,
                                          *args, **kwargs)
        if src_fun is None:
            p[i] = p_
            pl[i] = pl_
        else:
            src_fun(p_, axis=0, out=p[i])
            src_fun(pl_, axis=0, out=pl[i])

    out = Dataset()
    out['power'] = NDVar(p, dims)
    out['phase_locking'] = NDVar(pl, dims)
    if x is None:
        pass
    elif isfactor(x):
        out[x.name] = Factor(cells)
    elif isinteraction(x):
        for i, name in enumerate(x.cell_header):
            out[name] = Factor((cell[i] for cell in cells))
    else:
        raise TypeError("x=%s" % repr(x))
    return out
# epochs_clt_left = epochs["ctl_left"].copy()
# ind_ent_left = epochs["ent_left"].copy().subtract_evoked()
# ind_clt_left = epochs["ctl_left"].copy().subtract_evoked()
# ind_clt_left = epochs_clt_left.copy().subtract_evoked()

inverse_operator = read_inverse_operator(mne_folder + "%s-inv.fif" % subject)
labels = mne.read_labels_from_annot(subject, parc='PALS_B12_Lobes',
                                    # regexp="Bro",
                                    subjects_dir=subjects_dir)
label = labels[9]


for cond in ["ent_left", "ctl_left"]:
        # compute the source space power and phase lock
    power, phase_lock = source_induced_power(
        epochs[cond], inverse_operator, frequencies, label, baseline=(-0.3, 0.),
        baseline_mode="percent", n_cycles=n_cycles, n_jobs=1, pca=True)

    exec("power_%s = np.mean(power, axis=0)" % cond)  # average over sources
    exec("phase_lock_%s = np.mean(phase_lock, axis=0)" % cond)  # average over sources
    times = epochs.times
    power = np.mean(power, axis=0)
    phase_lock = np.mean(phase_lock, axis=0)

    ##########################################################################
    # View time-frequency plots
    plt.figure()
    plt.imshow(20 * power,
               extent=[times[0], times[-1], frequencies[0], frequencies[-1]],
               aspect='auto', origin='lower', vmin=0., vmax=None, cmap='hot')
    plt.xlabel('Time (s)')
epochs = mne.Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    picks=picks,
                    baseline=(None, 0),
                    reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)

# Compute a source estimate per frequency band
bands = dict(alpha=[9, 11], beta=[18, 22])

stcs = source_induced_power(epochs,
                            inverse_operator,
                            bands,
                            n_cycles=2,
                            use_fft=False,
                            n_jobs=-1)

for b, stc in stcs.iteritems():
    stc.save('induced_power_%s' % b)

###############################################################################
# plot mean power
import pylab as pl

pl.plot(stcs['alpha'].times, stcs['alpha'].data.mean(axis=0), label='Alpha')
pl.plot(stcs['beta'].times, stcs['beta'].data.mean(axis=0), label='Beta')
pl.xlabel('Time (ms)')
pl.ylabel('Power')
pl.legend()
    for label in labels_occ:
        plt.figure()
        epochs_induced = epochs[cond].copy().subtract_evoked()
        for ii, (this_epochs, title) in enumerate(zip([epochs["ent_left_pas_3",
                                                              "ent_left_pas_2"# "ent_left",
                                                              # "ent_right",
                                                              # "ctl_left",
                                                              # "ctl_right"
                                                              ],
                                                       epochs_induced],
                                                      ['evoked + induced',
                                                       'induced only'])):
            # compute the source space power and phase lock
            power, phase_lock = source_induced_power(
                this_epochs, inverse_operator, frequencies, label,
                baseline=(None, 0),
                baseline_mode='zscore', n_cycles=n_cycles, pca=True,
                n_jobs=n_jobs)

            power = np.mean(power, axis=0)  # average over sources
            phase_lock = np.mean(phase_lock, axis=0)  # average over sources
            times = epochs.times

            ###################################################################
            # View time-frequency plots
            plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.43)
            plt.subplot(2, 2, 2 * ii + 1)
            plt.imshow(20 * power,
                       extent=[times[60], times[220],
                               frequencies[0], frequencies[-1]],
                       aspect='auto', origin='lower', cmap='RdBu_r')
    epochs.resample(500, n_jobs=1)
    power_lbl = np.empty([len(labels, ), len(freqs), len(epochs.times)])
    itc_lbl = np.empty([len(labels, ), len(freqs), len(epochs.times)])

    for j, label in enumerate(labels):
        print("\n****************************")
        print("Working on: %s" % label.name)
        print("****************************\n")

        power, itc = source_induced_power(epochs,
                                          inv,
                                          frequencies=freqs,
                                          label=label,
                                          lambda2=lambda2,
                                          method=method,
                                          n_cycles=n_cycles,
                                          decim=1,
                                          pick_ori=None,
                                          baseline=(-3.8, -3.4),
                                          baseline_mode='zscore',
                                          n_jobs=1,
                                          pca=True)
        power_lbl[j] = power.mean(axis=0)
        itc_lbl[j] = itc.mean(axis=0)

    np.save(
        source_folder + "source_TF/%s_%s_source-pow_snr-3.npy" %
        (subject, condition), power_lbl)
    np.save(
        source_folder + "source_TF/%s_%s_source-itc_snr-3.npy" %
        (subject, condition), itc_lbl)
Example #11
0
]
df = pd.DataFrame(columns=columns_keys)

for label in labels_selc:
    for cond in conditions:
        for corr in cor:
            for p in phase:
                for cong in congrunet:
                    for j, side in enumerate(sides):
                        power, itc = source_induced_power(
                            epochs[cond + "/" + side + "/" + cong + "/" +
                                   corr + "/" + p],
                            inv,
                            frequencies,
                            label=label,
                            method=method,
                            pick_ori=None,
                            use_fft=True,
                            # baseline=(-0.2, 0),
                            # baseline_mode='zscore',
                            n_cycles=n_cycles,
                            pca=True,
                            n_jobs=1)
                        np.save(
                            tf_folder +
                            "%s_pow_%s_%s_%s_%s_%s_%s_%s_start.npy" %
                            (subject, cond, side, method, corr, p, cong,
                             label.name), power)
                        np.save(
                            tf_folder +
                            "%s_itc_%s_%s_%s_%s_%s_%s_%s_start.npy" %
                            (subject, cond, side, method, corr, p, cong,
plt.close('all')

for ii, (this_epochs, title) in enumerate(
        zip([epochs, epochs_induced], ['evoked + induced', 'induced only'])):
    # compute the source space power and the inter-trial coherence

    # power, itc = source_induced_power(this_epochs, inverse_operator, \
    #                  freqs,label, lambda2=0.11,method='MNE',\
    #                  baseline=(-.100,0),baseline_mode= 'logratio',\
    #                  use_fft=False, n_jobs=6,n_cycles=n_cycles,zero_mean=True,\
    #                  pca =True)
    power, itc = source_induced_power(this_epochs,
                                      inverse_operator,
                                      freqs,
                                      label,
                                      baseline=(-0.1, 0),
                                      baseline_mode='logratio',
                                      n_cycles=n_cycles,
                                      n_jobs=1)

    power = np.mean(power, axis=0)  # average over sources
    itc = np.mean(itc, axis=0)  # average over sources
    times = epochs.times

    ##########################################################################
    # View time-frequency plots
    plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.43)
    plt.subplot(2, 2, 2 * ii + 1)
    plt.imshow(20 * power,
               extent=[times[0], times[-1], freqs[0], freqs[-1]],
               aspect='auto',
Example #13
0
inverse_operator = read_inverse_operator(mne_folder + "%s-inv.fif" % subject)
src = mne.read_source_spaces(subjects_dir + "%s/bem/%s-oct-6-src.fif" %
                             (subject, subject))
epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject)
# epochs.drop_bad_epochs(reject_params)
epochs.resample(250, n_jobs=n_jobs)

for condition in conditions:
    for label in labels_sel:
        power, itc = source_induced_power(
            epochs[condition],
            inverse_operator,
            frequencies=freqs,
            label=label,
            lambda2=lambda2,
            method=method,
            pick_ori=None,
            baseline=(-0.4, -0.1),
            baseline_mode='ratio',
            n_cycles=n_cycles,
            pca=True,
            n_jobs=n_jobs)

        power = np.mean(power, axis=1)  # average over frequencies
        itc = np.mean(itc, axis=1)  # average over frequencies

        np.save(tf_folder + "%s_%s_%s_%s_%s_source_power_snr_3.npy" %
                (subject, condition[:3], condition[4:], label.name, method),
                power)
        np.save(tf_folder + "%s_%s_%s_%s_%s_source_itc_snr_3.npy" %
                (subject, condition[:3], condition[4:], label.name, method),
# picks MEG gradiometers
picks = fiff.pick_types(raw.info, meg=True, eeg=False, eog=True,
                                stim=False, include=include, exclude=exclude)

# Load condition 1
event_id = 1
events = events[:10]  # take 10 events to keep the computation time low
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)

# Compute a source estimate per frequency band
bands = dict(alpha=[9, 11], beta=[18, 22])

stcs = source_induced_power(epochs, inverse_operator, bands, n_cycles=2,
                            use_fft=False, n_jobs=-1)

for b, stc in stcs.iteritems():
    stc.save('induced_power_%s' % b)

###############################################################################
# plot mean power
import pylab as pl
pl.plot(stcs['alpha'].times, stcs['alpha'].data.mean(axis=0), label='Alpha')
pl.plot(stcs['beta'].times, stcs['beta'].data.mean(axis=0), label='Beta')
pl.xlabel('Time (ms)')
pl.ylabel('Power')
pl.legend()
pl.title('Mean source induced power')
pl.show()
        labels, ), len(freqs), len(epochs.times)])
    itc_lbl = np.empty([len(
        labels, ), len(freqs), len(epochs.times)])

    for j, label in enumerate(labels):
        print("\n****************************")
        print("Working on: %s" % label.name)
        print("****************************\n")

        power, itc = source_induced_power(
            epochs,
            inv,
            frequencies=freqs,
            label=label,
            lambda2=lambda2,
            method=method,
            n_cycles=n_cycles,
            decim=1,
            pick_ori=None,
            baseline=(-3.8, -3.4),
            baseline_mode='zscore',
            n_jobs=1,
            pca=True)
        power_lbl[j] = power.mean(axis=0)
        itc_lbl[j] = itc.mean(axis=0)

    np.save(source_folder + "source_TF/%s_%s_source-pow_snr-3.npy" %
            (subject, condition), power_lbl)
    np.save(source_folder + "source_TF/%s_%s_source-itc_snr-3.npy" %
            (subject, condition), itc_lbl)
Example #16
0
phase = ["in_phase", "out_phase"]
congrunet = ["cong", "incong"]

columns_keys = ["subject", "side", "condition", "phase", "ROI"]
df = pd.DataFrame(columns=columns_keys)

for label in labels_selc:
    for cond in conditions:
        for j, side in enumerate(sides):
            power, itc = source_induced_power(
                epochs[cond + "/" + side],
                inv,
                frequencies,
                label=label,
                method=method,
                pick_ori=None,
                use_fft=True,
                baseline=(-1.4, -1.1),
                baseline_mode='zscore',
                n_cycles=n_cycles,
                pca=True,
                n_jobs=1)
            np.save(tf_folder + "%s_pow_%s_%s_%s_%s_target.npy" %
                    (subject, cond, side, method, label.name), power)
            np.save(tf_folder + "%s_itc_%s_%s_%s_%s_target.npy" %
                    (subject, cond, side, method, label.name), itc)

            n = len(epochs[cond + "/" + side])

            row = pd.DataFrame([{
                "subject": subject,
def calc_power(subject, epochs, condition=None, label=None, save=True):
    """Calculate induced power and ITC.

    Does TF...

    Parameters
    ----------
    subject : string
        the subject number.
    epochs : ???  # TODO give proper name for epochs file
        the epochs to calculate power from.
    label : string
        restrict to a label.
    condition : string
        the condition to use if there several in the epochs file.
    save : bool
        whether for save the results. Defaults to True.
    """
    frequencies = np.arange(8, 13, 1)  # define frequencies of interest
    n_cycles = frequencies / 3.
    inverse_operator = read_inverse_operator(mne_folder +
                                             "%s-inv.fif" % subject)
    snr = 1.0
    lambda2 = 1.0 / snr ** 2
    method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

    if condition:
        epochs_test = epochs[condition]
    else:
        epochs_test = epochs

    power, phase_lock = source_induced_power(epochs_test,
                                             inverse_operator,
                                             frequencies,
                                             label=label,
                                             method=method,
                                             lambda2=lambda2,
                                             n_cycles=n_cycles,
                                             use_fft=True,
                                             pick_ori=None,
                                             baseline=(None, -0.3),
                                             baseline_mode='zscore',
                                             pca=True,
                                             n_jobs=2)

    if save:
        np.save(tf_folder + "pow_%s_%s-%s_%s_%s_%s.npy" % (subject,
                                                           frequencies[0],
                                                           frequencies[-1],
                                                           label.name,
                                                           condition,
                                                           method),
                power)
        np.save(tf_folder + "itc_%s_%s-%s_%s_%s_%s.npy" % (subject,
                                                           frequencies[0],
                                                           frequencies[-1],
                                                           label.name,
                                                           condition,
                                                           method),
                phase_lock)

    return power, phase_lock
Example #18
0
    sub_to = MRI_sub[i][1:15]
    print('Participant : ' , i)

    for n in np.array([0]):
        # Reading epochs
        epo_name= data_path + meg + epochs_names[n]
        epochs = mne.read_epochs(epo_name, preload=True)
        epochs = epochs['words'].crop(-0.300,0.550).resample(500)
    
        # Reading inverse operator
        inv_fname = data_path + meg + inv_op_name[n]
        inv_op = read_inverse_operator(inv_fname) 
       
        print('Participant: ' , i,'/ condition: ',n)
        power, itc = source_induced_power(epochs,inverse_operator=\
                 inv_op, freqs=freq, label=None, lambda2=\
                 C.lambda2, method='MNE', baseline=(-.300,0), baseline_mode=\
                 'percent', n_jobs=6, n_cycles=n_cycles)
        X[i,:,:]  = power.copy().mean(1)
        Y[i,:,:]  = itc.copy().mean(1)

        inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    
        inv_op_SD = read_inverse_operator(inv_fname_SD) 

        morph_SD = mne.compute_source_morph( src= inv_op_SD['src'],subject_from\
                    = sub_to , subject_to = 'fsaverage' , spacing = \
                    C.spacing_morph, subjects_dir = C.data_path)    
      
        
vertices_to = [np.arange(4098), np.arange(4098)]