TEAP (Toolbox for Emotion Analysis using Physiological Signals) doc
eeg_checkset.m
Go to the documentation of this file.
1 % eeg_checkset() - check the consistency of the fields of an EEG dataset
2 % Also: See EEG dataset structure field descriptions below.
3 %
4 % Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
5 % except 'makeur'
6 % >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
7 %
8 % Inputs:
9 % EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures
10 %
11 % Optional keywords:
12 % 'icaconsist' - if EEG contains several datasets, check whether they have
13 % the same ICA decomposition
14 % 'epochconsist' - if EEG contains several datasets, check whether they have
15 % identical epoch lengths and time limits.
16 % 'chanconsist' - if EEG contains several datasets, check whether they have
17 % the same number of channela and channel labels.
18 % 'data' - check whether EEG contains data (EEG.data)
19 % 'loaddata' - load data array (if necessary)
20 % 'savedata' - save data array (if necessary - see EEG.saved below)
21 % 'contdata' - check whether EEG contains continuous data
22 % 'epoch' - check whether EEG contains epoched or continuous data
23 % 'ica' - check whether EEG contains an ICA decomposition
24 % 'besa' - check whether EEG contains component dipole locations
25 % 'event' - check whether EEG contains an event array
26 % 'makeur' - remake the EEG.urevent structure
27 % 'checkur' - check whether the EEG.urevent structure is consistent
28 % with the EEG.event structure
29 % 'chanlocsize' - check the EEG.chanlocs structure length; show warning if
30 % necessary.
31 % 'chanlocs_homogeneous' - check whether EEG contains consistent channel
32 % information; if not, correct it.
33 % 'eventconsistency' - check whether EEG.event information are consistent;
34 % rebuild event* subfields of the 'EEG.epoch' structure
35 % (can be time consuming).
36 % Outputs:
37 % EEGOUT - output EEGLAB dataset or dataset array
38 % changes - change code: 'no' = no changes; 'yes' = the EEG
39 % structure was modified
40 %
41 % ===========================================================
42 % The structure of an EEG dataset under EEGLAB (as of v5.03):
43 %
44 % Basic dataset information:
45 % EEG.setname - descriptive name|title for the dataset
46 % EEG.filename - filename of the dataset file on disk
47 % EEG.filepath - filepath (directory/folder) of the dataset file(s)
48 % EEG.trials - number of epochs (or trials) in the dataset.
49 % If data are continuous, this number is 1.
50 % EEG.pnts - number of time points (or data frames) per trial (epoch).
51 % If data are continuous (trials=1), the total number
52 % of time points (frames) in the dataset
53 % EEG.nbchan - number of channels
54 % EEG.srate - data sampling rate (in Hz)
55 % EEG.xmin - epoch start latency|time (in sec. relative to the
56 % time-locking event at time 0)
57 % EEG.xmax - epoch end latency|time (in seconds)
58 % EEG.times - vector of latencies|times in seconds (one per time point)
59 % EEG.ref - ['common'|'averef'|integer] reference channel type or number
60 % EEG.history - cell array of ascii pop-window commands that created
61 % or modified the dataset
62 % EEG.comments - comments about the nature of the dataset (edit this via
63 % menu selection Edit > About this dataset)
64 % EEG.etc - miscellaneous (technical or temporary) dataset information
65 % EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit
66 %
67 % The data:
68 % EEG.data - two-dimensional continuous data array (chans, frames)
69 % ELSE, three-dim. epoched data array (chans, frames, epochs)
70 %
71 % The channel locations sub-structures:
72 % EEG.chanlocs - structure array containing names and locations
73 % of the channels on the scalp
74 % EEG.urchanlocs - original (ur) dataset chanlocs structure containing
75 % all channels originally collected with these data
76 % (before channel rejection)
77 % EEG.chaninfo - structure containing additional channel info
78 % EEG.ref - type of channel reference ('common'|'averef'|+/-int]
79 % EEG.splinefile - location of the spline file used by headplot() to plot
80 % data scalp maps in 3-D
81 %
82 % The event and epoch sub-structures:
83 % EEG.event - event structure containing times and nature of experimental
84 % events recorded as occurring at data time points
85 % EEG.urevent - original (ur) event structure containing all experimental
86 % events recorded as occurring at the original data time points
87 % (before data rejection)
88 % EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch)
89 % EEG.eventdescription - cell array of strings describing event fields.
90 % EEG.epochdescription - cell array of strings describing epoch fields.
91 % --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
92 %
93 % ICA (or other linear) data components:
94 % EEG.icasphere - sphering array returned by linear (ICA) decomposition
95 % EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition
96 % EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected
97 % topographies of the components to the electrodes.
98 % EEG.icaact - ICA activations matrix (components, frames, epochs)
99 % Note: [] here means that 'compute_ica' option has bee set
100 % to 0 under 'File > Memory options' In this case,
101 % component activations are computed only as needed.
102 % EEG.icasplinefile - location of the spline file used by headplot() to plot
103 % component scalp maps in 3-D
104 % EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition
105 % EEG.dipfit - array of structures containing component map dipole models
106 %
107 % Variables indicating membership of the dataset in a studyset:
108 % EEG.subject - studyset subject code
109 % EEG.group - studyset group code
110 % EEG.condition - studyset experimental condition code
111 % EEG.session - studyset session number
112 %
113 % Variables used for manual and semi-automatic data rejection:
114 % EEG.specdata - data spectrum for every single trial
115 % EEG.specica - data spectrum for every single trial
116 % EEG.stats - statistics used for data rejection
117 % EEG.stats.kurtc - component kurtosis values
118 % EEG.stats.kurtg - global kurtosis of components
119 % EEG.stats.kurta - kurtosis of accepted epochs
120 % EEG.stats.kurtr - kurtosis of rejected epochs
121 % EEG.stats.kurtd - kurtosis of spatial distribution
122 % EEG.reject - statistics used for data rejection
123 % EEG.reject.entropy - entropy of epochs
124 % EEG.reject.entropyc - entropy of components
125 % EEG.reject.threshold - rejection thresholds
126 % EEG.reject.icareject - epochs rejected by ICA criteria
127 % EEG.reject.gcompreject - rejected ICA components
128 % EEG.reject.sigreject - epochs rejected by single-channel criteria
129 % EEG.reject.elecreject - epochs rejected by raw data criteria
130 %
131 % Author: Arnaud Delorme, CNL / Salk Institute, 2001
132 %
133 % See also: eeglab()
134 
135 % Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
136 %
137 % This program is free software; you can redistribute it and/or modify
138 % it under the terms of the GNU General Public License as published by
139 % the Free Software Foundation; either version 2 of the License, or
140 % (at your option) any later version.
141 %
142 % This program is distributed in the hope that it will be useful,
143 % but WITHOUT ANY WARRANTY; without even the implied warranty of
144 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
145 % GNU General Public License for more details.
146 %
147 % You should have received a copy of the GNU General Public License
148 % along with this program; if not, write to the Free Software
149 % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
150 
151 % 01-25-02 reformated help & license -ad
152 % 01-26-02 chandeg events and trial condition format -ad
153 % 01-27-02 debug when trial condition is empty -ad
154 % 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
155 % 02-16-02 remove last modification and test icawinv separatelly -ad
156 % 02-16-02 empty event and epoch check -ad
157 % 03-07-02 add the eeglab options -ad
158 % 03-07-02 corrected typos and rate/point calculation -ad & ja
159 % 03-15-02 add channel location reading & checking -ad
160 % 03-15-02 add checking of ICA and epochs with pop_up windows -ad
161 % 03-27-02 recorrected rate/point calculation -ad & sm
162 
163 function [EEG, res] = eeg_checkset( EEG, varargin );
164 msg = '';
165 res = 'no';
166 com = sprintf('EEG = eeg_checkset( EEG );');
167 
168 if nargin < 1
169  help eeg_checkset;
170  return;
171 end;
172 
173 if isempty(EEG), return; end;
174 if ~isfield(EEG, 'data'), return; end;
175 
176 % checking multiple datasets
177 % --------------------------
178 if length(EEG) > 1
179 
180  if nargin > 1
181  switch varargin{1}
182  case 'epochconsist', % test epoch consistency
183  % ----------------------
184  res = 'no';
185  datasettype = unique( [ EEG.trials ] );
186  if datasettype(1) == 1 & length(datasettype) == 1, return; % continuous data
187  elseif datasettype(1) == 1, return; % continuous and epoch data
188  end;
189 
190  allpnts = unique( [ EEG.pnts ] );
191  allxmin = unique( [ EEG.xmin ] );
192  if length(allpnts) == 1 & length(allxmin) == 1, res = 'yes'; end;
193  return;
194 
195  case 'chanconsist' % test channel number and name consistency
196  % ----------------------------------------
197  res = 'yes';
198  chanlen = unique( [ EEG.nbchan ] );
199  anyempty = unique( cellfun( 'isempty', { EEG.chanlocs }) );
200  if length(chanlen) == 1 & all(anyempty == 0)
201  tmpchanlocs = EEG(1).chanlocs;
202  channame1 = { tmpchanlocs.labels };
203  for i = 2:length(EEG)
204  tmpchanlocs = EEG(i).chanlocs;
205  channame2 = { tmpchanlocs.labels };
206  if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end;
207  end;
208  else res = 'no';
209  end;
210  return;
211 
212  case 'icaconsist' % test ICA decomposition consistency
213  % ----------------------------------
214  res = 'yes';
215  anyempty = unique( cellfun( 'isempty', { EEG.icaweights }) );
216  if length(anyempty) == 1 & anyempty(1) == 0
217  ica1 = EEG(1).icawinv;
218  for i = 2:length(EEG)
219  if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
220  res = 'no';
221  end;
222  end;
223  else res = 'no';
224  end;
225  return;
226 
227  end;
228  end;
229 
230 end;
231 
232 % reading these option take time because
233 % of disk access
234 % --------------
235 eeglab_options;
236 
237 % standard checking
238 % -----------------
239 ALLEEG = EEG;
240 for inddataset = 1:length(ALLEEG)
241 
242  EEG = ALLEEG(inddataset);
243 
244  % additional checks
245  % -----------------
246  res = -1; % error code
247  if ~isempty( varargin)
248  for index = 1:length( varargin )
249  switch varargin{ index }
250  case 'data',; % already done at the top
251  case 'contdata',;
252  if EEG.trials > 1
253  errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
254  return;
255  end;
256  case 'ica',
257  if isempty(EEG.icaweights)
258  errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
259  return;
260  end;
261  case 'epoch',
262  if EEG.trials == 1
263  errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
264  return
265  end;
266  case 'besa',
267  if ~isfield(EEG, 'sources')
268  errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
269  , '2) Run BESA to localize the equivalent dipoles', ...
270  '3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
271  return
272  end;
273  case 'event',
274  if isempty(EEG.event)
275  errordlg2(strvcat('Requires events. You need to dd events first.', ...
276  'Use "Edit > event fields" to create event fields.', ...
277  'Or use "File > Import event info" or "File > Import epoch info"'), 'Error');
278  return;
279  end;
280  case 'chanloc',
281  tmplocs = EEG.chanlocs;
282  if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
283  errordlg2( strvcat('This functionality requires channel location information.', ...
284  'Enter the channel file name via "Edit > Edit dataset info".', ...
285  'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
286  return;
287  end;
288  case 'chanlocs_homogeneous',
289  tmplocs = EEG.chanlocs;
290  if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
291  errordlg2( strvcat('This functionality requires channel location information.', ...
292  'Enter the channel file name via "Edit > Edit dataset info".', ...
293  'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
294  return;
295  end;
296  if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
297  EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
298  res = [ inputname(1) ' = eeg_checkset(' inputname(1) ', ''chanlocs_homogeneous'' ); ' ];
299  end;
300  case 'chanlocsize',
301  if ~isempty(EEG.chanlocs)
302  if length(EEG.chanlocs) > EEG.nbchan
303  questdlg2(strvcat('Warning: there is one more electrode location than', ...
304  'data channels. EEGLAB will consider the last electrode to be the', ...
305  'common reference channel. If this is not the case, remove the', ...
306  'extra channel'), 'Warning', 'Ok', 'Ok');
307  end;
308  end;
309  case 'makeur',
310  if ~isempty(EEG.event)
311  if isfield(EEG.event, 'urevent'),
312  EEG.event = rmfield(EEG.event, 'urevent');
313  disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
314  else
315  disp('eeg_checkset note: creating the original event table (EEG.urevent)');
316  end;
317  EEG.urevent = EEG.event;
318  for index = 1:length(EEG.event)
319  EEG.event(index).urevent = index;
320  end;
321  end;
322  case 'checkur',
323  if ~isempty(EEG.event)
324  if isfield(EEG.event, 'urevent') & ~isempty(EEG.urevent)
325  urlatencies = [ EEG.urevent.latency ];
326  [newlat tmpind] = sort(urlatencies);
327  if ~isequal(newlat, urlatencies)
328  EEG.urevent = EEG.urevent(tmpind);
329  [tmp tmpind2] = sort(tmpind);
330  for index = 1:length(EEG.event)
331  EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
332  end;
333  end;
334  end;
335  end;
336  case 'eventconsistency',
337  [EEG res] = eeg_checkset(EEG);
338  if isempty(EEG.event), return; end;
339 
340  % check events (slow)
341  % ------------
342  if isfield(EEG.event, 'type')
343  tmpevent = EEG.event;
344  if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
345  disp('Warning: converting all event types to strings');
346  for ind = 1:length(EEG.event)
347  EEG.event(ind).type = num2str(EEG.event(ind).type);
348  end;
349  EEG = eeg_checkset(EEG, 'eventconsistency');
350  end;
351  end;
352 
353  % remove the events which latency are out of boundary
354  % ---------------------------------------------------
355  if isfield(EEG.event, 'latency')
356  if isfield(EEG.event, 'type') && ischar(EEG.event(1).type)
357  if strcmpi(EEG.event(1).type, 'boundary') & isfield(EEG.event, 'duration')
358  if EEG.event(1).duration < 1
359  EEG.event(1) = [];
360  elseif EEG.event(1).latency > 0 & EEG.event(1).latency < 1
361  EEG.event(1).latency = 0.5;
362  end;
363  end;
364  end;
365 
366  try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ];
367  catch, error('Checkset: error empty latency entry for new events added by user');
368  end;
369  I1 = find(alllatencies < 0.5);
370  I2 = find(alllatencies > EEG.pnts*EEG.trials+0.5); % The addition of 0.5 was included
371  % for symmetry with the above line, which most likely has something to do with rounding
372  if (length(I1) + length(I2)) > 0
373  fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
374  length(I1) + length(I2), length(EEG.event));
375  EEG.event(union(I1, I2)) = [];
376  end;
377  end;
378  if isempty(EEG.event), return; end;
379 
380  % save information for non latency fields updates
381  % -----------------------------------------------
382  difffield = [];
383  if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
384  % remove fields with empty epochs
385  % -------------------------------
386  removeevent = [];
387  try, tmpevent = EEG.event; allepochs = [ tmpevent.epoch ];
388  removeevent = find( allepochs < 1 | allepochs > EEG.trials);
389  if ~isempty(removeevent)
390  disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
391  end;
392  catch,
393  for indexevent = 1:length(EEG.event)
394  if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
395  | EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
396  removeevent = [removeevent indexevent];
397  disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
398  end;
399  end;
400  end;
401  EEG.event(removeevent) = [];
402  tmpevent = EEG.event;
403  allepochs = [ tmpevent.epoch ];
404 
405  % uniformize fields content for the different epochs
406  % --------------------------------------------------
407  % THIS WAS REMOVED SINCE SOME FIELDS ARE ASSOCIATED WITH THE EVENT AND NOT WITH THE EPOCH
408  % I PUT IT BACK, BUT IT DOES NOT ERASE NON-EMPTY VALUES
409  difffield = fieldnames(EEG.event);
410  difffield = difffield(~(strcmp(difffield,'latency')|strcmp(difffield,'epoch')|strcmp(difffield,'type')));
411  for index = 1:length(difffield)
412  tmpevent = EEG.event;
413  allvalues = { tmpevent.(difffield{index}) };
414  try
415  valempt = cellfun('isempty', allvalues);
416  catch
417  valempt = mycellfun('isempty', allvalues);
418  end;
419  arraytmpinfo = cell(1,EEG.trials);
420 
421  % spetial case of duration
422  % ------------------------
423  if strcmp( difffield{index}, 'duration')
424  if any(valempt)
425  fprintf(['eeg_checkset: found empty values for field ''' difffield{index} ...
426  ''' (filling with 0)\n']);
427  end;
428  for indexevent = find(valempt)
429  EEG.event(indexevent).duration = 0;
430  end;
431  else
432 
433  % get the field content
434  % ---------------------
435  indexevent = find(~valempt);
436  arraytmpinfo(allepochs(indexevent)) = allvalues(indexevent);
437 
438  % uniformize content for all epochs
439  % ---------------------------------
440  indexevent = find(valempt);
441  tmpevent = EEG.event;
442  [tmpevent(indexevent).(difffield{index})] = arraytmpinfo{allepochs(indexevent)};
443  EEG.event = tmpevent;
444  if any(valempt)
445  fprintf(['eeg_checkset: found empty values for field ''' difffield{index} '''\n']);
446  fprintf([' filling with values of other events in the same epochs\n']);
447  end;
448  end;
449  end;
450  end;
451  if isempty(EEG.event), return; end;
452 
453  % uniformize fields (str or int) if necessary
454  % -------------------------------------------
455  fnames = fieldnames(EEG.event);
456  for fidx = 1:length(fnames)
457  fname = fnames{fidx};
458  tmpevent = EEG.event;
459  allvalues = { tmpevent.(fname) };
460  try
461  % find indices of numeric values among values of this event property
462  valreal = ~cellfun('isclass', allvalues, 'char');
463  catch
464  valreal = mycellfun('isclass', allvalues, 'double');
465  end;
466 
467  format = 'ok';
468  if ~all(valreal) % all valreal ok
469  format = 'str';
470  if all(valreal == 0) % all valreal=0 ok
471  format = 'ok';
472  end;
473  end;
474  if strcmp(format, 'str')
475  fprintf('eeg_checkset note: value format of event field ''%s'' made uniform\n', fname);
476  % get the field content
477  % ---------------------
478  for indexevent = 1:length(EEG.event)
479  if valreal(indexevent)
480  EEG.event = setfield(EEG.event, { indexevent }, fname, num2str(allvalues{indexevent}) );
481  end;
482  end;
483  end;
484  end;
485 
486  % check boundary events
487  % ---------------------
488  tmpevent = EEG.event;
489  if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
490  allEventTypes = { tmpevent.type };
491  boundsInd = strmatch('boundary', allEventTypes);
492  if ~isempty(boundsInd),
493  bounds = [ tmpevent(boundsInd).latency ];
494  % remove last event if necessary
495  if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
496  % The first boundary below need to be kept for
497  % urevent latency calculation
498  % if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any
499  indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
500  if ~isempty(indDoublet)
501  disp('Warning: duplicate boundary event removed');
502  for indBound = 1:length(indDoublet)
503  EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
504  end;
505  EEG.event(boundsInd(indDoublet)) = [];
506  end;
507  end;
508  end;
509  if isempty(EEG.event), return; end;
510 
511  % check that numeric format is double (Matlab 7)
512  % -----------------------------------
513  allfields = fieldnames(EEG.event);
514  if ~isempty(EEG.event)
515  for index = 1:length(allfields)
516  tmpval = EEG.event(1).(allfields{index});
517  if isnumeric(tmpval) && ~isa(tmpval, 'double')
518  for indexevent = 1:length(EEG.event)
519  tmpval = getfield(EEG.event, { indexevent }, allfields{index} );
520  EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
521  end;
522  end;
523  end;
524  end;
525 
526  % check duration field, replace empty by 0
527  % ----------------------------------------
528  if isfield(EEG.event, 'duration')
529  tmpevent = EEG.event;
530  try, valempt = cellfun('isempty' , { tmpevent.duration });
531  catch, valempt = mycellfun('isempty', { tmpevent.duration });
532  end;
533  if any(valempt),
534  for index = find(valempt)
535  EEG.event(index).duration = 0;
536  end;
537  end;
538  end;
539 
540  % resort events
541  % -------------
542  if isfield(EEG.event, 'latency')
543  try,
544  if isfield(EEG.event, 'epoch')
545  TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
546  else
547  TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
548  end;
549  if ~isequal(TMPEEG.event, EEG.event)
550  EEG = TMPEEG;
551  disp('Event resorted by increasing latencies.');
552  end;
553  catch,
554  disp('eeg_checkset: problem when attempting to resort event latencies.');
555  end;
556  end;
557 
558  % check latency of first event
559  % ----------------------------
560  if ~isempty(EEG.event)
561  if isfield(EEG.event, 'latency')
562  if EEG.event(1).latency < 0.5
563  EEG.event(1).latency = 0.5;
564  end;
565  end;
566  end;
567 
568  % build epoch structure
569  % ---------------------
570  try,
571  if EEG.trials > 1 & ~isempty(EEG.event)
572  % erase existing event-related fields
573  % ------------------------------
574  if ~isfield(EEG,'epoch')
575  EEG.epoch = [];
576  end
577  if ~isempty(EEG.epoch)
578  if length(EEG.epoch) ~= EEG.trials
579  disp('Warning: number of epoch entries does not match number of dataset trials;');
580  disp(' user-defined epoch entries will be erased.');
581  EEG.epoch = [];
582  else
583  fn = fieldnames(EEG.epoch);
584  EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
585  end
586  end
587 
588  % set event field
589  % ---------------
590  tmpevent = EEG.event;
591  eventepoch = [tmpevent.epoch];
592  epochevent = cell(1,EEG.trials);
593  destdata = epochevent;
594  EEG.epoch(length(epochevent)).event = [];
595  for k=1:length(epochevent)
596  epochevent{k} = find(eventepoch==k);
597  end
598  tmpepoch = EEG.epoch;
599  [tmpepoch.event] = epochevent{:};
600  EEG.epoch = tmpepoch;
601  maxlen = max(cellfun(@length,epochevent));
602 
603  % copy event information into the epoch array
604  % -------------------------------------------
605  eventfields = fieldnames(EEG.event)';
606  eventfields = eventfields(~strcmp(eventfields,'epoch'));
607  tmpevent = EEG.event;
608  for k = 1:length(eventfields)
609  fname = eventfields{k};
610  switch fname
611  case 'latency'
612  sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
613  sourcedata = num2cell(sourcedata);
614  case 'duration'
615  sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
616  otherwise
617  sourcedata = {tmpevent.(fname)};
618  end
619  if maxlen == 1
620  destdata = cell(1,length(epochevent));
621  destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
622  else
623  for l=1:length(epochevent)
624  destdata{l} = sourcedata(epochevent{l});
625  end
626  end
627  tmpepoch = EEG.epoch;
628  [tmpepoch.(['event' fname])] = destdata{:};
629  EEG.epoch = tmpepoch;
630  end
631  end;
632  catch,
633  errordlg2(['Warning: minor problem encountered when generating' 10 ...
634  'the EEG.epoch structure (used only in user scripts)']); return;
635  end;
636  case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
637  otherwise, error('eeg_checkset: unknown option');
638  end;
639  end;
640  end;
641 
642  res = [];
643 
644  % check name consistency
645  % ----------------------
646  if ~isempty(EEG.setname)
647  if ~ischar(EEG.setname)
648  EEG.setname = '';
649  else
650  if size(EEG.setname,1) > 1
651  disp('eeg_checkset warning: invalid dataset name, removed');
652  EEG.setname = '';
653  end;
654  end;
655  else
656  EEG.setname = '';
657  end;
658 
659  % checking history and convert if necessary
660  % -----------------------------------------
661  if isfield(EEG, 'history') & size(EEG.history,1) > 1
662  allcoms = cellstr(EEG.history);
663  EEG.history = deblank(allcoms{1});
664  for index = 2:length(allcoms)
665  EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
666  end;
667  end;
668 
669  % read data if necessary
670  % ----------------------
671  if ischar(EEG.data) & nargin > 1
672  if strcmpi(varargin{1}, 'loaddata')
673 
674  EEG.data = eeg_getdatact(EEG);
675 
676  end;
677  end;
678 
679  % save data if necessary
680  % ----------------------
681  if nargin > 1
682 
683  % datfile available?
684  % ------------------
685  datfile = 0;
686  if isfield(EEG, 'datfile')
687  if ~isempty(EEG.datfile)
688  datfile = 1;
689  end;
690  end;
691 
692  % save data
693  % ---------
694  if strcmpi(varargin{1}, 'savedata') & option_storedisk
695  error('eeg_checkset: cannot call savedata any more');
696 
697  % the code below is deprecated
698  if ~ischar(EEG.data) % not already saved
699  disp('Writing previous dataset to disk...');
700 
701  if datfile
702  tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
703  floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
704  EEG.data = EEG.datfile;
705  end;
706  EEG.icaact = [];
707 
708  % saving dataset
709  % --------------
710  filename = fullfile(EEG(1).filepath, EEG(1).filename);
711  if ~ischar(EEG.data) & option_single, EEG.data = single(EEG.data); end;
712  v = version;
713  if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
714  else save( filename, '-mat', 'EEG');
715  end;
716  if ~ischar(EEG.data), EEG.data = 'in set file'; end;
717 
718  res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
719  end;
720  end;
721  end;
722 
723  % numerical format
724  % ----------------
725  if isnumeric(EEG.data)
726  v = version;
727  EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
728  EEG.icaweights = double(EEG.icaweights);
729  EEG.icasphere = double(EEG.icasphere);
730  if ~isempty(findstr(v, 'R11')) | ~isempty(findstr(v, 'R12')) | ~isempty(findstr(v, 'R13'))
731  EEG.data = double(EEG.data);
732  EEG.icaact = double(EEG.icaact);
733  else
734  try,
735  if isa(EEG.data, 'double') & option_single
736  EEG.data = single(EEG.data);
737  EEG.icaact = single(EEG.icaact);
738  end;
739  catch,
740  disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
741  disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).');
742  disp(' Then reload it.');
743  end;
744  end;
745  end;
746 
747  % verify the type of the variables
748  % --------------------------------
749  % data dimensions -------------------------
750  if isnumeric(EEG.data) && ~isempty(EEG.data)
751  if ~isequal(size(EEG.data,1), EEG.nbchan)
752  disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ...
753  ') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
754  res = com;
755  EEG.nbchan = size(EEG.data,1);
756  end;
757 
758  if (ndims(EEG.data)) < 3 & (EEG.pnts > 1)
759  if mod(size(EEG.data,2), EEG.pnts) ~= 0
760  if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.' 10 ...
761  'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)'])
762  error('eeg_checkset error: user abort');
763  %res = com;
764  %EEG.pnts = size(EEG.data,2);
765  %EEG = eeg_checkset(EEG);
766  %return;
767  else
768  res = com;
769  return;
770  %error( 'eeg_checkset error: number of points does not divide the number of columns in data');
771  end;
772  else
773  if EEG.trials > 1
774  disp( 'eeg_checkset note: data array made 3-D');
775  res = com;
776  end;
777  if size(EEG.data,2) ~= EEG.pnts
778  EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
779  end;
780  end;
781  end;
782 
783  % size of data -----------
784  if size(EEG.data,3) ~= EEG.trials
785  disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
786  ') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
787  res = com;
788  EEG.trials = size(EEG.data,3);
789  end;
790  if size(EEG.data,2) ~= EEG.pnts
791  disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
792  ') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
793  res = com;
794  EEG.pnts = size(EEG.data,2);
795  end;
796  end;
797 
798  % parameters consistency
799  % -------------------------
800  if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
801  fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
802  if EEG.srate == 0
803  EEG.srate = 1;
804  end;
805  EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
806  res = com;
807  end;
808 
809  % deal with event arrays
810  % ----------------------
811  if ~isfield(EEG, 'event'), EEG.event = []; res = com; end;
812  if ~isempty(EEG.event)
813  if EEG.trials > 1 & ~isfield(EEG.event, 'epoch')
814  if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ...
815  'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
816  error('eeg_checkset error(): user abort');
817  %res = com;
818  %EEG.event = [];
819  %EEG = eeg_checkset(EEG);
820  %return;
821  else
822  res = com;
823  return;
824  %error('eeg_checkset error: no epoch field in event structure');
825  end;
826  end;
827  else
828  EEG.event = [];
829  end;
830  if isempty(EEG.event)
831  EEG.eventdescription = {};
832  end;
833  if ~isfield(EEG, 'eventdescription') | ~iscell(EEG.eventdescription)
834  EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
835  res = com;
836  else
837  if ~isempty(EEG.event)
838  if length(EEG.eventdescription) > length( fieldnames(EEG.event))
839  EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
840  elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
841  EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
842  end;
843  end;
844  end;
845  % create urevent if continuous data
846  % ---------------------------------
847  %if ~isempty(EEG.event) & ~isfield(EEG, 'urevent')
848  % EEG.urevent = EEG.event;
849  % disp('eeg_checkset note: creating the original event table (EEG.urevent)');
850  % for index = 1:length(EEG.event)
851  % EEG.event(index).urevent = index;
852  % end;
853  %end;
854  if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'urevent')
855  EEG.urevent = rmfield(EEG.urevent, 'urevent');
856  end;
857 
858  % deal with epoch arrays
859  % ----------------------
860  if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end;
861 
862  % check if only one epoch
863  % -----------------------
864  if EEG.trials == 1
865  if isfield(EEG.event, 'epoch')
866  EEG.event = rmfield(EEG.event, 'epoch'); res = com;
867  end;
868  if ~isempty(EEG.epoch)
869  EEG.epoch = []; res = com;
870  end;
871  end;
872 
873  if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end;
874  if ~isempty(EEG.epoch)
875  if isstruct(EEG.epoch), l = length( EEG.epoch);
876  else l = size( EEG.epoch, 2);
877  end;
878  if l ~= EEG.trials
879  if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
880  int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
881  'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
882  error('eeg_checkset error: user abort');
883  %res = com;
884  %EEG.epoch = [];
885  %EEG = eeg_checkset(EEG);
886  %return;
887  else
888  res = com;
889  return;
890  %error('eeg_checkset error: epoch structure size invalid');
891  end;
892  end;
893  else
894  EEG.epoch = [];
895  end;
896 
897  % check ica
898  % ---------
899  if ~isfield(EEG, 'icachansind')
900  if isempty(EEG.icaweights)
901  EEG.icachansind = []; res = com;
902  else
903  EEG.icachansind = [1:EEG.nbchan]; res = com;
904  end;
905  elseif isempty(EEG.icachansind)
906  if isempty(EEG.icaweights)
907  EEG.icachansind = []; res = com;
908  else
909  EEG.icachansind = [1:EEG.nbchan]; res = com;
910  end;
911  end;
912  if ~isempty(EEG.icasphere)
913  if ~isempty(EEG.icaweights)
914  if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
915  if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
916  'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
917  'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
918  res = com;
919  EEG.icasphere = [];
920  EEG.icaweights = [];
921  EEG = eeg_checkset(EEG);
922  return;
923  else
924  error('eeg_checkset error: user abort');
925  res = com;
926  return;
927  %error('eeg_checkset error: invalid weight and sphere array sizes');
928  end;
929  end;
930  if isnumeric(EEG.data)
931  if length(EEG.icachansind) ~= size(EEG.icasphere,2)
932  if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
933  'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
934  'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
935  res = com;
936  EEG.icasphere = [];
937  EEG.icaweights = [];
938  EEG = eeg_checkset(EEG);
939  return;
940  else
941  error('eeg_checkset error: user abort');
942  res = com;
943  return;
944  %error('eeg_checkset error: invalid weight and sphere array sizes');
945  end;
946  end;
947  if isempty(EEG.icaact) | (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) | (size(EEG.icaact,2) ~= size(EEG.data,2))
948  EEG.icaweights = double(EEG.icaweights);
949  EEG.icawinv = double(EEG.icawinv);
950 
951  % scale ICA components to RMS microvolt
952  if option_scaleicarms
953  if ~isempty(EEG.icawinv)
954  if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001
955  disp('Scaling components to RMS microvolt');
956  scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]);
957  EEG.etc.icaweights_beforerms = EEG.icaweights;
958  EEG.etc.icasphere_beforerms = EEG.icasphere;
959 
960  EEG.icaweights = EEG.icaweights .* scaling;
961  EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere);
962  end;
963  end;
964  end;
965 
966  if ~isempty(EEG.data) && option_computeica
967  fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n');
968  res = com;
969  % Make compatible with Matlab 7
970  if any(isnan(EEG.data(:)))
971  tmpdata = EEG.data(EEG.icachansind,:);
972  fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n');
973  tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:)));
974  EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN;
975  EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices);
976  else
977  EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double
978  end;
979  EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
980  end;
981  end;
982  end;
983  if isempty(EEG.icawinv)
984  EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
985  res = com;
986  end;
987  else
988  disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]);
989  res = com;
990  EEG.icasphere = [];
991  end;
992  if option_computeica
993  if ~isempty(EEG.icaact) & ndims(EEG.icaact) < 3 & (EEG.trials > 1)
994  disp( [ 'eeg_checkset note: independent component made 3-D' ]);
995  res = com;
996  EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
997  end;
998  else
999  if ~isempty(EEG.icaact)
1000  fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n');
1001  end;
1002  EEG.icaact = [];
1003  end;
1004  else
1005  if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end;
1006  if ~isempty( EEG.icawinv ), EEG.icawinv = []; res = com; end;
1007  if ~isempty( EEG.icaact ), EEG.icaact = []; res = com; end;
1008  end;
1009  if isempty(EEG.icaact)
1010  EEG.icaact = [];
1011  end;
1012 
1013  % -------------
1014  % check chanlocs
1015  % -------------
1016  if ~isfield(EEG, 'chaninfo')
1017  EEG.chaninfo = [];
1018  end;
1019  if ~isempty( EEG.chanlocs )
1020 
1021  % reference (use EEG structure)
1022  % ---------
1023  if ~isfield(EEG, 'ref'), EEG.ref = ''; end;
1024  if strcmpi(EEG.ref, 'averef')
1025  ref = 'average';
1026  else ref = '';
1027  end;
1028  if ~isfield( EEG.chanlocs, 'ref')
1029  EEG.chanlocs(1).ref = ref;
1030  end;
1031  charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char');
1032  if any(charrefs) ref = ''; end
1033  for tmpind = find(~charrefs)
1034  EEG.chanlocs(tmpind).ref = ref;
1035  end
1036  if ~isstruct( EEG.chanlocs)
1037  if exist( EEG.chanlocs ) ~= 2
1038  disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]);
1039  EEG.chanlocs = [];
1040  res = com;
1041  else
1042  res = com;
1043  try, EEG.chanlocs = readlocs( EEG.chanlocs );
1044  disp( [ 'eeg_checkset: channel file read' ]);
1045  catch, EEG.chanlocs = []; end;
1046  end;
1047  else
1048  if ~isfield(EEG.chanlocs,'labels')
1049  disp('eeg_checkset warning: no field label in channel location structure, removing it');
1050  EEG.chanlocs = [];
1051  res = com;
1052  end;
1053  end;
1054  if isstruct( EEG.chanlocs)
1055  if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data)
1056  disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]);
1057  EEG.chanlocs = [];
1058  res = com;
1059  end;
1060  end;
1061 
1062  % force Nosedir to +X (done here because of DIPFIT)
1063  % -------------------
1064  if isfield(EEG.chaninfo, 'nosedir')
1065  if strcmpi(EEG.chaninfo.nosedir, '+x')
1066  rotate = 0;
1067  elseif all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'}))
1068  disp('EEG checkset note for expert users: Noze direction now set to default +X in EEG.chanlocs and EEG.dipfit.');
1069  if strcmpi(EEG.chaninfo.nosedir, '+y')
1070  rotate = 270;
1071  elseif strcmpi(EEG.chaninfo.nosedir, '-x')
1072  rotate = 180;
1073  else rotate = 90;
1074  end;
1075  for index = 1:length(EEG.chanlocs)
1076  if ~isempty(EEG.chanlocs(index).theta)
1077  rotategrad = rotate/180*pi;
1078  coord = (EEG.chanlocs(index).Y + EEG.chanlocs(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad);
1079  EEG.chanlocs(index).Y = real(coord);
1080  EEG.chanlocs(index).X = imag(coord);
1081 
1082  EEG.chanlocs(index).theta = EEG.chanlocs(index).theta -rotate;
1083  EEG.chanlocs(index).sph_theta = EEG.chanlocs(index).sph_theta+rotate;
1084  if EEG.chanlocs(index).theta <-180, EEG.chanlocs(index).theta =EEG.chanlocs(index).theta +360; end;
1085  if EEG.chanlocs(index).sph_theta>180 , EEG.chanlocs(index).sph_theta=EEG.chanlocs(index).sph_theta-360; end;
1086  end;
1087  end;
1088 
1089  if isfield(EEG, 'dipfit')
1090  if isfield(EEG.dipfit, 'coord_transform')
1091  if isempty(EEG.dipfit.coord_transform)
1092  EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
1093  end;
1094  EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad;
1095  end;
1096  end;
1097 
1098  end;
1099  EEG.chaninfo.nosedir = '+X';
1100  end;
1101 
1102  % general checking of channels
1103  % ----------------------------
1104  EEG = eeg_checkchanlocs(EEG);
1105  if EEG.nbchan ~= length(EEG.chanlocs)
1106  EEG.chanlocs = [];
1107  EEG.chaninfo = [];
1108  disp('Warning: the size of the channel location structure does not match with');
1109  disp(' number of channels. Channel information have been removed.');
1110  end;
1111  end;
1112  EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience
1113 
1114  %if ~isfield(EEG, 'urchanlocs')
1115  % EEG.urchanlocs = EEG.chanlocs;
1116  % for index = 1:length(EEG.chanlocs)
1117  % EEG.chanlocs(index).urchan = index;
1118  % end;
1119  % disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)');
1120  %end;
1121 
1122  % check reference
1123  % ---------------
1124  if ~isfield(EEG, 'ref')
1125  EEG.ref = 'common';
1126  end;
1127  if ischar(EEG.ref) & strcmpi(EEG.ref, 'common')
1128  if length(EEG.chanlocs) > EEG.nbchan
1129  disp('Extra common reference electrode location detected');
1130  EEG.ref = EEG.nbchan+1;
1131  end;
1132  end;
1133 
1134  % DIPFIT structure
1135  % ----------------
1136  if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit)
1137  EEG.dipfit = []; res = com;
1138  else
1139  try
1140  % check if dipfitdefs is present
1141  dipfitdefs;
1142  if isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
1143  if exist('pop_dipfit_settings')
1144  disp('Old DIPFIT structure detected: converting to DIPFIT 2 format');
1145  EEG.dipfit.hdmfile = template_models(1).hdmfile;
1146  EEG.dipfit.coordformat = template_models(1).coordformat;
1147  EEG.dipfit.mrifile = template_models(1).mrifile;
1148  EEG.dipfit.chanfile = template_models(1).chanfile;
1149  EEG.dipfit.coord_transform = [];
1150  EEG.saved = 'no';
1151  res = com;
1152  end;
1153  end;
1154  if isfield(EEG.dipfit, 'hdmfile')
1155  if length(EEG.dipfit.hdmfile) > 8
1156  if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end;
1157  if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end;
1158  end;
1159  if length(EEG.dipfit.mrifile) > 8
1160  if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end;
1161  if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end;
1162  end;
1163  if length(EEG.dipfit.chanfile) > 8
1164  if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end;
1165  if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end;
1166  end;
1167  end;
1168 
1169  if isfield(EEG.dipfit, 'coord_transform')
1170  if isempty(EEG.dipfit.coord_transform)
1171  EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
1172  end;
1173  elseif ~isempty(EEG.dipfit)
1174  EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
1175  end;
1176  catch
1177  e = lasterror;
1178  if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')
1179  % if we got some error aside from dipfitdefs not being present, rethrow it
1180  rethrow(e);
1181  end
1182  end
1183  end;
1184 
1185  % check events (fast)
1186  % ------------
1187  if isfield(EEG.event, 'type')
1188  tmpevent = EEG.event(1:min(length(EEG.event), 100));
1189  if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
1190  disp('Warning: converting all event types to strings');
1191  for ind = 1:length(EEG.event)
1192  EEG.event(ind).type = num2str(EEG.event(ind).type);
1193  end;
1194  EEG = eeg_checkset(EEG, 'eventconsistency');
1195  end;
1196  end;
1197 
1198  % EEG.times (only for epoched datasets)
1199  % ---------
1200  if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts
1201  EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
1202  end;
1203 
1204  if ~isfield(EEG, 'history') EEG.history = ''; res = com; end;
1205  if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end;
1206  if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end;
1207  if ~isfield(EEG, 'saved') EEG.saved = 'no'; res = com; end;
1208  if ~isfield(EEG, 'subject') EEG.subject = ''; res = com; end;
1209  if ~isfield(EEG, 'condition') EEG.condition = ''; res = com; end;
1210  if ~isfield(EEG, 'group') EEG.group = ''; res = com; end;
1211  if ~isfield(EEG, 'session') EEG.session = []; res = com; end;
1212  if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end;
1213  if ~isfield(EEG, 'specdata') EEG.specdata = []; res = com; end;
1214  if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end;
1215  if ~isfield(EEG, 'comments') EEG.comments = ''; res = com; end;
1216  if ~isfield(EEG, 'etc' ) EEG.etc = []; res = com; end;
1217  if ~isfield(EEG, 'urevent' ) EEG.urevent = []; res = com; end;
1218  if ~isfield(EEG, 'ref') | isempty(EEG.ref) EEG.ref = 'common'; res = com; end;
1219 
1220  % create fields if absent
1221  % -----------------------
1222  if ~isfield(EEG, 'reject') EEG.reject.rejjp = []; res = com; end;
1223 
1224  listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ...
1225  'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'};
1226  for index = 1:length(listf)
1227  name = listf{index};
1228  elecfield = [name 'E'];
1229  if ~isfield(EEG.reject, elecfield), EEG.reject.(elecfield) = []; res = com; end;
1230  if ~isfield(EEG.reject, name)
1231  EEG.reject.(name) = [];
1232  res = com;
1233  elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield))
1234  % check if electrode array is empty with rejection array is not
1235  nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan);
1236  EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com;
1237  end;
1238  end;
1239  if ~isfield(EEG.reject, 'rejglobal') EEG.reject.rejglobal = []; res = com; end;
1240  if ~isfield(EEG.reject, 'rejglobalE') EEG.reject.rejglobalE = []; res = com; end;
1241 
1242  % default colors for rejection
1243  % ----------------------------
1244  if ~isfield(EEG.reject, 'rejmanualcol') EEG.reject.rejmanualcol = [1.0000 1 0.783]; res = com; end;
1245  if ~isfield(EEG.reject, 'rejthreshcol') EEG.reject.rejthreshcol = [0.8487 1.0000 0.5008]; res = com; end;
1246  if ~isfield(EEG.reject, 'rejconstcol') EEG.reject.rejconstcol = [0.6940 1.0000 0.7008]; res = com; end;
1247  if ~isfield(EEG.reject, 'rejjpcol') EEG.reject.rejjpcol = [1.0000 0.6991 0.7537]; res = com; end;
1248  if ~isfield(EEG.reject, 'rejkurtcol') EEG.reject.rejkurtcol = [0.6880 0.7042 1.0000]; res = com; end;
1249  if ~isfield(EEG.reject, 'rejfreqcol') EEG.reject.rejfreqcol = [0.9596 0.7193 1.0000]; res = com; end;
1250  if ~isfield(EEG.reject, 'disprej') EEG.reject.disprej = { }; end;
1251 
1252  if ~isfield(EEG, 'stats') EEG.stats.jp = []; res = com; end;
1253  if ~isfield(EEG.stats, 'jp') EEG.stats.jp = []; res = com; end;
1254  if ~isfield(EEG.stats, 'jpE') EEG.stats.jpE = []; res = com; end;
1255  if ~isfield(EEG.stats, 'icajp') EEG.stats.icajp = []; res = com; end;
1256  if ~isfield(EEG.stats, 'icajpE') EEG.stats.icajpE = []; res = com; end;
1257  if ~isfield(EEG.stats, 'kurt') EEG.stats.kurt = []; res = com; end;
1258  if ~isfield(EEG.stats, 'kurtE') EEG.stats.kurtE = []; res = com; end;
1259  if ~isfield(EEG.stats, 'icakurt') EEG.stats.icakurt = []; res = com; end;
1260  if ~isfield(EEG.stats, 'icakurtE') EEG.stats.icakurtE = []; res = com; end;
1261 
1262  % component rejection
1263  % -------------------
1264  if ~isfield(EEG.stats, 'compenta') EEG.stats.compenta = []; res = com; end;
1265  if ~isfield(EEG.stats, 'compentr') EEG.stats.compentr = []; res = com; end;
1266  if ~isfield(EEG.stats, 'compkurta') EEG.stats.compkurta = []; res = com; end;
1267  if ~isfield(EEG.stats, 'compkurtr') EEG.stats.compkurtr = []; res = com; end;
1268  if ~isfield(EEG.stats, 'compkurtdist') EEG.stats.compkurtdist = []; res = com; end;
1269  if ~isfield(EEG.reject, 'threshold') EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end;
1270  if ~isfield(EEG.reject, 'threshentropy') EEG.reject.threshentropy = 600; res = com; end;
1271  if ~isfield(EEG.reject, 'threshkurtact') EEG.reject.threshkurtact = 600; res = com; end;
1272  if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end;
1273  if ~isfield(EEG.reject, 'gcompreject') EEG.reject.gcompreject = []; res = com; end;
1274  if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1)
1275  EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1));
1276  end;
1277 
1278  % remove old fields
1279  % -----------------
1280  if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end;
1281  if isfield(EEG, 'rt' ), EEG = rmfield(EEG, 'rt'); end;
1282 
1283  % store in new structure
1284  % ----------------------
1285  if isstruct(EEG)
1286  if ~exist('ALLEEGNEW','var')
1287  ALLEEGNEW = EEG;
1288  else
1289  ALLEEGNEW(inddataset) = EEG;
1290  end;
1291  end;
1292 end;
1293 
1294 % recorder fields
1295 % ---------------
1296 fieldorder = { 'setname' ...
1297  'filename' ...
1298  'filepath' ...
1299  'subject' ...
1300  'group' ...
1301  'condition' ...
1302  'session' ...
1303  'comments' ...
1304  'nbchan' ...
1305  'trials' ...
1306  'pnts' ...
1307  'srate' ...
1308  'xmin' ...
1309  'xmax' ...
1310  'times' ...
1311  'data' ...
1312  'icaact' ...
1313  'icawinv' ...
1314  'icasphere' ...
1315  'icaweights' ...
1316  'icachansind' ...
1317  'chanlocs' ...
1318  'urchanlocs' ...
1319  'chaninfo' ...
1320  'ref' ...
1321  'event' ...
1322  'urevent' ...
1323  'eventdescription' ...
1324  'epoch' ...
1325  'epochdescription' ...
1326  'reject' ...
1327  'stats' ...
1328  'specdata' ...
1329  'specicaact' ...
1330  'splinefile' ...
1331  'icasplinefile' ...
1332  'dipfit' ...
1333  'history' ...
1334  'saved' ...
1335  'etc' };
1336 
1337 for fcell = fieldnames(EEG)'
1338  fname = fcell{1};
1339  if ~any(strcmp(fieldorder,fname))
1340  fieldorder{end+1} = fname;
1341  end
1342 end
1343 
1344 try
1345  ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder);
1346  EEG = ALLEEGNEW;
1347 catch
1348  disp('Couldn''t order data set fields properly.');
1349 end;
1350 
1351 if exist('ALLEEGNEW','var')
1352  EEG = ALLEEGNEW;
1353 end;
1354 option_eegobject = 0 ;
1355 if ~isa(EEG, 'eegobj') && option_eegobject
1356  EEG = eegobj(EEG);
1357 end;
1358 
1359 return;
1360 
1361 function num = popask( text )
1362 ButtonName=questdlg2( text, ...
1363  'Confirmation', 'Cancel', 'Yes','Yes');
1364 switch lower(ButtonName),
1365  case 'cancel', num = 0;
1366  case 'yes', num = 1;
1367 end;
1368 
1369 function res = mycellfun(com, vals, classtype);
1370 res = zeros(1, length(vals));
1371 switch com
1372  case 'isempty',
1373  for index = 1:length(vals), res(index) = isempty(vals{index}); end;
1374  case 'isclass'
1375  if strcmp(classtype, 'double')
1376  for index = 1:length(vals), res(index) = isnumeric(vals{index}); end;
1377  else
1378  error('unknown cellfun command');
1379  end;
1380  otherwise error('unknown cellfun command');
1381 end;
1382 
1383 
eeg_checkchanlocs
function eeg_checkchanlocs(in chans, in chaninfo)
popask
function popask(in text)
mycellfun
function mycellfun(in com, in vals, in classtype)
function
function()
eeg_checkset
function eeg_checkset(in EEG, in varargin)