-
Notifications
You must be signed in to change notification settings - Fork 247
/
eeg_checkset.m
1430 lines (1338 loc) · 66.1 KB
/
eeg_checkset.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% EEG_CHECKSET - check the consistency of the fields of an EEG dataset
% Also: See EEG dataset structure field descriptions below.
%
% Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
% except 'makeur'
% >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
%
% Inputs:
% EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures
%
% Optional keywords:
% 'icaconsist' - if EEG contains several datasets, check whether they have
% the same ICA decomposition
% 'epochconsist' - if EEG contains several datasets, check whether they have
% identical epoch lengths and time limits.
% 'chanconsist' - if EEG contains several datasets, check whether they have
% the same number of channels and channel labels.
% 'data' - check whether EEG contains data (EEG.data)
% 'loaddata' - load data array (if necessary)
% 'savedata' - save data array (if necessary - see EEG.saved below)
% 'contdata' - check whether EEG contains continuous data
% 'epoch' - check whether EEG contains epoched or continuous data
% 'ica' - check whether EEG contains an ICA decomposition
% 'besa' - check whether EEG contains component dipole locations
% 'event' - check whether EEG contains an event array
% 'makeur' - remake the EEG.urevent structure
% 'checkur' - check whether the EEG.urevent structure is consistent
% with the EEG.event structure
% 'chanlocsize' - check the EEG.chanlocs structure length; show warning if
% necessary.
% 'chanlocs_homogeneous' - check whether EEG contains consistent channel
% information; if not, correct it.This option
% calls eeg_checkchanlocs.
% 'eventconsistency' - check whether EEG.event information are consistent;
% rebuild event* subfields of the 'EEG.epoch' structure
% (can be time consuming).
% Outputs:
% EEGOUT - output EEGLAB dataset or dataset array
% changes - change code: 'no' = no changes; 'yes' = the EEG
% structure was modified
%
% ===========================================================
% The structure of an EEG dataset under EEGLAB (as of v5.03):
%
% Basic dataset information:
% EEG.setname - descriptive name|title for the dataset
% EEG.filename - filename of the dataset file on disk
% EEG.filepath - filepath (directory/folder) of the dataset file(s)
% EEG.trials - number of epochs (or trials) in the dataset.
% If data are continuous, this number is 1.
% EEG.pnts - number of time points (or data frames) per trial (epoch).
% If data are continuous (trials=1), the total number
% of time points (frames) in the dataset
% EEG.nbchan - number of channels
% EEG.srate - data sampling rate (in Hz)
% EEG.xmin - epoch start latency|time (in sec. relative to the
% time-locking event at time 0)
% EEG.xmax - epoch end latency|time (in seconds)
% EEG.times - vector of latencies|times in milliseconds (one per time point)
% EEG.ref - ['common'|'averef'|integer] reference channel type or number
% EEG.history - cell array of ascii pop-window commands that created
% or modified the dataset
% EEG.comments - comments about the nature of the dataset (edit this via
% menu selection Edit > About this dataset)
% EEG.etc - miscellaneous (technical or temporary) dataset information
% EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit
%
% The data:
% EEG.data - two-dimensional continuous data array (chans, frames)
% ELSE, three-dim. epoched data array (chans, frames, epochs)
%
% The channel locations sub-structures:
% EEG.chanlocs - structure array containing names and locations
% of the channels on the scalp
% EEG.urchanlocs - original (ur) dataset chanlocs structure containing
% all channels originally collected with these data
% (before channel rejection)
% EEG.chaninfo - structure containing additional channel info
% EEG.ref - type of channel reference ('common'|'averef'|+/-int]
% EEG.splinefile - location of the spline file used by HEADPLOT to plot
% data scalp maps in 3-D
%
% The event and epoch sub-structures:
% EEG.event - event structure containing times and nature of experimental
% events recorded as occurring at data time points
% EEG.urevent - original (ur) event structure containing all experimental
% events recorded as occurring at the original data time points
% (before data rejection)
% EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch)
% EEG.eventdescription - cell array of strings describing event fields.
% EEG.epochdescription - cell array of strings describing epoch fields.
% --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
%
% ICA (or other linear) data components:
% EEG.icasphere - sphering array returned by linear (ICA) decomposition
% EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition
% EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected
% topographies of the components to the electrodes.
% EEG.icaact - ICA activations matrix (components, frames, epochs)
% Note: [] here means that 'compute_ica' option has been set
% to 0 under 'File > Memory options' In this case,
% component activations are computed only as needed.
% EEG.icasplinefile - location of the spline file used by HEADPLOT to plot
% component scalp maps in 3-D
% EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition
% EEG.dipfit - array of structures containing component map dipole models
%
% Variables indicating membership of the dataset in a studyset:
% EEG.subject - studyset subject code
% EEG.group - studyset group code
% EEG.condition - studyset experimental condition code
% EEG.run - studyset run number
% EEG.session - studyset session number
%
% Variables used for manual and semi-automatic data rejection:
% EEG.specdata - data spectrum for every single trial
% EEG.specica - data spectrum for every single trial
% EEG.stats - statistics used for data rejection
% EEG.stats.kurtc - component kurtosis values
% EEG.stats.kurtg - global kurtosis of components
% EEG.stats.kurta - kurtosis of accepted epochs
% EEG.stats.kurtr - kurtosis of rejected epochs
% EEG.stats.kurtd - kurtosis of spatial distribution
% EEG.reject - statistics used for data rejection
% EEG.reject.entropy - entropy of epochs
% EEG.reject.entropyc - entropy of components
% EEG.reject.threshold - rejection thresholds
% EEG.reject.icareject - epochs rejected by ICA criteria
% EEG.reject.gcompreject - rejected ICA components
% EEG.reject.sigreject - epochs rejected by single-channel criteria
% EEG.reject.elecreject - epochs rejected by raw data criteria
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: EEGLAB
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.
% 01-25-02 reformated help & license -ad
% 01-26-02 chandeg events and trial condition format -ad
% 01-27-02 debug when trial condition is empty -ad
% 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
% 02-16-02 remove last modification and test icawinv separately -ad
% 02-16-02 empty event and epoch check -ad
% 03-07-02 add the eeglab options -ad
% 03-07-02 corrected typos and rate/point calculation -ad & ja
% 03-15-02 add channel location reading & checking -ad
% 03-15-02 add checking of ICA and epochs with pop_up windows -ad
% 03-27-02 recorrected rate/point calculation -ad & sm
function [EEGFINAL, res] = eeg_checkset( EEG, varargin )
msg = '';
res = 'no';
com = sprintf('EEG = eeg_checkset( EEG );');
if nargin < 1
help eeg_checkset;
return;
end
EEGFINAL = EEG;
warning backtrace off
if isempty(EEG), return; end
if ~isfield(EEG, 'data'), return; end
% checking multiple datasets
% --------------------------
if length(EEG) > 1
if length(EEG) > 5000
disp('Too many datasets, aborting check')
return;
end
if nargin > 1
switch varargin{1}
case 'epochconsist' % test epoch consistency
% ----------------------
res = 'no';
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 && length(datasettype) == 1, return; % continuous data
elseif datasettype(1) == 1, return; % continuous and epoch data
end
allpnts = unique_bc( [ EEG.pnts ] );
allxmin = unique_bc( [ EEG.xmin ] );
if length(allpnts) == 1 && length(allxmin) == 1, res = 'yes'; end
return;
case 'chanconsist' % test channel number and name consistency
% ----------------------------------------
res = 'yes';
chanlen = unique_bc( [ EEG.nbchan ] );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(chanlen) == 1 && all(anyempty == 0)
tmpchanlocs = EEG(1).chanlocs;
channame1 = { tmpchanlocs.labels };
for i = 2:length(EEG)
tmpchanlocs = EEG(i).chanlocs;
channame2 = { tmpchanlocs.labels };
if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end
end
else res = 'no';
end
% Field 'datachan in 'urchanlocs' is removed, if exist
if isfield(EEG, 'urchanlocs') && ~all(cellfun(@isempty,{EEG.urchanlocs})) && isfield([EEG.urchanlocs], 'datachan')
[EEG.urchanlocs] = deal(rmfield([EEG.urchanlocs], 'datachan'));
end
return;
case 'icaconsist' % test ICA decomposition consistency
% ----------------------------------
res = 'yes';
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 1 && anyempty(1) == 0
ica1 = EEG(1).icawinv;
for i = 2:length(EEG)
if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
res = 'no';
end
end
else res = 'no';
end
return;
end
end
end
% reading these option take time because
% of disk access
% --------------
eeglab_options;
% rename fields for backward compatibility in future versions
if isfield(EEG, 'nchans')
for iEEG = 1:length(EEG)
EEG(iEEG).nbchan = EEG.nchans;
end
end
if isfield(EEG, 'chanlocs')
for iEEG = 1:length(EEG)
if isfield(EEG(iEEG).chanlocs, 'label')
for iChan = 1:length(EEG(iEEG).chanlocs)
EEG(iEEG).chanlocs(iChan).labels = EEG(iEEG).chanlocs(iChan).label;
end
EEG(iEEG).chanlocs = rmfield(EEG(iEEG).chanlocs, 'label');
end
end
end
% standard checking
% -----------------
ALLEEG = EEG;
for inddataset = 1:length(ALLEEG)
EEG = ALLEEG(inddataset);
% additional checks
% -----------------
res = -1; % error code
if ~isempty( varargin)
for index = 1:length( varargin )
switch varargin{ index }
case 'data',; % already done at the top
case 'contdata',
if EEG.trials > 1
errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
return;
end
case 'ica',
if isempty(EEG.icaweights)
errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
return;
end
case 'epoch',
if EEG.trials == 1
errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
return
end
case 'besa',
if ~isfield(EEG, 'sources')
errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
, '2) Run BESA to localize the equivalent dipoles', ...
'3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
return
end
case 'event',
if isempty(EEG.event)
errordlg2(strvcat('Requires events. You need to add events first.', ...
'Use "File > Import event info" or "File > Import epoch info"', ...
'Install plugin VidEd to manually add events as you scroll the data.' ), 'Error');
return;
end
case 'chanloc',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end
case 'chanlocs_homogeneous',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end
if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
EEG = eeg_checkchanlocs(EEG);
% EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
res = ['EEG = eeg_checkset(EEG, ''chanlocs_homogeneous''); ' ];
end
case 'chanlocsize',
if ~isempty(EEG.chanlocs)
if length(EEG.chanlocs) > EEG.nbchan
questdlg2(strvcat('Warning: there is one more electrode location than', ...
'data channels. EEGLAB will consider the last electrode to be the', ...
'common reference channel. If this is not the case, remove the', ...
'extra channel'), 'Warning', 'Ok', 'Ok');
end
end
case 'makeur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent'),
EEG.event = rmfield(EEG.event, 'urevent');
disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
else
disp('eeg_checkset note: creating the original event table (EEG.urevent)');
end
EEG.urevent = EEG.event;
for index = 1:length(EEG.event)
EEG.event(index).urevent = index;
end
end
case 'checkur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent') && ~isempty(EEG.urevent)
urlatencies = [ EEG.urevent.latency ];
[newlat tmpind] = sort(urlatencies);
if ~isequal(newlat, urlatencies)
EEG.urevent = EEG.urevent(tmpind);
[tmp tmpind2] = sort(tmpind);
for index = 1:length(EEG.event)
EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
end
end
end
end
case 'eventconsistency',
[EEG res] = eeg_checkset(EEG);
if isempty(EEG.event), return; end
% check events (slow)
% ------------
if isfield(EEG.event, 'type')
eventInds = arrayfun(@(x)isempty(x.type), EEG.event);
if any(eventInds)
eventInds = find(eventInds);
eventInds = eventInds(:)'; % make row vector
if all(arrayfun(@(x)isnumeric(x.type), EEG.event))
for ind = eventInds, EEG.event(ind).type = NaN; end
else for ind = eventInds, EEG.event(ind).type = 'empty'; end
end
end
if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end
EEG = eeg_checkset(EEG, 'eventconsistency');
end
end
% Removing events with NaN latency
% --------------------------------
if isfield(EEG.event, 'latency')
nanindex = find(isnan([ EEG.event.latency ]));
if ~isempty(nanindex)
EEG.event(nanindex) = [];
trialtext = '';
for inan = 1:length(nanindex)
trialstext = [trialtext ' ' num2str(nanindex(inan))];
end
disp(sprintf(['eeg_checkset: Event(s) with NaN latency were deleted \nDeleted event index(es):[' trialstext ']']));
end
end
% remove the events which latency are out of boundary
% ---------------------------------------------------
if isempty(EEG.event), return; end
if isfield(EEG.event, 'latency')
if isfield(EEG.event, 'type')
if eeg_isboundary(EEG.event(1)) && isfield(EEG.event, 'duration')
if EEG.event(1).duration < 1
EEG.event(1) = [];
elseif EEG.event(1).latency > 0 && EEG.event(1).latency < 1
EEG.event(1).latency = 0.5;
end
end
end
try
tmpevent = EEG.event;
alllatencies = [tmpevent.latency];
catch
error('Checkset: error empty latency entry for new events added by user');
end
I1 = find(alllatencies < 0.5);
I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included
% because, if data epochs are extracted from -1 to
% time 0, this allow to include the last event in
% the last epoch (otherwise all epochs have an
% event except the last one
if (length(I1) + length(I2)) > 0
fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
length(I1) + length(I2), length(EEG.event));
EEG.event(union(I1, I2)) = [];
end
end
if isempty(EEG.event), return; end
% save information for non latency fields updates
% -----------------------------------------------
difffield = [];
if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
% remove fields with empty epochs
% -------------------------------
removeevent = [];
try
tmpevent = EEG.event;
allepochs = [ tmpevent.epoch ];
removeevent = find( allepochs < 1 | allepochs > EEG.trials);
if ~isempty(removeevent)
disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
end
catch
for indexevent = 1:length(EEG.event)
if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
|| EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
removeevent = [removeevent indexevent];
disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
end
end
end
EEG.event(removeevent) = [];
end
if isempty(EEG.event), return; end
% Duration set to 0 if empty
% --------------------------
if isfield(EEG.event, 'duration')
emptyDur = cellfun(@isempty, { EEG.event.duration });
if any(emptyDur)
for indexevent = find(emptyDur)
EEG.event(indexevent).duration = 0;
end
end
end
% uniformize fields (str or int) if necessary
% -------------------------------------------
fnames = fieldnames(EEG.event);
for fidx = 1:length(fnames)
fname = fnames{fidx};
if ~strcmpi(fname, 'mffkeys') && ~strcmpi(fname, 'mffkeysbackup')
tmpevent = EEG.event;
allvalues = { tmpevent.(fname) };
try
% find indices of numeric values among values of this event property
valreal = ~cellfun('isclass', allvalues, 'char');
catch
valreal = mycellfun('isclass', allvalues, 'double');
end
format = 'ok';
if ~all(valreal) % all valreal ok
format = 'str';
if all(valreal == 0) % all valreal=0 ok
format = 'ok';
end
end
if strcmp(format, 'str')
fprintf('eeg_checkset note: event field format ''%s'' made uniform\n', fname);
allvalues = cellfun(@num2str, allvalues, 'uniformoutput', false);
[EEG.event(valreal).(fname)] = deal(allvalues{find(valreal)});
end
end
end
% check boundary events
% ---------------------
tmpevent = EEG.event;
if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
boundsInd = eeg_findboundaries(EEG);
if ~isempty(boundsInd)
bounds = [ tmpevent(boundsInd).latency ];
% remove last event if necessary
if EEG.trials==1 %this if block added by James Desjardins (Jan 13th, 2014)
if round(bounds(end)-0.5) > size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
end
% The first boundary below need to be kept for
% urevent latency calculation
% if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any
indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
if ~isempty(indDoublet)
disp('Warning: duplicate boundary event removed');
if isfield(EEG.event, 'duration')
for indBound = 1:length(indDoublet)
EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
end
end
EEG.event(boundsInd(indDoublet)) = [];
end
end
end
if isempty(EEG.event), return; end
% check that numeric format is double (Matlab 7)
% -----------------------------------
allfields = fieldnames(EEG.event);
if ~isempty(EEG.event)
for index = 1:length(allfields)
tmpval = EEG.event(1).(allfields{index});
if isnumeric(tmpval) && ~isa(tmpval, 'double')
for indexevent = 1:length(EEG.event)
tmpval = getfield(EEG.event, { indexevent }, allfields{index} );
EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
end
end
end
end
% check duration field, replace empty by 0
% ----------------------------------------
if isfield(EEG.event, 'duration')
tmpevent = EEG.event;
try
valempt = cellfun('isempty' , { tmpevent.duration });
catch
valempt = mycellfun('isempty', { tmpevent.duration });
end
if any(valempt)
for index = find(valempt)
EEG.event(index).duration = 0;
end
end
end
% resort events
% -------------
if isfield(EEG.event, 'latency')
try
if isfield(EEG.event, 'epoch')
TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
else
TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
end
if ~isequal(TMPEEG.event, EEG.event)
EEG = TMPEEG;
disp('eeg_checkset note: events'' order (re)sorted by time');
end
catch
disp('eeg_checkset: problem when attempting to resort event latencies.');
end
end
% check latency of first event
% ----------------------------
if ~isempty(EEG.event)
if isfield(EEG.event, 'latency')
if EEG.event(1).latency < 0.5
EEG.event(1).latency = 0.5;
end
end
end
% build epoch structure
% ---------------------
try,
if EEG.trials > 1 && ~isempty(EEG.event)
% erase existing event-related fields
% ------------------------------
if ~isfield(EEG,'epoch')
EEG.epoch = [];
end
if ~isempty(EEG.epoch)
if length(EEG.epoch) ~= EEG.trials
disp('Warning: number of epoch entries does not match number of dataset trials;');
disp(' user-defined epoch entries will be erased.');
EEG.epoch = [];
else
fn = fieldnames(EEG.epoch);
EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
end
end
% set event field
% ---------------
tmpevent = EEG.event;
eventepoch = [tmpevent.epoch];
epochevent = cell(1,EEG.trials);
destdata = epochevent;
EEG.epoch(length(epochevent)).event = [];
for k=1:length(epochevent)
epochevent{k} = find(eventepoch==k);
end
tmpepoch = EEG.epoch;
[tmpepoch.event] = epochevent{:};
EEG.epoch = tmpepoch;
maxlen = max(cellfun(@length,epochevent));
% copy event information into the epoch array
% -------------------------------------------
eventfields = fieldnames(EEG.event)';
eventfields = eventfields(~strcmp(eventfields,'epoch'));
tmpevent = EEG.event;
for k = 1:length(eventfields)
fname = eventfields{k};
switch fname
case 'latency'
sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
sourcedata = num2cell(sourcedata);
case 'duration'
sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
otherwise
sourcedata = {tmpevent.(fname)};
end
if maxlen == 1
destdata = cell(1,length(epochevent));
destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
else
for l=1:length(epochevent)
destdata{l} = sourcedata(epochevent{l});
end
end
tmpepoch = EEG.epoch;
[tmpepoch.(['event' fname])] = destdata{:};
EEG.epoch = tmpepoch;
end
end
catch
errordlg2(['Warning: minor problem encountered when generating' 10 ...
'the EEG.epoch structure (used only in user scripts)']); return;
end
case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
otherwise, error('eeg_checkset: unknown option');
end
end
end
res = [];
% check name consistency
% ----------------------
if ~isempty(EEG.setname)
if ~ischar(EEG.setname)
EEG.setname = '';
else
if size(EEG.setname,1) > 1
disp('eeg_checkset warning: invalid dataset name, removed');
EEG.setname = '';
end
end
else
EEG.setname = '';
end
% checking history and convert if necessary
% -----------------------------------------
if isfield(EEG, 'history') && size(EEG.history,1) > 1
allcoms = cellstr(EEG.history);
EEG.history = deblank(allcoms{1});
for index = 2:length(allcoms)
EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
end
end
% read data if necessary
% ----------------------
if ischar(EEG.data) && nargin > 1
if strcmpi(varargin{1}, 'loaddata')
EEG.data = eeg_getdatact(EEG);
end
end
% save data if necessary
% ----------------------
if nargin > 1
% datfile available?
% ------------------
datfile = 0;
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
datfile = 1;
end
end
% save data
% ---------
if strcmpi(varargin{1}, 'savedata') && option_storedisk
error('eeg_checkset: cannot call savedata any more');
% the code below is deprecated
if ~ischar(EEG.data) % not already saved
disp('Writing previous dataset to disk...');
if datfile
tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
EEG.data = EEG.datfile;
end
EEG.icaact = [];
% saving dataset
% --------------
filename = fullfile(EEG(1).filepath, EEG(1).filename);
if ~ischar(EEG.data) && option_single, EEG.data = single(EEG.data); end
v = version;
if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
else save( filename, '-mat', 'EEG');
end
if ~ischar(EEG.data), EEG.data = 'in set file'; end
% res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
res = ['EEG = eeg_checkset( EEG, ''savedata'');'];
end
end
end
% numerical format
% ----------------
if isnumeric(EEG.data)
v = version;
EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
EEG.icaweights = double(EEG.icaweights);
EEG.icasphere = double(EEG.icasphere);
if ~isempty(findstr(v, 'R11')) || ~isempty(findstr(v, 'R12')) || ~isempty(findstr(v, 'R13'))
EEG.data = double(EEG.data);
EEG.icaact = double(EEG.icaact);
else
try,
if isa(EEG.data, 'double') && option_single
EEG.data = single(EEG.data);
EEG.icaact = single(EEG.icaact);
end
catch,
disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).');
disp(' Then reload it.');
end
end
end
% verify the type of the variables
% --------------------------------
% data dimensions -------------------------
if isnumeric(EEG.data) && ~isempty(EEG.data)
if ~isequal(size(EEG.data,1), EEG.nbchan)
disp( [ 'eeg_checkset warning: number of rows in data (' int2str(size(EEG.data,1)) ...
') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
res = com;
EEG.nbchan = size(EEG.data,1);
end
if (ndims(EEG.data)) < 3 && (EEG.pnts > 1)
if mod(size(EEG.data,2), EEG.pnts) ~= 0
fprintf(2, 'eeg_checkset error: binary data file likely truncated, importing anyway...\n');
if EEG.trials > 1
EEG.trials = floor(size(EEG.data,2)/EEG.pnts);
EEG.data(:,EEG.trials*EEG.pnts+1:end) = [];
res = com;
else
EEG.pnts = size(EEG.data,2);
res = com;
end
else
if EEG.trials > 1
disp( 'eeg_checkset note: data array made 3-D');
res = com;
end
if size(EEG.data,2) ~= EEG.pnts
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
end
end
end
% size of data -----------
if size(EEG.data,3) ~= EEG.trials
disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
res = com;
EEG.trials = size(EEG.data,3);
end
if size(EEG.data,2) ~= EEG.pnts
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
res = com;
EEG.pnts = size(EEG.data,2);
end
end
% xmin must be 0 for continuous data or
% pop_select does not behave correctly when
% removing data points
% --------------------
if EEG.trials == 1 && EEG.xmin ~= 0
EEG.xmin = 0;
fprintf( 'eeg_checkset note: xmin set to 0 for continuous data\n');
res = com;
end
% parameters consistency
% -------------------------
if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
if EEG.srate == 0
EEG.srate = 1;
end
EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
res = com;
end
% deal with event arrays
% ----------------------
if ~isfield(EEG, 'event'), EEG.event = []; res = com; end
if ~isempty(EEG.event)
if EEG.trials > 1 && ~isfield(EEG.event, 'epoch')
if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error(): user abort');
%res = com;
%EEG.event = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: no epoch field in event structure');
end
end
else
EEG.event = [];
end
if isfield(EEG, 'urevent') && ~isempty(EEG.urevent) && ~isfield(EEG.event, 'urevent') && ~isempty(EEG.event)
warning('Inconsistency between urevent (backup) and event structures, removing urevent structure');
EEG.urevent = [];
end
if isempty(EEG.event)
EEG.eventdescription = {};
end
if ~isfield(EEG, 'eventdescription') || ~iscell(EEG.eventdescription)
EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
res = com;
else
if ~isempty(EEG.event)
if length(EEG.eventdescription) > length( fieldnames(EEG.event))
EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
end
end
end
% create urevent if continuous data
% ---------------------------------
%if ~isempty(EEG.event) && ~isfield(EEG, 'urevent')
% EEG.urevent = EEG.event;
% disp('eeg_checkset note: creating the original event table (EEG.urevent)');
% for index = 1:length(EEG.event)
% EEG.event(index).urevent = index;
% end
%end
if isfield(EEG, 'urevent') && isfield(EEG.urevent, 'urevent')
EEG.urevent = rmfield(EEG.urevent, 'urevent');
end
% deal with epoch arrays
% ----------------------
if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end
% check if only one epoch
% -----------------------
if EEG.trials == 1
if isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch'); res = com;
end
if ~isempty(EEG.epoch)
EEG.epoch = []; res = com;
end
end
if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end
if ~isempty(EEG.epoch)
if isstruct(EEG.epoch), l = length( EEG.epoch);
else l = size( EEG.epoch, 2);
end
if l ~= EEG.trials
if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.epoch = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: epoch structure size invalid');
end
end
else
EEG.epoch = [];
end
% check ica
% ---------
if ~isfield(EEG, 'icachansind')
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end
elseif isempty(EEG.icachansind)
if ~isempty(EEG.icaweights)
EEG.icachansind = [1:EEG.nbchan]; res = com;
end
end
if ~isempty(EEG.icasphere)
if ~isempty(EEG.icaweights)
if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end
end
if isnumeric(EEG.data)
if length(EEG.icachansind) ~= size(EEG.icasphere,2)
if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end
end
if isempty(EEG.icaact) || (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) || (size(EEG.icaact,2) ~= size(EEG.data,2))
EEG.icaweights = double(EEG.icaweights);
EEG.icawinv = double(EEG.icawinv);