def find_pattern(): global mneraw,icas,ica_pic_path,pattern_ica_id,pattern_subject_id raw=mneraw[0] ica=icas[0] fig1,fig2=corrmap(icas,template=(pattern_subject_id,pattern_ica_id),threshold=ica_threshold,show=False,label="blink") fig1.savefig(os.path.join(ica_pic_path,"blink_pattern.jpg")) print(type(fig2)) if type(fig2)==list: for j in range(len(fig2)): fig2[j].savefig(os.path.join(ica_pic_path,"blink_found_{}.jpg".format(j+1))) else: fig2.savefig(os.path.join(ica_pic_path,"blink_found.jpg"))
def remove_eog_template_ica(raws, n_components, ch_name, threshold): """Remove EOG artifacts by similar Independent Components across subjects. Parameters ---------- raws : list List Raw instances. n_components : int Number of principal components for ICA. ch_name : str The name of the channel to use for EOG peak detection. threshold : int The value above which a feature is classified as outlier. Returns ------- raws : list List Raw instances. Notes ----- """ icas = [ ICA(n_components=n_components, max_iter='auto').copy().fit(raw, verbose=0) for raw in raws ] for raw, ica in zip(raws, icas): eog_inds, _ = ica.find_bads_eog(raw, ch_name=ch_name, verbose=0) if eog_inds: break if not eog_inds: raise RuntimeError( 'This group of subjects does not have an EOG template, add more subjects.' ) _ = corrmap(icas, template=(0, eog_inds[0]), threshold=threshold, label='blink') for raw, ica in zip(raws, icas): ica.exclude = ica.labels_['blink'] ica.apply(raw, verbose=0) return raws
def ICA_apply(icas: int, subj_number: int, comp_number: int, epochs: list) -> list: """ Applies ICA with template model from 1 participant in the dyad. See ICA_choice_comp for a detailed description of the parameters and output. """ cleaned_epochs_ICA = [] # selecting which ICs corresponding to the template template_eog_component = icas[subj_number].get_components()[:, comp_number] # applying corrmap with at least 1 component detected for each subj fig_template, fig_detected = corrmap(icas, template=template_eog_component, threshold=0.9, label='blink', ch_type='eeg') # labeling the ICs that capture blink artifacts print([ica.labels_ for ica in icas]) # selecting ICA components after viz for i in icas: i.exclude = i.labels_['blink'] epoch_all_ch = [] # applying ica on clean_epochs # for each participant for i, j in zip(range(0, len(epochs)), icas): # taking all channels to apply ICA bads = epochs[i].info['bads'] epoch_all_ch.append(mne.Epochs.copy(epochs[i])) epoch_all_ch[i].info['bads'] = [] j.apply(epoch_all_ch[i]) epoch_all_ch[i].info['bads'] = bads cleaned_epochs_ICA.append(epoch_all_ch[i]) return cleaned_epochs_ICA
raw.rename_channels(mapping) raw.set_montage('standard_1005') # fit ICA ica = ICA(n_components=30, random_state=97) ica.fit(raw) raws.append(raw) icas.append(ica) ############################################################################### # Now let's run :func:`~mne.preprocessing.corrmap`: # use the first subject as template; use Fpz as proxy for EOG raw = raws[0] ica = icas[0] eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name='Fpz') corrmap(icas, template=(0, eog_inds[0])) ############################################################################### # The first figure shows the template map, while the second figure shows all # the maps that were considered a "match" for the template (including the # template itself). There were only three matches from the four subjects; # notice the output message ``No maps selected for subject(s) 1, consider a # more liberal threshold``. By default the threshold is set automatically by # trying several values; here it may have chosen a threshold that is too high. # Let's take a look at the ICA sources for each subject: for index, (ica, raw) in enumerate(zip(icas, raws)): fig = ica.plot_sources(raw, show_scrollbars=False) fig.subplots_adjust(top=0.9) # make space for title fig.suptitle('Subject {}'.format(index))
def corr_map(list_icas, ica_template, comp_template, dir_templates, label, threshold=0.85): """ apply a corr map modify objects list_icas inplace :param list_icas: list of icas objects :param ica_template: int positional int of the ica to use as template :param comp_template: list of int, list of components :param dir_templates: string, diretory to save templates :param threshold: float64, set the threshold :param label: string, label """ for comp in comp_template: corr = corrmap(list_icas, template=(ica_template, comp), plot=True, show=False, threshold=threshold, label=label) path_topos = os.path.join(dir_templates, str(comp) + ".png") corr[0].savefig(path_topos) topos = Image.open(path_topos) if type(corr[1]) == list: lst = [topos] paths = [path_topos] total_width = 0 total_height = 0 for ind, im in enumerate(corr[1]): path_im = os.path.join(dir_templates, str(comp) + str(ind) + ".png") paths.append(path_im) im.savefig(path_im) scalps = Image.open(path_im) lst.append(scalps) width, height = scalps.size total_width += width if height > total_height: total_height = height new_im = Image.new('RGBA', (total_width, total_height)) x_offset = 0 for scalp in lst: new_im.paste(scalp, (x_offset, 0)) x_offset += scalp.size[0] new_im.save( os.path.join(dir_templates, "component" + str(comp) + ".png")) # for i in lst: # i.close() for p in paths: os.remove(p) plt.close('all') else: path_found = os.path.join(dir_templates, str(comp) + "a" + ".png") corr[1].savefig(path_found) topos = Image.open(path_topos) found = Image.open(path_found) img = [topos, found] width_0, height_0 = img[0].size width_1, height_1 = img[1].size real_width = width_0 + width_1 real_height = height_1 new_im = Image.new('RGBA', (real_width, real_height)) x_offset = 0 for im in img: new_im.paste(im, (x_offset, 0)) x_offset += im.size[0] new_im.save( os.path.join(dir_templates, "component" + str(comp) + ".png")) os.remove(path_topos) os.remove(path_found) plt.close('all')
montage = make_standard_montage('standard_1005') #Caricare il montaggio raw.set_montage(montage) #Setto il montaggio raw.filter(1.0, 79.0, fir_design='firwin', skip_by_annotation='edge') #Filtro raw_notch = raw.notch_filter(freqs=60) #Faccio un filtro passa banda raw.plot_psd(area_mode=None, show=False, average=False, fmin =1.0, fmax=80.0, dB=False, n_fft=160) # todo: qui salvare il plot psd # Ica ica = ICA(n_components=64, random_state=42, method="fastica", max_iter=1000) ind = [] for index, value in enumerate((raw.annotations).description): if value == "BAD boundary" or value == "EDGE boundary": ind.append(index) (raw.annotations).delete(ind) ica.fit(raw) raws.append(raw) icas.append(ica) #%% icas[0].plot_properties(raws[0], picks = [2,3], dB = False) eog_inds, eog_scores = icas[0].find_bads_eog(raws[0],ch_name='Fp1') icas[0].plot_components(picks = eog_inds) exc_0 = [] corr_map = corrmap(icas, template=(0, eog_inds[0]))
exc_66 = [0,1,3,13,14,17,29,32,33,35,47,50,53] #Here we report what kind of artifact eyes = [0,1,3,14,33,35,47] #ecg = [] #movement =[17,32,] #odd = [13] #electrode =[53] #%% Correlational map #exc_template = corrmap(icas, template=(0, 33), plot=True, threshold=0.75, label = 'artifact Subject' ) for subj in range (len(subjects)): print(str(icas_load[subj].labels_ )) artifacts_dic = [] #artifacts_dic.append(icas[subj].labels_.items()) #artifacts_dic.append(icas[subj].labels_) print(artifacts_dic) # print(' Subject' + str(subjects[subj]) +' ' + str([icas[subj].labels_ for ica in icas])) i = icas_load[1].labels_
temp_icas.append( read_ica( fname.output(subject=subj, processing_step='fit_ica', file_type='ica.fif'))) # set thresholds for correlation if subject in {5, 28, 32, 39, 45}: threshold = 0.90 else: threshold = 0.85 # compute correlations with template ocular movements up/down and left/right corrmap(icas=[temp_icas[1], ica], template=(0, 0), threshold=threshold, label='blink_up', plot=False) corrmap(icas=[temp_icas[1], ica], template=(0, 1), threshold=threshold, label='blink_side', plot=False) # compute correlations with template ocular movements that look slightly # different corrmap(icas=[temp_icas[0], ica], template=(0, 0), threshold=threshold, label='blink_misc', plot=False)
for subj in temp_subjs: temp_raws.append( read_raw_fif( fname.output(subject=subj, processing_step='repair_bads', file_type='raw.fif'))) temp_icas.append( read_ica( fname.output(subject=subj, processing_step='fit_ica', file_type='ica.fif'))) # compute correlations with template ocular movements up/down and left/right corrmap(icas=[temp_icas[0], ica], template=(0, 0), threshold=0.85, label='blink_up', plot=False) corrmap(icas=[temp_icas[0], ica], template=(0, 7), threshold=0.85, label='blink_side', plot=False) ############################################################################### # 4) Create summary plots to show signal correction on main experimental # condition # create target epochs target_evs = events_from_annotations(raw, regexp='(11)|(12)|(21)|(22)')[0] target_epo = Epochs(raw,
ica = ICA(n_components=64, random_state=42, method="fastica", max_iter=1000) ind = [] for index, value in enumerate((raw.annotations).description): if value == "BAD boundary" or value == "EDGE boundary": ind.append(index) (raw.annotations).delete(ind) ica.fit(raw) raws.append(raw) icas.append(ica) corrmap(icas, template=(0, 19), plot=True, threshold=0.80) icas[0].plot_properties( raws[0], picks=[26, 29, 34, 44, 47, 49, 51, 53, 55, 56, 58, 59, 63, 60, 61], dB=False) #%% #eog_inds, eog_scores = icas[0].find_bads_eog(raws[0], ch_name='Fpz') #icas[0].plot_properties(raws[0], picks=[], dB=False) exc_0 = [ 0, 3, 9, 11, 14, 15, 19, 26, 29, 34, 44, 47, 49, 51, 53, 55, 56, 58, 59, 63, 60, 61 ] maybe = [7, 12, 23, 24, 40] #reconst_raw = raws[0].copy() #icas[0].plot_overlay(reconst_raw, exclude=exc_0)