H_STSW_automatic_artifact_correction_180123_noTardis.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. function H_STSW_automatic_artifact_correction_180123_noTardis()
  2. %% H_SS_automatic_artifact_correction_20170922
  3. % 180326 | instead of equalizing to smallest amount of samples, interpolate
  4. % for the same timing across subjects. Note that this does not
  5. % counteract any natural jitter in the paradigm and should only
  6. % equalize the size of matrices (fill with zeros! at ends).
  7. % Artefact detection does NOT currently work with potential NaN
  8. % values that would naturally arise from the interpolation.
  9. %% initialize
  10. %restoredefaultpath;
  11. %clear all; close all; pack; clc;
  12. %% pathdef
  13. if ismac
  14. pn.study = '/Volumes/LNDG/Projects/StateSwitch/';
  15. pn.eeg_root = [pn.study, 'dynamic/data/eeg/task/A_preproc/SA_preproc_study/'];
  16. pn.dynamic_In = [pn.eeg_root, 'B_data/B_EEG_ET_ByRun/'];
  17. pn.triggerTiming= [pn.eeg_root, 'C_figures/D_TriggerTiming/'];
  18. pn.EEG = [pn.eeg_root, 'B_data/C_EEG_FT/']; mkdir(pn.EEG);
  19. pn.History = [pn.eeg_root, 'B_data/D_History/']; mkdir(pn.History);
  20. pn.logs = [pn.eeg_root, 'Y_logs/H_ArtCorr/'];
  21. % add ConMemEEG tools
  22. pn.MWBtools = [pn.eeg_root, 'T_tools/fnct_MWB/']; addpath(genpath(pn.MWBtools));
  23. pn.THGtools = [pn.eeg_root, 'T_tools/fnct_THG/']; addpath(genpath(pn.THGtools));
  24. pn.commontools = [pn.eeg_root, 'T_tools/fnct_common/']; addpath(genpath(pn.commontools));
  25. pn.fnct_JQK = [pn.eeg_root, 'T_tools/fnct_JQK/']; addpath(genpath(pn.fnct_JQK));
  26. pn.FT = [pn.eeg_root, 'T_tools/fieldtrip-20170904/']; addpath(pn.FT); ft_defaults;
  27. pn.helper = [pn.eeg_root, 'A_scripts/helper/']; addpath(pn.helper);
  28. else
  29. pn.root = '/home/mpib/LNDG/StateSwitch/WIP_eeg/SA_preproc_study/';
  30. pn.EEG = [pn.root, 'B_data/C_EEG_FT/'];
  31. pn.History = [pn.root, 'B_data/D_History/'];
  32. pn.triggerTiming= [pn.root, 'C_figures/D_TriggerTiming/'];
  33. pn.logs = [pn.root, 'Y_logs/H_ArtCorr/'];
  34. end
  35. %% define Condition & IDs for preprocessing
  36. condEEG = 'dynamic';
  37. %% define IDs for segmentation
  38. % N = 47 YAs + 53 OAs;
  39. IDs = {'1117';'1118';'1120';'1124';'1126';'1131';'1132';'1135';'1136';'1138';...
  40. '1144';'1151';'1158';'1160';'1163';'1164';'1167';'1169';'1172';'1173';...
  41. '1178';'1182';'1215';'1216';'1219';'1221';'1223';'1227';'1228';'1233';...
  42. '1234';'1237';'1239';'1240';'1243';'1245';'1247';'1250';'1252';'1257';...
  43. '1261';'1265';'1266';'1268';'1270';'1276';'1281';...
  44. '2104';'2107';'2108';'2112';'2118';'2120';'2121';'2123';'2125';'2129';...
  45. '2130';'2131';'2132';'2133';'2134';'2135';'2139';'2140';'2145';'2147';...
  46. '2149';'2157';'2160';'2201';'2202';'2203';'2205';'2206';'2209';'2210';...
  47. '2211';'2213';'2214';'2215';'2216';'2217';'2219';'2222';'2224';'2226';...
  48. '2227';'2236';'2237';'2238';'2241';'2244';'2246';'2248';'2250';'2251';...
  49. '2252';'2258';'2261'};
  50. %% loop IDs
  51. ID_unavailable = cell(length(IDs),1);
  52. for id = 1:length(IDs)
  53. try
  54. display(['processing ID ' num2str(IDs{id})]);
  55. for iRun = 1:4
  56. % load config
  57. load([pn.History, IDs{id}, '_r',num2str(iRun), '_', condEEG, '_config'],'config')
  58. if ~isfield(config, 'ArtDect')
  59. % load data
  60. load([pn.EEG, IDs{id}, '_r',num2str(iRun), '_', condEEG, '_EEG_Rlm_Fhl_rdSeg'],'data_EEG');
  61. dataICA = load([pn.EEG, IDs{id}, '_', condEEG, '_EEG_Rlm_Fhl_Ica'],'data');
  62. data = data_EEG; clear data_EEG;
  63. data.elec = dataICA.data.elec;
  64. data.chanlocs = dataICA.data.chanlocs; clear dataICA;
  65. %% ------------------ ARTIFACT DETECTION - PREPARATION ----------------- %%
  66. config.elec = data.elec;
  67. %% ICA (from weights)
  68. % ica config
  69. cfg.method = 'runica';
  70. cfg.channel = {'all','-ECG','-A2'};
  71. cfg.trials = 'all';
  72. cfg.numcomponent = 'all';
  73. cfg.demean = 'yes';
  74. cfg.runica.extended = 1;
  75. % ICA solution
  76. cfg.unmixing = config.ica1.unmixing;
  77. cfg.topolabel = config.ica1.topolabel;
  78. % components
  79. comp = ft_componentanalysis(cfg,data);
  80. % clear cfg
  81. clear cfg data
  82. %% remove components
  83. % get IC labels
  84. iclabels = config.ica1.iclabels.manual;
  85. % cfg for rejecting components (reject: blinks, eye movements,
  86. % ecg, ref); JQK: added artifacts and emg
  87. cfg.component = sortrows([iclabels.bli(:); iclabels.mov(:); iclabels.hrt(:); iclabels.ref(:); iclabels.art(:); iclabels.emg(:)])';
  88. cfg.demean = 'yes';
  89. % reject components
  90. data = ft_rejectcomponent(cfg,comp);
  91. % clear cfg
  92. clear cfg comp
  93. %% remove eye & reference channels
  94. cfg.channel = {'all','-IOR','-LHEOG','-RHEOG','-A1'};
  95. cfg.demean = 'yes';
  96. % remove channels
  97. tmpdat = ft_preprocessing(cfg,data);
  98. % clear cfg & data variable
  99. clear cfg data
  100. %% ------------------------- ARTIFACT DETECTION ------------------------ %%
  101. % open log file
  102. fid = fopen([pn.logs, 'log_' IDs{id}, '_r',num2str(iRun), '_' condEEG '_ArtCorr.txt'],'a');
  103. % write log
  104. % fprintf(fid,['********************* ' BLOCK ' *********************\n']); % Undefined function or variable 'BLOCK'. but see: %% H_prep_data_for_analysis_20141218
  105. fprintf(fid,['********************* BLOCK *********************\n']);
  106. fprintf(fid,['function: H_SS_automatic_artifact_correction_20170922.m \n\n']);
  107. fprintf(fid,['eeg file = ' config.data_file '\n\n']);
  108. n_trl = length(tmpdat.trial);
  109. %% get artifact contaminated channels by kurtosis, low & high frequency artifacts
  110. cfg.criterion = 3;
  111. cfg.recursive = 'no';
  112. [index0 parm0 zval0] = cm_MWB_channel_x_epoch_artifacts_20170922(cfg,tmpdat);
  113. % write log
  114. tmp_log = '';
  115. for j = 1:length(index0.c)
  116. tmp_log = [tmp_log num2str(index0.c(j)) ' '];
  117. end; clear j
  118. tmp_log = [tmp_log(1:end-1) '\n'];
  119. fprintf(fid,'(1) automatic bad channel detection:\n');
  120. fprintf(fid,['MWB: channel(s) ' tmp_log]);
  121. % clear cfg
  122. clear cfg tmp_log
  123. %% get artifact contaminated channels by FASTER
  124. cfg.criterion = 3;
  125. cfg.recursive = 'no';
  126. [index1 parm1 zval1] = THG_FASTER_1_channel_artifacts_20140302(cfg,tmpdat);
  127. % write log
  128. tmp_log = '';
  129. for j = 1:length(index1)
  130. tmp_log = [tmp_log num2str(index1(j)) ' '];
  131. end; clear j
  132. tmp_log = [tmp_log(1:end-1) '\n'];
  133. fprintf(fid,['FASTER: channel(s) ' tmp_log]);
  134. % clear cfg
  135. clear cfg tmp_log
  136. %% interpolate artifact contaminated channels
  137. % collect bad channels
  138. badchan = unique([index0.c; index1]);
  139. fprintf(fid,['--> ' num2str(length(badchan)) ' channels interpolated\n\n']);
  140. cfg.method = 'spline';
  141. cfg.badchannel = tmpdat.label(badchan);
  142. cfg.trials = 'all';
  143. cfg.lambda = 1e-5;
  144. cfg.order = 4;
  145. cfg.elec = config.elec;
  146. % interpolate
  147. tmpdat = ft_channelrepair(cfg,tmpdat);
  148. % clear cfg
  149. clear cfg
  150. %% interpolate data to requested time (necessary due to acquisition jitter)
  151. % 2160 has only 62 trials, i.e. the first two trials were
  152. % not recorded.
  153. timeRequested = -1.5:1/500:9.566;
  154. for indTrial = 1:size(tmpdat.trial,2)
  155. recTime = tmpdat.time{indTrial};
  156. recData = tmpdat.trial{indTrial};
  157. for indChannel = 1:size(recData,1)
  158. interpData(indChannel,:) = interp1(recTime,recData(indChannel,:),timeRequested,'linear');
  159. end
  160. interpData(isnan(interpData)) = 0;
  161. tmpdat.trial{indTrial} = interpData;
  162. tmpdat.time{indTrial} = timeRequested;
  163. end
  164. %figure; plot(timeRequested,interpData, 'k'); hold on; plot(recTime,recData(1,:), 'r')
  165. %% get artifact contaminated epochs & exclude epochs
  166. % includes: - THG_MWB_channel_x_epoch_artifacts_20140311
  167. % - THG_FASTER_2_epoch_artifacts_20140302
  168. % recursive epoch exclusion!
  169. [tmpdat index] = THG_automatic_artifact_correction_trials_20170922(tmpdat);
  170. % write log
  171. fprintf(fid,'(2) automatic recursive bad epoch detection:\n');
  172. fprintf(fid,['MWB & FASTER: ' num2str(n_trl-length(index)) ' bad epoch(s) detected\n\n']);
  173. %% get channel x epoch artifacts
  174. % cfg
  175. cfg.criterion = 3;
  176. cfg.recursive = 'yes';
  177. [index3 parm3 zval3] = THG_FASTER_4_channel_x_epoch_artifacts_20140302(cfg,tmpdat);
  178. % write log
  179. fprintf(fid,'(3) automatic single epoch/channel detection:\n');
  180. fprintf(fid,['FASTER: ' num2str(sum(sum(index3))) ' channel(s) x trial(s) detected\n\n']);
  181. % clear cfg
  182. clear cfg
  183. %% collect and save detected artifacts & artifact correction infos
  184. % include ArtDect.parameters
  185. % bad channels
  186. ArtDect.channels = badchan;
  187. % bad trials
  188. tmp = zeros(n_trl,1); tmp(index,1) = 1;
  189. badtrl = find(tmp==0);
  190. ArtDect.trials = badtrl;
  191. clear tmp
  192. % bad single epoch(s)/channel(s) - after exclusion of bad epochs
  193. ArtDect.channels_x_trials = index3;
  194. % overview
  195. ind = [1:n_trl];
  196. ind(badtrl) = [];
  197. tmp = ones(length(tmpdat.label),n_trl);
  198. tmp(:,ind) = index3;
  199. tmp(badchan,:) = 1;
  200. ArtDect.channels_x_trials_all = tmp;
  201. clear tmp
  202. % save version
  203. ArtDect.version = 'JQK 20180123';
  204. % add to config
  205. config.ArtDect = ArtDect;
  206. % save config
  207. save([pn.History, IDs{id}, '_r',num2str(iRun), '_', condEEG, '_config'],'config')
  208. %% finalize log
  209. % log
  210. fprintf(fid,'Artifact detection completed.\n');
  211. fprintf(fid,['Information saved to: ' IDs{id} '_config.mat\n\n']);
  212. fclose(fid);
  213. else
  214. disp([IDs{id}, ' Run ',num2str(iRun), ' has already run through automatic artifact detection']);
  215. end % if data was not processed yet
  216. end % run
  217. catch ME
  218. warning('Error occured. Please check.');
  219. rethrow(ME)
  220. fprintf('\n ID not availble! Skip! \n')
  221. ID_unavailable{id,1} = (IDs{id});
  222. end
  223. end; clear id
  224. end