def sources_to_labels(stcs, age=None, template=None, parc='aparc', mode='mean_flip', allow_empty=True, return_generator=False, subjects_dir=None, include_vol_src=True): template = __validate_template__(age, template, subjects_dir) montage, trans, bem_model, bem_solution, src = get_bem_artifacts( template, subjects_dir=subjects_dir, include_vol_src=include_vol_src) labels_parc = mne.read_labels_from_annot(template, subjects_dir=subjects_dir, parc=parc) labels_ts = mne.extract_label_time_course( stcs, labels_parc, src, mode=mode, allow_empty=allow_empty, return_generator=return_generator) if include_vol_src: labels_aseg = mne.get_volume_labels_from_src(src, template, subjects_dir) labels = labels_parc + labels_aseg else: labels = labels_parc return labels_ts, labels
def _compute_mean_ROIs(stc, sbj_id, subjects_dir, parc, inverse_operator, forward, aseg, is_fixed): # these coo are in MRI space and we have to convert them to MNI space labels_cortex = mne.read_labels_from_annot(sbj_id, parc=parc, subjects_dir=subjects_dir) print(('\n*** %d ***\n' % len(labels_cortex))) src = inverse_operator['src'] # allow_empty : bool -> Instead of emitting an error, return all-zero time # courses for labels that do not have any vertices in the source estimate if is_fixed: mode = 'mean_flip' else: mode = 'mean' label_ts = mne.extract_label_time_course(stc, labels_cortex, src, mode=mode, allow_empty=True, return_generator=False) # save results in .npy file that will be the input for spectral node print('\n*** SAVE ROI TS ***\n') print((len(label_ts))) if aseg: print(sbj_id) labels_aseg = get_volume_labels_from_src(src, sbj_id, subjects_dir) labels = labels_cortex + labels_aseg else: labels = labels_cortex labels_aseg = None print((labels[0].pos)) print((len(labels))) labels_file, label_names_file, label_coords_file = \ _create_MNI_label_files(forward, labels_cortex, labels_aseg, sbj_id, subjects_dir) return label_ts, labels_file, label_names_file, label_coords_file
fmin = 8. fmax = 13. sfreq = raw.info['sfreq'] # the sampling frequency con, freqs, times, n_epochs, n_tapers = spectral_connectivity( label_ts, method='pli', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=1) # We create a list of Label containing also the sub structures labels_aseg = mne.get_volume_labels_from_src(src, subject, subjects_dir) labels = labels_parc + labels_aseg # read colors node_colors = [label.color for label in labels] # We reorder the labels based on their location in the left hemi label_names = [label.name for label in labels] lh_labels = [name for name in label_names if name.endswith('lh')] rh_labels = [name for name in label_names if name.endswith('rh')] # Get the y-location of the label label_ypos_lh = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1])
label_ts = mne.extract_label_time_course(stcs, labels_parc, src, mode='mean_flip', allow_empty=True, return_generator=False) # We compute the connectivity in the alpha band and plot it using a circular # graph layout fmin = 8. fmax = 13. sfreq = raw.info['sfreq'] # the sampling frequency con, freqs, times, n_epochs, n_tapers = spectral_connectivity( label_ts, method='pli', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=1) # We create a list of Label containing also the sub structures labels_aseg = mne.get_volume_labels_from_src(src, subject, subjects_dir) labels = labels_parc + labels_aseg # read colors node_colors = [label.color for label in labels] # We reorder the labels based on their location in the left hemi label_names = [label.name for label in labels] lh_labels = [name for name in label_names if name.endswith('lh')] rh_labels = [name for name in label_names if name.endswith('rh')] # Get the y-location of the label label_ypos_lh = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1])
def compute_rois_inv_sol(raw_filename, sbj_id, sbj_dir, fwd_filename, cov_fname, is_epoched=False, events_id=[], t_min=None, t_max=None, is_evoked=False, snr=1.0, inv_method='MNE', parc='aparc', aseg=False, aseg_labels=[], save_stc=False, is_fixed=False): """Compute the inverse solution on raw/epoched data. This function return the average time series computed in the N_r regions of the source space defined by the specified cortical parcellation Parameters ---------- raw_filename : str filename of the raw/epoched data sbj_id : str subject name sbj_dir : str Freesurfer directory fwd_filename : str filename of the forward operator cov_filename : str filename of the noise covariance matrix is_epoched : bool if True and events_id = None the input data are epoch data in the format -epo.fif if True and events_id is not None, the raw data are epoched according to events_id and t_min and t_max values events_id: dict the dict of events t_min, t_max: int define the time interval in which to epoch the raw data is_evoked: bool if True the raw data will be averaged according to the events contained in the dict events_id inv_method : str the inverse method to use; possible choices: MNE, dSPM, sLORETA snr : float the SNR value used to define the regularization parameter parc: str the parcellation defining the ROIs atlas in the source space aseg: bool if True a mixed source space will be created and the sub cortical regions defined in aseg_labels will be added to the source space aseg_labels: list list of substructures we want to include in the mixed source space save_stc: bool if True the stc will be saved Returns ------- ts_file : str filename of the file where are saved the ROIs time series labels_file : str filename of the file where are saved the ROIs of the parcellation label_names_file : str filename of the file where are saved the name of the ROIs of the parcellation label_coords_file : str filename of the file where are saved the coordinates of the centroid of the ROIs of the parcellation """ import os.path as op import numpy as np import mne from mne.io import read_raw_fif from mne import read_epochs from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from mne.minimum_norm import apply_inverse_epochs, apply_inverse from mne import get_volume_labels_from_src from nipype.utils.filemanip import split_filename as split_f from ephypype.preproc import create_reject_dict from ephypype.source_space import create_mni_label_files try: traits.undefined(events_id) except NameError: events_id = None print(('\n*** READ raw filename %s ***\n' % raw_filename)) if is_epoched and events_id is None: epochs = read_epochs(raw_filename) info = epochs.info else: raw = read_raw_fif(raw_filename, preload=True) # raw.set_eeg_reference() info = raw.info subj_path, basename, ext = split_f(raw_filename) print(('\n*** READ noise covariance %s ***\n' % cov_fname)) noise_cov = mne.read_cov(cov_fname) print(('\n*** READ FWD SOL %s ***\n' % fwd_filename)) forward = mne.read_forward_solution(fwd_filename) if not aseg: print(('\n*** fixed orientation {} ***\n'.format(is_fixed))) forward = mne.convert_forward_solution(forward, surf_ori=True, force_fixed=is_fixed) lambda2 = 1.0 / snr**2 # compute inverse operator print('\n*** COMPUTE INV OP ***\n') if is_fixed: loose = None depth = None pick_ori = None elif aseg: loose = 1 depth = None pick_ori = None else: loose = 0.2 depth = 0.8 pick_ori = 'normal' print(('\n *** loose {} depth {} ***\n'.format(loose, depth))) inverse_operator = make_inverse_operator(info, forward, noise_cov, loose=loose, depth=depth, fixed=is_fixed) # apply inverse operator to the time windows [t_start, t_stop]s print('\n*** APPLY INV OP ***\n') if is_epoched and events_id is not None: events = mne.find_events(raw) picks = mne.pick_types(info, meg=True, eog=True, exclude='bads') reject = create_reject_dict(info) if is_evoked: epochs = mne.Epochs(raw, events, events_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) evoked = [epochs[k].average() for k in events_id] snr = 3.0 lambda2 = 1.0 / snr**2 ev_list = list(events_id.items()) for k in range(len(events_id)): stc = apply_inverse(evoked[k], inverse_operator, lambda2, inv_method, pick_ori=pick_ori) print(('\n*** STC for event %s ***\n' % ev_list[k][0])) stc_file = op.abspath(basename + '_' + ev_list[k][0]) print('***') print(('stc dim ' + str(stc.shape))) print('***') if not aseg: stc.save(stc_file) else: epochs = mne.Epochs(raw, events, events_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=pick_ori) print('***') print(('len stc %d' % len(stc))) print('***') elif is_epoched and events_id is None: stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=pick_ori) print('***') print(('len stc %d' % len(stc))) print('***') else: stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method, label=None, start=None, stop=None, buffer_size=1000, pick_ori=pick_ori) # None 'normal' print('***') print(('stc dim ' + str(stc.shape))) print('***') if not isinstance(stc, list): stc = [stc] if save_stc: for i in range(len(stc)): stc_file = op.abspath(basename + '_stc_' + str(i) + '.npy') np.save(stc_file, stc[i].data) # these coo are in MRI space and we have to convert to MNI space labels_cortex = mne.read_labels_from_annot(sbj_id, parc=parc, subjects_dir=sbj_dir) print(('\n*** %d ***\n' % len(labels_cortex))) src = inverse_operator['src'] # allow_empty : bool -> Instead of emitting an error, return all-zero time # courses for labels that do not have any vertices in the source estimate if is_fixed: mode = 'mean_flip' else: mode = 'mean' label_ts = mne.extract_label_time_course(stc, labels_cortex, src, mode=mode, allow_empty=True, return_generator=False) # save results in .npy file that will be the input for spectral node print('\n*** SAVE ROI TS ***\n') print((len(label_ts))) ts_file = op.abspath(basename + '_ROI_ts.npy') np.save(ts_file, label_ts) if aseg: print(sbj_id) labels_aseg = get_volume_labels_from_src(src, sbj_id, sbj_dir) labels = labels_cortex + labels_aseg else: labels = labels_cortex labels_aseg = None print((labels[0].pos)) print((len(labels))) # labels_file, label_names_file, label_coords_file = \ # create_label_files(labels) labels_file, label_names_file, label_coords_file = \ create_mni_label_files(forward, labels_cortex, labels_aseg, sbj_id, sbj_dir) return ts_file, labels_file, label_names_file, label_coords_file
def compute_ROIs_inv_sol(raw_filename, sbj_id, sbj_dir, fwd_filename, cov_fname, is_epoched=False, event_id=None, t_min=None, t_max=None, is_evoked=False, events_id=[], snr=1.0, inv_method='MNE', parc='aparc', aseg=False, aseg_labels=[], is_blind=False, labels_removed=[], save_stc=False): import os import os.path as op import numpy as np import mne import pickle from mne.io import read_raw_fif from mne import read_epochs from mne.minimum_norm import make_inverse_operator, apply_inverse_raw from mne.minimum_norm import apply_inverse_epochs, apply_inverse from mne import get_volume_labels_from_src from nipype.utils.filemanip import split_filename as split_f from neuropype_ephy.preproc import create_reject_dict try: traits.undefined(event_id) except NameError: event_id = None print '\n*** READ raw filename %s ***\n' % raw_filename if is_epoched and event_id is None: epochs = read_epochs(raw_filename) info = epochs.info else: raw = read_raw_fif(raw_filename) info = raw.info subj_path, basename, ext = split_f(info['filename']) print '\n*** READ noise covariance %s ***\n' % cov_fname noise_cov = mne.read_cov(cov_fname) print '\n*** READ FWD SOL %s ***\n' % fwd_filename forward = mne.read_forward_solution(fwd_filename) if not aseg: forward = mne.convert_forward_solution(forward, surf_ori=True, force_fixed=False) lambda2 = 1.0 / snr ** 2 # compute inverse operator print '\n*** COMPUTE INV OP ***\n' if not aseg: loose = 0.2 depth = 0.8 else: loose = None depth = None inverse_operator = make_inverse_operator(info, forward, noise_cov, loose=loose, depth=depth, fixed=False) # apply inverse operator to the time windows [t_start, t_stop]s print '\n*** APPLY INV OP ***\n' if is_epoched and event_id is not None: events = mne.find_events(raw) picks = mne.pick_types(info, meg=True, eog=True, exclude='bads') reject = create_reject_dict(info) if is_evoked: epochs = mne.Epochs(raw, events, events_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) evoked = [epochs[k].average() for k in events_id] snr = 3.0 lambda2 = 1.0 / snr ** 2 ev_list = events_id.items() for k in range(len(events_id)): stc = apply_inverse(evoked[k], inverse_operator, lambda2, inv_method, pick_ori=None) print '\n*** STC for event %s ***\n' % ev_list[k][0] stc_file = op.abspath(basename + '_' + ev_list[k][0]) print '***' print 'stc dim ' + str(stc.shape) print '***' if not aseg: stc.save(stc_file) else: epochs = mne.Epochs(raw, events, event_id, t_min, t_max, picks=picks, baseline=(None, 0), reject=reject) stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=None) print '***' print 'len stc %d' % len(stc) print '***' elif is_epoched and event_id is None: stc = apply_inverse_epochs(epochs, inverse_operator, lambda2, inv_method, pick_ori=None) print '***' print 'len stc %d' % len(stc) print '***' else: stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method, label=None, start=None, stop=None, buffer_size=1000, pick_ori=None) # None 'normal' print '***' print 'stc dim ' + str(stc.shape) print '***' if save_stc: if aseg: for i in range(len(stc)): try: os.mkdir(op.join(subj_path, 'TS')) except OSError: pass stc_file = op.join(subj_path, 'TS', basename + '_' + inv_method + '_stc_' + str(i) + '.npy') if not op.isfile(stc_file): np.save(stc_file, stc[i].data) labels_cortex = mne.read_labels_from_annot(sbj_id, parc=parc, subjects_dir=sbj_dir) if is_blind: for l in labels_cortex: if l.name in labels_removed: print l.name labels_cortex.remove(l) print '\n*** %d ***\n' % len(labels_cortex) src = inverse_operator['src'] # allow_empty : bool -> Instead of emitting an error, return all-zero time # courses for labels that do not have any vertices in the source estimate label_ts = mne.extract_label_time_course(stc, labels_cortex, src, mode='mean', allow_empty=True, return_generator=False) # save results in .npy file that will be the input for spectral node print '\n*** SAVE ROI TS ***\n' print len(label_ts) ts_file = op.abspath(basename + '_ROI_ts.npy') np.save(ts_file, label_ts) if aseg: print sbj_id labels_aseg = get_volume_labels_from_src(src, sbj_id, sbj_dir) labels = labels_cortex + labels_aseg else: labels = labels_cortex print labels[0].pos print len(labels) labels_file = op.abspath('labels.dat') with open(labels_file, "wb") as f: pickle.dump(len(labels), f) for value in labels: pickle.dump(value, f) label_names_file = op.abspath('label_names.txt') label_coords_file = op.abspath('label_coords.txt') label_names = [] label_coords = [] for value in labels: label_names.append(value.name) # label_coords.append(value.pos[0]) label_coords.append(np.mean(value.pos, axis=0)) np.savetxt(label_names_file, np.array(label_names, dtype=str), fmt="%s") np.savetxt(label_coords_file, np.array(label_coords, dtype=float), fmt="%f %f %f") return ts_file, labels_file, label_names_file, label_coords_file
os.chdir(filedir + '/' + SubjID) fwdfile = 'MixedSourceSpace_%s_3shell_forICA-fwd.fif' % SubjID fwd = mne.read_forward_solution(fwdfile) # convert to surface-based source orientation fwd = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=False) # preparation for subcortical sources srcfile = [i for i in os.listdir(os.getcwd()) if '_forICA-oct-6-src.fif' in i][0] srcspace = mne.read_source_spaces(srcfile) nvert_insurf = srcspace[0]['nuse'] + srcspace[1]['nuse'] vertices = [srcspace[0]['vertno'], srcspace[1]['vertno']] locVal = locals() vollabels = mne.get_volume_labels_from_src(srcspace, MRIsubject, subjects_dir) nVert = [len(i.vertices) for i in vollabels] vertNo = np.cumsum(nVert) # make inverse operators: InvOperator = make_inverse_operator(rawdata.info, forward=fwd, noise_cov=NoiseCov, loose='auto', depth=0.8, fixed=False, limit_depth_chs=False, verbose=None) snr = 3.0 lambda2 = 1.0 / snr**2
roi_power = [] # load the epochs, and restrict them to the experimental trials epo_all = mne.read_epochs("{}{}-epo.fif".format(proc_dir, meg)) epos = epo_all['negative', 'positive'] # load the forward model and labels fwd = mne.read_forward_solution("{}{}-fwd.fif".format(proc_dir, meg)) labels = mne.read_labels_from_annot(mri, parc='aparc', hemi='both', surf_name='white', annot_fname=None, regexp=None, subjects_dir=mri_dir, sort=False, verbose=None) labels_sub = mne.get_volume_labels_from_src(fwd['src'], mri, mri_dir) labels_all = labels + labels_sub # load filters for DICS beamformer filters = mne.beamformer.read_beamformer('{}{}-dics.h5'.format( proc_dir, meg)) filters_g = mne.beamformer.read_beamformer('{}{}-gamma-dics.h5'.format( proc_dir, meg)) # create a file to save the values filename = "{}{}_trial_roi_power.txt".format(proc_dir, meg) with open(filename, "w") as file: file.write("Tri_Ord\tEvent_ID\tTrig\tFreq") for l in labels_all: file.write("\t{}".format(l.name)) file.write("\n") # now loop through the single epochs and calculate the power values for i in range(len(epos)):