def _initialize(self): mne_info = self.traverse_back_and_find('mne_info') if self._user_provided_forward_model_file_path is None: self._default_forward_model_file_path = get_default_forward_file( mne_info) self.sender.montage_signal.connect(self._root.reciever.on_montage_error) is_ok = True try: fwd, missing_ch_names = get_clean_forward( self.mne_forward_model_file_path, mne_info) except ValueError as ve: if len(ve.args) == 3: self.sender.montage_signal.emit(ve.args) is_ok = False else: raise Exception('BAD FORWARD + DATA COMBINATION!') if is_ok: mne_info['bads'] = list(set(mne_info['bads'] + missing_ch_names)) self._gain_matrix = fwd['sol']['data'] G = self._gain_matrix if self.is_adaptive is False: Rxx = G.dot(G.T) elif self.is_adaptive is True: Rxx = np.zeros([G.shape[0], G.shape[0]]) # G.dot(G.T) goods = mne.pick_types(mne_info, eeg=True, meg=False, exclude='bads') ch_names = [mne_info['ch_names'][i] for i in goods] self._Rxx = mne.Covariance(Rxx, ch_names, mne_info['bads'], mne_info['projs'], nfree=1) self.noise_cov = mne.Covariance(G.dot(G.T), ch_names, mne_info['bads'], mne_info['projs'], nfree=1) self._mne_info = mne_info frequency = mne_info['sfreq'] self._forgetting_factor_per_sample = np.power( self.forgetting_factor_per_second, 1 / frequency) n_vert = fwd['nsource'] channel_labels = ['vertex #{}'.format(i + 1) for i in range(n_vert)] self.mne_info = mne.create_info(channel_labels, frequency) self._initialized_as_adaptive = self.is_adaptive self._initialized_as_fixed = self.fixed_orientation self.fwd_surf = mne.convert_forward_solution( fwd, surf_ori=True, force_fixed=False) if not self.is_adaptive: self._filters = make_lcmv( info=self._mne_info, forward=self.fwd_surf, data_cov=self._Rxx, reg=self.reg, pick_ori='max-power', weight_norm='unit-noise-gain', reduce_rank=False) else: self._filters = None print('beamformer nchan',self.mne_info['nchan'])
def make_inverse_operator(fwd, mne_info, sigma2=1): # sigma2 is what will be used to scale the identity covariance matrix. # This will not affect MNE solution though. # The inverse operator will use channels common to # forward_model_file_path and mne_info. picks = mne.pick_types(mne_info, eeg=True, meg=False, exclude='bads') info_goods = mne.pick_info(mne_info, sel=picks) N_SEN = fwd['nchan'] ch_names = info_goods['ch_names'] cov_data = np.identity(N_SEN) cov = mne.Covariance(cov_data, ch_names, mne_info['bads'], mne_info['projs'], nfree=1) inv = mne.minimum_norm.make_inverse_operator(info_goods, fwd, cov, depth=None, loose=0, fixed=True, verbose='ERROR') return inv
def _update_covariance_matrix(self, input_array): t1 = time.time() alpha = self._forgetting_factor_per_sample sample_count = input_array.shape[TIME_AXIS] self.logger.debug('Number of samples: {}'.format(sample_count)) new_Rxx_data = self._Rxx.data raw_array = mne.io.RawArray(input_array, self._mne_info, verbose='ERROR') raw_array.pick_types(eeg=True, meg=False, stim=False, exclude='bads') raw_array.set_eeg_reference(ref_channels='average', projection=True) input_array_nobads = raw_array.get_data() t2 = time.time() self.logger.debug('Prepared covariance update in {:.2f} ms'.format( (t2 - t1) * 1000)) samples = make_time_dimension_second(input_array_nobads).T new_Rxx_data = (alpha * new_Rxx_data + (1 - alpha) * samples.T.dot(samples)) t3 = time.time() self.logger.debug('Updated matrix data in {:.2f} ms'.format( (t3 - t2) * 1000)) self._Rxx = mne.Covariance(new_Rxx_data, self._Rxx.ch_names, raw_array.info['bads'], raw_array.info['projs'], nfree=1) t4 = time.time() self.logger.debug('Created instance of covariance' + ' in {:.2f} ms'.format((t4 - t4) * 1000))
def make_inverse_operator(fwd, mne_info, depth=None, loose=1, fixed=False): """ Make noise covariance matrix and create inverse operator using only good channels """ # The inverse operator will use channels common to # forward_model_file_path and mne_info. picks = mne.pick_types(mne_info, eeg=True, meg=False, exclude='bads') info_goods = mne.pick_info(mne_info, sel=picks) N_SEN = fwd['nchan'] ch_names = info_goods['ch_names'] cov_data = np.identity(N_SEN) cov = mne.Covariance(cov_data, ch_names, mne_info['bads'], mne_info['projs'], nfree=1) inv = mne.minimum_norm.make_inverse_operator(info_goods, fwd, cov, depth=None, loose=0.8, fixed=False, verbose='ERROR') return inv
def test_whitening_cov(): """Whitening of evoked data and leadfields """ data_path = sample.data_path('.') ave_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') cov_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') # Reading evoked = read_evoked(ave_fname, setno=0, baseline=(None, 0)) cov = mne.Covariance(cov_fname) cov.get_whitener(evoked.info)
def test_cov_estimation_on_raw_segment(): """Estimate raw on continuous recordings (typically empty room) """ raw = Raw(raw_fname) cov = mne.compute_raw_data_covariance(raw) cov_mne = mne.Covariance(erm_cov_fname) assert cov_mne.ch_names == cov.ch_names print( linalg.norm(cov.data - cov_mne.data, ord='fro') / linalg.norm(cov.data, ord='fro')) assert (linalg.norm(cov.data - cov_mne.data, ord='fro') / linalg.norm(cov.data, ord='fro')) < 1e-6
def dipolarity_using_sphere_model(A, inst, picks, head_radius=0.085, n_jobs=1): # head_radius must be in meters ! n_channels = inst.info['nchan'] ch_names = inst.info['ch_names'] cov = mne.Covariance(np.eye(n_channels), ch_names, bads=[], projs=[], nfree=1) # project the electrodes to the outer sphere pos = np.array([c['loc'][:3] for c in inst.info['chs']]) pos /= np.sqrt(np.sum(pos**2, axis=1))[:, None] pos *= head_radius kind = "eeglab" selection = np.arange(n_channels) montage = mne.channels.Montage(pos, ch_names, kind, selection) inst.set_montage(montage) # # # Specify the eog channels # inst.set_channel_types({'LEYE': 'eog', 'REYE': 'eog'}) # eeglab: # EEG.dipfit.vol # r: [71 72 79 85] # c: [0.3300 1 0.0042 0.3300] # o: [0 0 0] # # XXX : try auto mode # sphere = mne.make_sphere_model(r0='auto', # head_radius='auto', # relative_radii=[0.8353, 0.847, 0.93, 1], # sigmas=(0.33, 1.0, 0.0042, 0.33), # info=info) sphere = mne.make_sphere_model(r0=(0.0, 0.0, 0.0), head_radius=head_radius, relative_radii=[0.8353, 0.847, 0.93, 1], sigmas=(0.33, 1.0, 0.0042, 0.33)) new_info = mne.pick_info(inst.info, sel=picks) gof, dip, evoked = dipolarity(A, new_info, cov, sphere, fname_trans=None, min_dist=1, verbose=False, n_jobs=n_jobs) return gof, dip, evoked, sphere
def content(self): if self._content: return self._content cov = read_cov(self._path) # read_cov cannot handle the ad hoc cov.. fixed_cov = mne.Covariance(cov['data'].astype(np.float64), cov['names'], cov['bads'], cov['projs'], cov['nfree']) self._content = fixed_cov return self._content
def _initialize(self): print('INITIALIZING MCE NODE ...') mne_info = self.traverse_back_and_find('mne_info') # mne_info['custom_ref_applied'] = True # -------- truncated svd for fwd_opr operator -------- # fwd, missing_ch_names = get_clean_forward( self.mne_forward_model_file_path, mne_info) mne_info['bads'] = list(set(mne_info['bads'] + missing_ch_names)) fwd_fix = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=False) self._gain_matrix = fwd_fix['sol']['data'] print('MCE: COMPUTING SVD OF THE FORWARD OPERATOR') U, S, V = svd(self._gain_matrix) Sn = np.zeros([self.n_comp, V.shape[0]]) Sn[:self.n_comp, :self.n_comp] = np.diag(S[:self.n_comp]) self.Un = U[:, :self.n_comp] self.A_non_ori = Sn @ V # ---------------------------------------------------- # # -------- leadfield dims -------- # N_SEN = self._gain_matrix.shape[0] # -------------------------------- # # ------------------------ noise-covariance ------------------------ # cov_data = np.identity(N_SEN) ch_names = np.array(mne_info['ch_names'])[mne.pick_types(mne_info, eeg=True, meg=False)] ch_names = list(ch_names) noise_cov = mne.Covariance(cov_data, ch_names, mne_info['bads'], mne_info['projs'], nfree=1) # ------------------------------------------------------------------ # self.mne_inv = mne_make_inverse_operator(mne_info, fwd_fix, noise_cov, depth=0.8, loose=1, fixed=False, verbose='ERROR') self.mne_info = mne_info self.Sn = Sn self.V = V
def make_inverse_operator(forward_model_file_path, mne_info, sigma2=1): # sigma2 is what will be used to scale the identity covariance matrix. This will not affect the MNE solution though. # The inverse operator will use channels common to forward_model_file_path and mne_info. forward = mne.read_forward_solution(forward_model_file_path, verbose='ERROR') cov = mne.Covariance(data=sigma2 * np.identity(mne_info['nchan']), names=mne_info['ch_names'], bads=mne_info['bads'], projs=mne_info['projs'], nfree=1) return mne.minimum_norm.make_inverse_operator(mne_info, forward, cov, verbose='ERROR')
def _initialize(self): mne_info = self.traverse_back_and_find('mne_info') # mne_info['custom_ref_applied'] = True # -------- truncated svd for fwd_opr operator -------- # fwd, missing_ch_names = get_clean_forward( self.mne_forward_model_file_path, mne_info) mne_info['bads'] = list(set(mne_info['bads'] + missing_ch_names)) fwd_fix = mne.convert_forward_solution( fwd, surf_ori=True, force_fixed=False) self._gain_matrix = fwd_fix['sol']['data'] self.logger.info('Computing SVD of the forward operator') U, S, V = svd(self._gain_matrix) Sn = np.zeros([self.n_comp, V.shape[0]]) Sn[:self.n_comp, :self.n_comp] = np.diag(S[:self.n_comp]) self.Un = U[:, :self.n_comp] self.A_non_ori = Sn @ V # ---------------------------------------------------- # # -------- leadfield dims -------- # N_SEN = self._gain_matrix.shape[0] # -------------------------------- # # ------------------------ noise-covariance ------------------------ # cov_data = np.identity(N_SEN) ch_names = np.array(mne_info['ch_names'])[mne.pick_types(mne_info, eeg=True, meg=False)] ch_names = list(ch_names) noise_cov = mne.Covariance( cov_data, ch_names, mne_info['bads'], mne_info['projs'], nfree=1) # ------------------------------------------------------------------ # self.mne_inv = mne_make_inverse_operator( mne_info, fwd_fix, noise_cov, depth=0.8, loose=1, fixed=False, verbose='ERROR') self._mne_info = mne_info self.Sn = Sn self.V = V channel_count = fwd['nsource'] channel_labels = ['vertex #{}'.format(i + 1) for i in range(channel_count)] self.mne_info = mne.create_info(channel_labels, mne_info['sfreq'])
def compute_cov_identity(raw_filename): "Compute Identity Noise Covariance matrix." raw = read_raw_fif(raw_filename) data_path, basename, ext = split_f(raw_filename) cov_fname = op.join(data_path, 'identity_noise-cov.fif') if not op.isfile(cov_fname): picks = pick_types(raw.info, meg=True, ref_meg=False, exclude='bads') ch_names = [raw.info['ch_names'][k] for k in picks] bads = [b for b in raw.info['bads'] if b in ch_names] noise_cov = mne.Covariance(np.identity(len(picks)), ch_names, bads, raw.info['projs'], nfree=0) write_cov(cov_fname, noise_cov) return cov_fname
def test_cov_estimation_with_triggers(): """Estimate raw with triggers """ raw = Raw(raw_fname) events = mne.find_events(raw) event_ids = [1, 2, 3, 4] cov = mne.compute_covariance(raw, events, event_ids, tmin=-0.2, tmax=0, reject=dict(grad=10000e-13, mag=4e-12, eeg=80e-6, eog=150e-6), keep_sample_mean=True) cov_mne = mne.Covariance(cov_fname) assert cov_mne.ch_names == cov.ch_names assert (linalg.norm(cov.data - cov_mne.data, ord='fro') / linalg.norm(cov.data, ord='fro')) < 0.05
def read_noise_cov(cov_fname, raw_info): """Read a noise covariance matrix from cov_fname. Parameters ---------- cov_fname : str noise covariance file name raw_info : dict dictionary containing the information about the raw data Returns ------- noise_cov : Covariance the noise covariance matrix """ import os.path as op import numpy as np import mne print(('***** READ RAW COV *****' + cov_fname)) if not op.isfile(cov_fname): # create an Identity matrix picks = mne.pick_types(raw_info, meg=True, ref_meg=False, exclude='bads') ch_names = [raw_info['ch_names'][i] for i in picks] c = mne.Covariance(data=np.identity(len(picks)), names=ch_names, bads=[], projs=[], nfree=0) mne.write_cov(cov_fname, c) else: print(('*** noise covariance file %s exists!!!' % cov_fname)) noise_cov = mne.read_cov(cov_fname) return noise_cov
def dipolarity(mixing, inst, picks, fname_bem=None, fname_trans=None, min_dist=5, n_jobs=1, verbose=None): n_channels = inst.info['nchan'] ch_names = inst.info['ch_names'] cov = mne.Covariance(np.eye(n_channels), ch_names, bads=[], projs=[], nfree=1) if fname_bem is None: head_radius = 0.085 pos = np.array([c['loc'][:3] for c in inst.info['chs']]) pos /= np.sqrt(np.sum(pos**2, axis=1))[:, None] pos *= head_radius kind = "eeglab" selection = np.arange(n_channels) montage = mne.channels.Montage(pos, ch_names, kind, selection) inst.set_montage(montage) inst.set_channel_types({'LEYE': 'eog', 'REYE': 'eog'}) fname_bem =\ mne.make_sphere_model(r0=(0.0, 0.0, 0.0), head_radius=head_radius, relative_radii=[0.8353, 0.847, 0.93, 1], sigmas=(0.33, 1.0, 0.0042, 0.33)) picks = mne.pick_types(inst.info, eeg=True, eog=False) info = mne.pick_info(inst.info, sel=picks) evoked = mne.EvokedArray(mixing, info, tmin=0, comment='ICA components') info['projs'] = [] # get rid of SSP projections if 'eeg' in evoked: evoked = evoked.copy() avg_proj = mne.io.make_eeg_average_ref_proj(evoked.info) evoked.add_proj([avg_proj]) evoked.apply_proj() dip, residual = mne.fit_dipole(evoked, cov, fname_bem, fname_trans, min_dist=min_dist, verbose=verbose, n_jobs=n_jobs) gof = (1. - np.sum(residual.data**2, axis=0) / np.sum(evoked.data**2, axis=0)) gof = 100. * gof # Scale the gof between 0 and 100 # if some gof is NaN, raise an Error if np.sum(np.isnan(gof)) > 0: raise ValueError('ERROR!, some gof are NaN. This usually happens ' 'because some dipoles position resulting to be too ' 'close to the inner sphere. To solve this issue, ' 'consider using a different value for the min_dist ' 'parameter.') # Do not sort the columns of A, neither the gof, this way is easier to # mantain the one-to-one correspondence between the columns of A and the # the measures associated to them (gof, depth, radiality, etc) # idx_sort_desc = np.argsort(gof)[::-1] # evoked.data = evoked.data[:, idx_sort_desc] # gof = gof[idx_sort_desc] return gof, dip, evoked
meg=False, eeg=True, stim=False, eog=True, exclude=exclude) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(eeg=40e-6, eog=150e-6)) evoked = epochs.average() # average epochs and get an Evoked dataset. cov = mne.Covariance(cov_fname) # Whiten data whitener = cov.get_whitener(evoked.info, pca=False) # get whitening matrix sel = mne.fiff.pick_channels(evoked.ch_names, include=whitener.ch_names) whitened_data = np.dot(whitener.W, evoked.data[sel]) # apply whitening ############################################################################### # Show result times = 1e3 * epochs.times # in ms import pylab as pl pl.clf() pl.plot(times, whitened_data.T) pl.xlim([times[0], times[-1]]) pl.xlabel('time (ms)')
import os.path as op import numpy as np import mne data_path = mne.datasets.brainstorm.bst_resting.data_path() subjects_dir = op.join(data_path, 'subjects') subject = 'bst_resting' trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif') src = op.join(subjects_dir, subject, 'bem', subject + '-oct-6-src.fif') fname_bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif') raw_fname = op.join(data_path, 'MEG', 'bst_resting', 'subj002_spontaneous_20111102_01_AUX.ds') raw = mne.io.read_raw_ctf(raw_fname, preload=True) picks = mne.pick_types(raw.info, meg='mag', eeg=False) n_channels = raw.info['nchan'] ch_names = raw.info['ch_names'] cov = mne.Covariance(np.eye(n_channels), ch_names, bads=[], projs=[], nfree=1) info = mne.pick_info(raw.info, sel=picks) evoked = mne.EvokedArray(np.ones((info['nchan'], 1)), info, tmin=0) mne.fit_dipole(evoked, cov, fname_bem, min_dist=5)
""" ========================================= Reading/Writing a noise covariance matrix ========================================= """ # Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print __doc__ import mne from mne.datasets import sample data_path = sample.data_path('.') fname = data_path + '/MEG/sample/sample_audvis-cov.fif' cov = mne.Covariance(fname) print cov ############################################################################### # Show covariance import pylab as pl pl.matshow(cov.data) pl.title('Noise covariance matrix (%d channels)' % cov.data.shape[0]) pl.show()
import os.path as op import numpy as np import matplotlib.pyplot as plt import mne import config_drago as cfg info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg='mag') fname = op.join(cfg.path_outputs, 'covs_allch_oas.h5') data = mne.externals.h5io.read_hdf5(fname) # (sub, fb, ch, ch) subjects = [d['subject'] for d in data if 'subject' in d] covs = [d['covs'][:, picks][:, :, picks] for d in data if 'subject' in d] covs = np.array(covs) # (sub,fb,chan,chan) ranks = [] for sub in range(len(subjects)): cov = mne.Covariance(covs[sub][4], np.array(info['ch_names'])[picks], [], [], 1) ranks.append(mne.compute_rank(cov, info=info)['mag']) plt.figure() plt.hist(ranks)
data = 0 n_samples = 0 mu = 0 for first in range(start, stop, step): last = first + step if last >= stop: last = stop raw_segment = raw_data[:, first:last] mu += raw_segment.sum(axis=1) data += np.dot(raw_segment, raw_segment.T) n_samples += raw_segment.shape[1] mu /= n_samples data -= n_samples * mu[:, None] * mu[None, :] data /= (n_samples - 1.0) ch_names = [raw.info['ch_names'][k] for k in picks] data_cov = mne.Covariance(None) data_cov.update(kind=mne.fiff.FIFF.FIFFV_MNE_NOISE_COV, diag=False, dim=len(data), names=ch_names, data=data, projs=cp.deepcopy(raw.info['projs']), bads=raw.info['bads'], nfree=n_samples, eig=None, eigvec=None) noise_cov = mne.compute_raw_data_covariance(er_raw) # note that MNE reads CTF data as magnetometers! noise_cov = mne.cov.regularize(noise_cov, raw.info, mag=noise_reg) events = fg.get_good_events(markers[subj], time, window_length)
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape) n_sen = leadfield.shape[0] # forward}}} # # compute {{{inverse # snr = 1 # use smaller SNR for raw data inv_method = 'MNE' # sLORETA, MNE, dSPM # inv_method = 'dSPM' # sLORETA, MNE, dSPM parc = 'aparc' # the parcellation to use, e.g., 'aparc' 'aparc.a2009s' lambda2 = 1.0 / snr ** 2 # lambda2 = 0.1 # cov_data = np.eye(n_sen) * 1e-12 cov_data = np.identity(n_sen) noise_cov = mne.Covariance(cov_data, raw.info['ch_names'], raw.info['bads'], raw.info['projs'], nfree=1) # noise_cov = mne.compute_raw_covariance(raw, tmin=0, tmax=29, method='shrunk') inverse_operator = make_inverse_operator(raw.info, fwd, noise_cov, depth=0.8, loose=1, fixed=False) # inverse_operator = make_inverse_operator(raw.info, fwd, noise_cov, depth=None, loose=1, fixed=False) # inverse {{{cogni # # inv_cogni_path = op.join(data_path, 'inv_mat.npy') # inv_cogni = np.load(file=inv_cogni_path) # cogni}}} # # inverse}}} # # start, stop = raw.time_as_index([75,85]) start, stop = raw.time_as_index([0,29.9]) # {{{ apply inverse # raw_c = raw.copy()
1e6 * (glm_est['Simulated'].theta[0] - amp * 1e-6)) ############################################################################### # Simulate noisy NIRS data (colored) # ---------------------------------- # # Here we add colored noise which better matches what is seen with real data. # Again, the same GLM procedure is run. # The estimate is reported below, and even though the signal was difficult to # observe in the raw data, the GLM analysis has extracted an accurate estimate. # However, the error is greater for the colored than white noise. raw = raw_noise_free.copy() cov = mne.Covariance(np.ones(1) * 1e-11, raw.ch_names, raw.info['bads'], raw.info['projs'], nfree=0) raw = mne.simulation.add_noise(raw, cov, iir_filter=[ 1., -0.58853134, -0.29575669, -0.52246482, 0.38735476, 0.02428681 ]) design_matrix = make_first_level_design_matrix(raw, stim_dur=5.0, drift_order=1, drift_model='polynomial') glm_est = run_GLM(raw, design_matrix) plt.plot(raw.times, raw_noise_free.get_data().T * 1e6)
raw.filter(l_freq=8, h_freq=12) raw.set_eeg_reference(projection=True) # Construct inverse, apply info = raw.info G = fwd['sol']['data'] q = 1 # q = np.trace(G.dot(G.T)) / G.shape[0] # picks = mne.pick_types(info, eeg=True, meg=False) # q *= np.mean(np.var(raw.get_data(picks=picks))) cov = mne.Covariance( data=(q * np.identity( info['nchan'])), # "whitened" G.dot(G.T) and cov now have one scale names=info['ch_names'], bads=info['bads'], projs=info['projs'], nfree=0) # cov = mne.make_ad_hoc_cov(info, verbose='ERROR') inv = mne.minimum_norm.make_inverse_operator(info, fwd, cov, depth=0.5, verbose='ERROR') start, stop = raw.time_as_index((80, 100)) stc = mne.minimum_norm.apply_inverse_raw(raw, start=start, stop=stop, inverse_operator=inv,