Пример #1
0
def tfr_multitaper(arr, epochs_mode=False, feature_format=None, **mne_kwargs):
    """
    Extract the Multitaper Time-Frequency spectogram of an array.

    Parameters
    ----------
    arr : np.ndarray
        An (n_times, n_channels) shaped array of EEG data. If epochs_mode is True, the shape must be (n_epochs, n_times, n_channels).
    feature_format :
    epochs_mode : bool
        Whether the input array has the epochs dimension.
    **mne_kwargs
        Other keyword arguments that will be passed to mne.time_frequency.tfr_array_multitaper

    Returns
    -------
    tfr_psd : np.ndarray
        The Time-frequency spectogram of `arr`.
        If feature_format is True, the shape is (n_epochs, n_times, n_chans * n_freqs).
        If feature_format is False, the shape is (n_epochs, n_times, n_chans, n_freqs).

    """
    temp_mne_kwargs = DEFAULT_TRF_KWARGS.copy()
    temp_mne_kwargs.update(mne_kwargs)
    mne_kwargs = temp_mne_kwargs

    # arr is (n_times, n_channels)
    if not epochs_mode:
        assert arr.ndim == 2, "The input array must be of shape (n_times, n_channels)"
        # to (n_channels, n_times)
        arr = np.expand_dims(arr.T, axis=0)
    else:
        assert (
            arr.ndim == 3
        ), "The input array must be of shape (n_epochs, n_times, n_channels)"
        # to (n_epochs, n_channels, n_times)
        arr = arr.transpose(0, 2, 1)

    # input (n_epochs, n_channels, n_times)
    tfr_psd = tfr_array_multitaper(arr, **mne_kwargs)
    # output = (n_epochs, n_chans, n_freqs, n_times)

    if feature_format is None:
        return tfr_psd

    n_epochs, n_chans, n_freqs, n_times = tfr_psd.shape
    if feature_format:
        # (n_epochs, n_chans, n_freqs, n_times) -> (size, features)
        tfr_psd = tfr_psd.transpose(0, 3, 1, 2).reshape(
            n_epochs, n_times, n_chans * n_freqs
        )[:, -n_times:, :]

    else:
        tfr_psd = tfr_psd.transpose(0, 3, 1, 2)[:, :, :, -n_times:]

    tfr_psd = tfr_psd.squeeze() if (n_epochs == 1) else tfr_psd

    return tfr_psd
Пример #2
0
def time_frequency(data: pd.DataFrame, freqs: List[float], method: str = 'morlet', output: str = 'avg_power', **kwargs
                   ) -> np.ndarray:
    """Calculates time-frequency representation for each node.

    Parameters
    ----------
    data
        Simulation results.
    freqs
        Frequencies of interest.
    method
        Method to be used for TFR calculation. Can be `morlet` for `mne.time_frequency.tfr_array_morlet` or
        `multitaper` for `mne.time_frequency.tfr_array_multitaper`.
    output
        Type of the output variable to be calculated. For options, see `mne.time_frequency.tfr_array_morlet`.
    kwargs
        Additional keyword arguments to be passed to the function used for tfr calculation.

    Returns
    -------
    np.ndarray
        Time-frequency representation (n x f x t) for each node (n) at each frequency of interest (f) and time (t).

    """

    if 'time' in data.columns.values:
        idx = data.pop('time')
        data.index = idx

    if method == 'morlet':

        from mne.time_frequency import tfr_array_morlet
        return tfr_array_morlet(np.reshape(data.values.T, (1, data.shape[1], data.shape[0])),
                                sfreq=1./(data.index[1] - data.index[0]),
                                freqs=freqs, output=output, **kwargs)

    elif method == 'multitaper':

        from mne.time_frequency import tfr_array_multitaper
        return tfr_array_multitaper(np.reshape(data.values.T, (1, data.shape[1], data.shape[0])),
                                    sfreq=1. / (data.index[1] - data.index[0]),
                                    freqs=freqs, output=output, **kwargs)
Пример #3
0
dpls = simulate_dipole(net, n_jobs=1, n_trials=1)

###############################################################################
# We can plot the time-frequency response using MNE
import numpy as np
import matplotlib.pyplot as plt
from mne.time_frequency import tfr_array_multitaper

fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
dpls[0].plot(ax=axes[0], layer='agg')

sfreq = 1000. / params['dt']
time_bandwidth = 4.0
freqs = np.arange(20., 100., 1.)
n_cycles = freqs / 4.

# MNE expects an array of shape (n_trials, n_channels, n_times)
data = dpls[0].dpl['agg'][None, None, :]
power = tfr_array_multitaper(data,
                             sfreq=sfreq,
                             freqs=freqs,
                             n_cycles=n_cycles,
                             time_bandwidth=time_bandwidth,
                             output='power')
# stop = params['tstop'] + params['dt'] so last point is included
times = np.arange(0, params['tstop'] + params['dt'], params['dt'])
axes[1].pcolormesh(times, freqs, power[0, 0, ...], cmap='RdBu_r')
axes[1].set_xlabel('Time (ms)')
axes[1].set_ylabel('Frequency (Hz)')
plt.xlim((0, params['tstop']))
Пример #4
0
bem = mne.read_bem_solution(bem_fname)
src = mne.setup_source_space(subject, spacing='ico5',
                             add_dist=False, subjects_dir=subjects_mri_dir)

fwd = mne.make_forward_solution(raw.info, trans=trans_file, src=src, bem=bem, meg=True, eeg=False, n_jobs=2)
inv = mne.minimum_norm.make_inverse_operator(raw.info, fwd, cov, loose=0.2, depth=0.8)

labels = mne.read_labels_from_annot(subject, 'aparc', subjects_dir=subjects_mri_dir)
labels_name = np.array([label.name for label in labels])
stcs = mne.minimum_norm.apply_inverse_epochs(epochs, inv, lambda2=1. / 9., pick_ori='normal', return_generator=True)

label_ts = np.array(mne.extract_label_time_course(stcs, labels, inv['src'], return_generator=False))

psds, freqs = psd_array_multitaper(label_ts, epochs.info['sfreq'], fmin=2, fmax=55)

tfr_alpha = tfr_array_multitaper(label_ts, epochs.info['sfreq'], freqs=np.arange(8, 13), output='avg_power', n_jobs=4)
tfr_beta = tfr_array_multitaper(label_ts, epochs.info['sfreq'], freqs=np.arange(16, 30), output='avg_power', n_jobs=4)
tfr_lgamma = tfr_array_multitaper(label_ts, epochs.info['sfreq'], freqs=np.arange(30, 55), output='avg_power', n_jobs=4)
tfr_hgamma = tfr_array_multitaper(label_ts, epochs.info['sfreq'], freqs=np.arange(65, 100), output='avg_power', n_jobs=4)


for ix, inds in enumerate(np.split(np.arange(68), 4)):
    plt.figure(figsize=(15, 20))
    plt.rc('xtick', labelsize=25)
    plt.rc('ytick', labelsize=25)
    lineObjects = plt.plot(freqs, 20 * np.log10(psds.mean(0).T)[:, inds], linewidth=4)
    plt.xlabel('Frequency (Hz)', fontsize=30)
    plt.ylabel('Power (20*log10)', fontsize=30)
    plt.xlim(2, 55)
    plt.legend(iter(lineObjects), labels_name[inds], fontsize=18)
    plt.grid(True)
Пример #5
0
        #for b, base in enumerate(baseline_idx):
   
            #baseline_chunk_around_event[b,:] = ch_downsampled[base-offset : base+offset]
            #print(b)
            

            
    except Exception:
        continue     
#test = test_epochs[:,:,ch]    

test= None
    
freqs = np.arange(3.0, 100.0, 2.0)    
    
test_tfr = time_frequency.tfr_array_multitaper(test_epochs,sfreq= 1000,freqs = freqs, output= 'avg_power',n_jobs=8)   

norm = np.mean(test_tfr[94,:20,:1000],axis=1)

norm_expanded = np.repeat([norm], offset*2, axis=0).T

ch_test_norm = test_tfr[94,:20,:]/norm_expanded


ch_test = np.log(test_tfr[94,:20,:])
plt.figure()
plt.imshow(np.flipud(ch_test_norm),aspect='auto', cmap='jet')#,vmin=0.4, vmax =1.9)
#plt.axvline(6000,20,color='k')
plt.colorbar()