def mne_filter(raw, freqs=None): raw.load_data() if freqs is None: raw.notch_filter(np.arange(50, int(raw.info['sfreq']) + 1, 50), method='spectrum_fit', n_jobs=tb.n_jobs()) elif isinstance(freqs, type([])) and len(freqs) == 2: raw.filter(l_freq=freqs[0], h_freq=freqs[1], n_jobs=tb.n_jobs()) return raw
def mne_eeg_remove_eyeblinks(raw, channels=None, overwrite=False): if channels is None: channels = ['Fp1', 'Fp2'] icafile = tb.fileparts(raw.filenames[0], '-blink_ica.fif') if not pathlib.Path.is_file(pathlib.Path(icafile)) or overwrite: filt_raw = raw.copy() filt_raw.load_data().filter(l_freq=1., h_freq=None, n_jobs=tb.n_jobs()) ica = mne.preprocessing.ICA(n_components=15, random_state=97) ica.fit(filt_raw) ica.exclude = [] eog_indices = [] for ch in channels: eog_index, eog_scores = ica.find_bads_eog( raw, ch_name=ch, reject_by_annotation=True) eog_indices.extend(eog_index) eog_indices = list(set(eog_indices)) ica.exclude = eog_indices if eog_indices: ica.plot_properties(raw, picks=eog_indices) ica.plot_sources(raw) else: ica = mne.preprocessing.read_ica(icafile) clean_raw = raw.copy().load_data() ica.apply(clean_raw) ica.save(tb.fileparts(raw.filenames[0], '-blink_ica.fif')) return clean_raw
def mne_lcmv_template(raw, apply_to=None, fmin=3, fmax=45): # set paths and filenames subject = 'fsaverage' trans = 'fsaverage' # MNE has a built-in fsaverage transformation subjects_dir = mne.get_config('SUBJECTS_DIR') fs_dir = str(pathlib.Path(subjects_dir, 'fsaverage')) src = str(pathlib.Path(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')) bem = str( pathlib.Path(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')) # prepare raw data raw.load_data() raw = mne_filter(raw, [fmin, fmax]) raw = mne_set_1020_montage(raw) raw.interpolate_bads() raw.set_eeg_reference('average', projection=True) # prepare mne beamforming solutions fwd = mne.make_forward_solution(raw.info, trans=trans, src=src, bem=bem, eeg=True, mindist=5.0, n_jobs=tb.n_jobs()) # cov = mne.compute_raw_covariance(raw) # compute before band-pass of interest epochs = mne_epoch(raw, 3.) epochs.load_data() cov = mne.compute_covariance(epochs) filters = mne.beamformer.make_lcmv(raw.info, fwd, cov) # , 0.05, noise_cov=None, pick_ori='max-power', weight_norm='nai') if apply_to is None: raw_lcmv = mne.beamformer.apply_lcmv_raw(raw, filters) else: apply_to = mne_set_1020_montage(apply_to) apply_to.interpolate_bads() apply_to.set_eeg_reference('average', projection=True) raw_lcmv = mne.beamformer.apply_lcmv_raw(apply_to, filters) return raw_lcmv
def mne_burst_analysis(raw, freqranges=None, threshold=50, common_threshold=True, min_length=200, method='wavelet', smoothing=200, common_zscore=True): if freqranges is None: freqranges = {'beta': [13, 30]} csvfile = tb.fileparts(raw.filenames[0], '_bursts.tsv') bdf = pd.DataFrame([]) for fband, frange in freqranges.items(): print(fband) if method == 'hilbert': df = raw.copy().filter(l_freq=frange[0], h_freq=frange[1], n_jobs=tb.n_jobs()).apply_hilbert( envelope=True).to_data_frame() for ch in raw.ch_names: df.loc[:, ch] = df[ch].rolling( axis=0, window=int( smoothing / 1000 * raw.info['sfreq'])).mean().astype('float').interpolate( method='linear', limit_direction='both') sfreq = raw.info['sfreq'] info = raw.info elif method == 'wavelet': wav = mne_tf_wavelet(mne_cont_epoch(raw), freqs=np.arange(frange[0], frange[1] + 1), n_freq=smoothing / 1000 * raw.info['sfreq'], zero_mean=False, n_cycles=10) df = pd.DataFrame(np.squeeze(wav.data.mean(axis=2)).transpose(), columns=raw.ch_names) sfreq = wav.info['sfreq'] info = wav.info if common_zscore: df = (df - df.mean()) / df.std() bursts = OrderedDict() if common_threshold: bthresh = np.percentile(df, threshold) for ch in raw.ch_names: bdata = df.loc[:, ch] if not common_threshold: bthresh = np.percentile(bdata, threshold) bursts.update( {ch: rox_burst_duration(bdata, bthresh, sfreq, min_length)}) bdf.loc[ch, fband + '_threshold'] = bthresh if bursts[ch]['n']: if bursts[ch]['n'] > 10: mdl = stats.fitlm_kfold(bursts[ch]['bdur'], bursts[ch]['bamp'], 5) bdf.loc[ch, fband + '_slope'] = np.mean(mdl[1]) else: bdf.loc[ch, fband + '_slope'] = 0 bdf.loc[ch, fband + '_mdur'] = bursts[ch]['bdur'].mean() bdf.loc[ch, fband + '_n'] = bursts[ch]['n'] / raw._last_time bdf.loc[ch, fband + '_mamp'] = bursts[ch]['bamp'].mean() bdf.loc[ch, fband + '_mpow'] = bdata.mean() else: for s in ['_slope', '_mdur', '_n', '_mamp', '_mpow']: bdf.loc[ch, fband + s] = 0 bdf.to_csv(csvfile, sep='\t') burst_settings = { 'threshold[%]': threshold, 'common_threshold': common_threshold, 'common_zscore': common_zscore, 'sfreq[Hz]': sfreq, 'method': method, 'smoothing[ms]': smoothing, 'min_length[ms]': min_length, 'freqranges[Hz]': freqranges } tb.json_write(tb.fileparts(raw.filenames[0], '_bursts.json'), burst_settings) bdf._metadata = burst_settings return ['df', 'setttings', 'info', 'chanwise'], bdf, burst_settings, info, bursts
def mne_resample(raw, sfreq): raw.load_data() raw.resample(sfreq=sfreq, npad='auto', n_jobs=tb.n_jobs(), events=None) return raw