forked from sccn/EEG-BIDS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbids_export.m
715 lines (667 loc) · 29.8 KB
/
bids_export.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
% bids_export - this function allows converting a collection of datasets to
% BIDS formated folders and files.
%
% Usage:
% bids_export(files, varargin)
%
% Input:
% files - Structure with the fields 'file','session' and 'run'.
% The field 'file' should be a cell array of strings
% with the path to the data files. The fields 'session'
% and 'run' will contain the session index and the run index
% within the session for the corresponding data file in the
% same index. See example below for a case with 2 subjects with
% 2 sessions and 2 run each:
% subject(1).file = {'subj-1_ss-1-run1' 'subj-1_ss-1-run2' 'subj-1_ss-2-run1' 'subj-1_ss-2-run2'};
% subject(1).session = [ 1 1 2 2 ];
% subject(1).run = [ 1 2 1 2 ];
% subject(1).file = {'subj-2_ss-1-run1' 'subj-2_ss-1-run2' 'subj-2_ss-2-run1' 'subj-2_ss-2-run2'};
% subject(2).session = [ 1 1 2 2 ];
% subject(2).run = [ 1 2 1 2 ];
%
% Optional inputs:
% 'targetdir' - [string] target directory. Default is 'bidsexport' in the
% current folder.
%
% 'taskname' - [string] name of the task. No space are allowed and no
% special characters. Default is ''.
%
% 'README' - [string] content of the README file. If the string points
% to a file that exists on the path, the file is copied.
% Otherwise a new README file is created and the content of
% this variable is copied to the new file.
%
% 'CHANGES' - [string] content of the README file. If the string points
% to a file that exists on the path, the file is copied.
%
% 'codefiles' - [cell] cell array of file names containing code related
% to importing or processing the data.
%
% 'stimuli' - [cell] cell array of type and corresponding file names.
% For example: { 'sound1' '/Users/xxxx/sounds/sound1.mp3';
% 'img1' '/Users/xxxx/sounds/img1.jpg' }
% (the semicolumn above is optional)
%
% 'gInfo' - [struct] general information fields. See BIDS specifications.
% For example.
% info.ReferencesAndLinks = { 'Pubmed 122032020' };
% info.Name = 'This is a custom task';
% info.License = 'Creative commons';
%
% 'tInfo' - [struct] task information fields. See BIDS specifications.
% For example.
% tInfo.InstitutionAddress = '9500 Gilman Drive, CA92093-0559 La Jolla, USA';
% tInfo.InstitutionName = 'Univesity of California, San Diego';
% tInfo.InstitutionalDepartmentName = 'Institute of Neural Computation';
% tInfo.PowerLineFrequency = 50;
% tInfo.SoftwareFilters = struct('NotchFilter', struct('cutof', '50 (Hz)'));
%
% 'pInfo' - [cell] cell array of participant values, with one row
% per participants. The first row contains columns names.
% For example for 2 participants:
% { 'sex' 'age';
% 'male' 20;
% 'female' 25 };
%
% 'pInfoDesc' - [struct] structure describing participant file columns.
% The fields are described in the BIDS format.
% For example
% pInfo.participant_id.LongName = 'Participant ID';
% pInfo.participant_id.Description = 'Event onset';
% pInfo.sex.LongName = 'Gender';
% pInfo.sex.Description = 'Gender';
% pInfo.age.LongName = 'Age';
% pInfo.age.Description = 'Age in years';
%
% 'eInfo' - [cell] additional event information columns and their corresponding
% event fields in the EEGLAB event structure. Note that
% EEGLAB event latency, duration, and type are inserted
% automatically as columns "onset" (latency in sec), "duration"
% (duration in sec), "event_sample" (latency), "event_type"
% (time locking event), "event_value" (type). For example
% { 'HED' 'reaction_time';
% 'HED' 'rt' }
%
% 'eInfoDesc' - [struct] structure describing additional or/and original
% event fields if you wish to redefine these.
% These are EEGLAB event fields listed above.
% See the BIDS format for more information
% eInfo.onset.LongName = 'Event onset'; % change default value
% eInfo.onset.Description = 'Event onset';
% eInfo.onset.Units = 'seconds';
% eInfo.HED.LongName = 'Hierarchival Event Descriptors';
% eInfo.reaction_time.LongName = 'Reaction time';
% eInfo.reaction_time.Units = 'seconds';
%
% 'cInfo' - [cell] cell array containing the field names for the
% channel file in addition to the channel "name", "type" and
% "unit" which are extracted from the channel location
% structure. For example, to add the reference as an
% additional column:
% {'reference';
% 'ref' }
%
% 'cInfoDesc' - [struct] structure describing additional or/and original
% channel fields if you wish to redefine these.
% cInfo.name.LongName = 'Channel name'; % change default description
% cInfo.name.Description = 'Channel name';
% cInfo.reference.LongName = 'Channel reference';
% cInfo.reference.Description = 'Channel reference montage 10/20';
%
% 'trialtype' - [cell] 2 column cell table indicating the type of event
% for each event type. For example { '2' 'stimulus';
% '4' 'stimulus';
% '128' 'response' }
%
% 'chanlocs' - [cell or struct or file name] channel location structure or file
% name to use when saving channel information. Note that
% this assumes that all the files have the same number of
% channels. If a cell array is given as input, the size
% must be the same as the one used for files given as input.
%
% 'copydata' -[0|1] While exporting EEGLAB data to BIDS (.set, .fdt), this flag
% will enable the copy of all the data files [1], or just create the
% BIDS files hierarchy without the large data files [0]. This
% options is aimed to be used to speedup the troubleshooting
% of bids_export execution. Default: [1]
%
% Validation:
% If the BIDS data created with this function fails to pass the BIDS
% validator (npm install -g https://github.com/bids-standard/bids-validator.git
% Usage bids-validator/bin/bids-validator --bep006 bidsfolder), please
% email [email protected]
%
% Example: The following examples will pass the bids validator.
% data(1).file = 'subject1.set'; data(1).run = 1; data(1).session = 1;
% data(2).file = 'subject2.set'; data(2).run = 1; data(2).session = 1;
% bids_export(data);
%
% Note that important information might be missing. For example, line noise
% is set to 0. Use input 'tInfo' to set the line noise as below.
%
% bids_export( data, 'tInfo', struct('PowerLineFrequency', 50 );
%
% In general, you will want to describe your events and include as much
% information as possible. A detailed and comprehensive example is provided
% in bids_export_example.m
%
%
% Authors: Arnaud Delorme, 2019
% Ramon Martinez-Cancino, 2019
% Tyler K. Collins, 2019
% The following are automatically
% populated using channel structure info ('eeg', 'ecg', 'emg', 'eog', 'trigger')
% tInfo.ECGChannelCount = xxx;
% tInfo.EEGChannelCount = xxx;
% tInfo.EMGChannelCount = xxx;
% tInfo.EOGChannelCount = xxx;
% tInfo.MiscChannelCount = xxx;
% tInfo.TriggerChannelCount = xxx;
% tInfo.EEGReference = xxx;
% tInfo.EpochLength = xxx;
% tInfo.RecordingDuration = xxx;
% tInfo.SamplingFrequency = xxx;
% tInfo.TaskName = 'meditation';
% However, they may be overwritten man.
function bids_export(files, varargin)
if nargin < 1
help bids_format_eeglab;
return
end
if ~exist('savejson')
addpath(fullfile(fileparts(which(mfilename)), 'jsonlab'));
end
opt = finputcheck(varargin, {'ReferencesAndLinks' 'cell' {} { 'n/a' };
'Name' 'string' {} 'n/a';
'License' 'string' {} 'n/a';
'targetdir' 'string' {} fullfile(pwd, 'bidsexport');
'taskName' 'string' {} 'Experiment';
'codefiles' 'cell' {} {};
'stimuli' 'cell' {} {};
'pInfo' 'cell' {} {};
'eInfo' 'cell' {} {};
'cInfo' 'cell' {} {};
'bidsOpt' 'struct' {} struct([]);
'gInfo' 'struct' {} struct([]);
'tInfo' 'struct' {} struct([]);
'pInfoDesc' 'struct' {} struct([]);
'eInfoDesc' 'struct' {} struct([]);
'cInfoDesc' 'struct' {} struct([]);
'trialtype' 'cell' {} {};
'chanlocs' '' {} '';
'README' 'string' {} '';
'CHANGES' 'string' {} '';
'coordsys' 'string' {} '';
'copydata' 'real' [0 1] 1 }, 'bids_format_eeglab');
if isstr(opt), error(opt); end
if size(opt.stimuli,1) == 1 || size(opt.stimuli,1) == 1
opt.stimuli = reshape(opt.stimuli, [2 length(opt.stimuli)/2])';
end
% deleting folder - only if internal use is disabled.
fprintf('Exporting data to %s...\n', opt.targetdir);
if exist(opt.targetdir,'dir') && ~opt.bidsOpt.InteralUse
disp('Deleting folder...')
rmdir(opt.targetdir, 's');
end
disp('Creating directories...')
mkdir( fullfile(opt.targetdir, 'code'));
mkdir( fullfile(opt.targetdir, 'stimuli'));
% write dataset info (dataset_description.json)
% ---------------------------------------------
gInfoFields = { 'ReferencesAndLinks' 'required' 'cell' { 'n/a' };
'Name' 'required' 'char' '';
'License' 'required' 'char' 'CC0';
'BIDSVersion' 'required' 'char' '1.1.1' ;
'Authors' 'optional' 'cell' { 'n/a' };
'Acknowledgements' 'optional' 'char' '';
'HowToAcknowledge' 'optional' 'char' '';
'byJson' 'required' 'logical' false;
'Funding' 'optional' 'cell' { 'n/a' };
'DatasetDOI' 'optional' 'char' { 'n/a' }};
opt.gInfo = checkfields(opt.gInfo, gInfoFields, 'gInfo');
% Handles how arrays are loaded in via json and that it aggravates matlab
toFix = find(strcmp(gInfoFields(:,3),'cell'));
if ~isempty(toFix) && opt.gInfo.byJson
opt.gInfo = jsonArrayFix(opt.gInfo,gInfoFields(toFix));
end
opt.gInfo = rmfield(opt.gInfo,'byJson');
savejson('',opt.gInfo,fullfile(opt.targetdir, 'dataset_description.json'));
% Correction for files array when loading by json
if isfield(files,'byJson') && files.byJson
% Trim off the extra field
mainFiles = files.dataStruct;
% Rebuild the struct explicitly
newStruct = struct;
for i=1:length(mainFiles)
newStruct(i).file = mainFiles{i}.file;
newStruct(i).session = mainFiles{i}.session;
newStruct(i).run = mainFiles{i}.run;
if isfield(mainFiles{i},'subID')
newStruct(i).subID = mainFiles{i}.subID;
end
end
% Correct the cell array syntax/typing and overwrite files struct
for i=1:length(newStruct)
newStruct(i) = jsonArrayFix(newStruct(i),{'file'});
end
files = newStruct;
end
% write participant information (participants.tsv)
% -----------------------------------------------
if ~isempty(opt.pInfo)
participants = { 'participant_id' };
for iSubj=1:length(files)
participants{iSubj+1, 1} = sprintf('sub-%3.3d', iSubj);
end
if ~isempty(opt.pInfo)
if size(opt.pInfo,1) ~= length(participants)
error(sprintf('Wrong number of participant (%d) in tInfo structure, should be %d based on the number of files', size(opt.pInfo,1)-1, length(files)));
end
participants(:,2:size(opt.pInfo,2)+1) = opt.pInfo;
end
writetsv(fullfile(opt.targetdir, 'participants.tsv'), participants);
end
% write participants field description (participants.json)
% --------------------------------------------------------
descFields = { 'LongName' 'optional' 'char' '';
'Levels' 'optional' 'struct' {};
'Description' 'optional' 'char' '';
'Units' 'optional' 'char' '';
'TermURL' 'optional' 'char' '' };
if ~isempty(opt.pInfo)
fields = fieldnames(opt.pInfoDesc);
if ~isempty(setdiff(fields, participants(1,:)))
error('Some field names in the pInfoDec structure do not have a corresponding column name in pInfo');
end
fields = participants(1,:);
for iField = 1:length(fields)
descFields{1,4} = fields{iField};
if ~isfield(opt.pInfoDesc, fields{iField}), opt.pInfoDesc(1).(fields{iField}) = struct([]); end
opt.pInfoDesc.(fields{iField}) = checkfields(opt.pInfoDesc.(fields{iField}), descFields, 'pInfoDesc');
end
savejson('',opt.pInfoDesc,fullfile(opt.targetdir, 'participants.json'));
end
% write event file information (task-xxxxx_events.json)
% ----------------------------
events = { 'onset' 'duration' };
fields = fieldnames(opt.eInfoDesc);
% if ~ismember('onset', fields)
% disp('"onset" event field names in the eInfoDesc structure is missing, creating one');
% eInfoDesc.onset.Description = 'Event onset';
% eInfoDesc.onset.Units = 'second';
% end
% if ~ismember('onset', fields)
% disp('"duration" event field names in the eInfoDesc structure is missing, creating one');
% eInfoDesc.duration.Description = 'Event duration';
% eInfoDesc.duration.Units = 'second';
% end
for iField = 1:length(fields)
descFields{1,4} = fields{iField};
if ~isfield(opt.eInfoDesc, fields{iField}), opt.eInfoDesc(1).(fields{iField}) = struct([]); end
opt.eInfoDesc.(fields{iField}) = checkfields(opt.eInfoDesc.(fields{iField}), descFields, 'eInfoDesc');
end
savejson('',opt.eInfoDesc,fullfile(opt.targetdir, [ 'task-' opt.taskName '_events.json' ]));
% Write README files (README)
% ---------------------------
if ~isempty(opt.README)
if ~exist(opt.README)
fid = fopen(fullfile(opt.targetdir, 'README'), 'w');
if fid == -1, error('Cannot write README file'); end
fprintf(fid, '%s', opt.README);
fclose(fid);
else
copyfile(opt.README, fullfile(opt.targetdir, 'README'));
end
end
% Write CHANGES files (CHANGES)
% -----------------------------
if ~isempty(opt.CHANGES)
if ~exist(opt.CHANGES)
fid = fopen(fullfile(opt.targetdir, 'CHANGES'), 'w');
if fid == -1, error('Cannot write README file'); end
fprintf(fid, '%s', opt.CHANGES);
fclose(fid);
else
copyfile(opt.CHANGES, fullfile(opt.targetdir, 'CHANGES'));
end
end
% Write code files (code)
% -----------------------
if ~isempty(opt.codefiles)
for iFile = 1:length(opt.codefiles)
[~,fileName,Ext] = fileparts(opt.codefiles{iFile});
if ~isempty(dir(opt.codefiles{iFile}))
copyfile(opt.codefiles{iFile}, fullfile(opt.targetdir, 'code', [ fileName Ext ]));
else
fprintf('Warning: cannot find code file %s\n', opt.codefiles{iFile})
end
end
end
% Write stimulus files
% --------------------
if ~isempty(opt.stimuli)
if size(opt.stimuli,1) == 1, opt.stimuli = opt.stimuli'; end
for iStim = 1:size(opt.stimuli,1)
[~,fileName,Ext] = fileparts(opt.stimuli{iStim,1});
if ~isempty(dir(opt.stimuli{iStim,1}))
copyfile(opt.stimuli{iStim,1}, fullfile(opt.targetdir, 'stimuli', [ fileName Ext ]));
else
fprintf('Warning: cannot find stimulus file %s\n', opt.codefiles{iFile});
end
end
end
% check task info
% ---------------
opt.tInfo(1).TaskName = opt.taskName;
% load channel information
% ------------------------
chanlocs = {};
if ~isempty(opt.chanlocs) && isstr(opt.chanlocs)
opt.chanlocs = readlocs(opt.chanlocs);
end
if iscell(opt.chanlocs)
chanlocs = opt.chanlocs;
else
chanlocs = {};
for iSubj = 1:length(files)
nsessions = length(unique(files(iSubj).session));
if nsessions > 1 %iscell(files{iSubj})
for iSess = 1:nsessions %length(files{iSubj})
chanlocs{iSubj}{iSess} = opt.chanlocs;
end
else
chanlocs{iSubj} = opt.chanlocs;
end
end
end
% Heuristic for identifying multiple/single-run/sessions
%--------------------------------------------------------------------------
for iSubj = 1:length(files)
allsubjnruns(iSubj) = length(unique(files(iSubj).run));
allsubjnsessions(iSubj) = length(unique(files(iSubj).session));
end
tmpuniqueruns = unique(allsubjnruns);
tmpuniquesessions = unique(allsubjnsessions);
multsessionflag = 1;
if length(tmpuniquesessions) == 1 && tmpuniquesessions == 1
multsessionflag = 0;
end
multrunflag = 1;
if length(tmpuniqueruns) == 1 && tmpuniqueruns == 1
multrunflag = 0;
end
tmpsessrun = [multsessionflag multrunflag];
if tmpsessrun == [0 0] % Single-Session Single-Run
bidscase = 1';
elseif tmpsessrun == [0 1]% Single-Session Mult-Run
bidscase = 2';
elseif tmpsessrun == [1 0] % Mult-Session Single-Run
bidscase = 3;
elseif tmpsessrun == [1 1] % Mult-Session Mult-Run
bidscase = 4;
end
%--------------------------------------------------------------------------
% copy EEG files
% --------------
disp('Copying EEG files...')
for iSubj = 1:length(files)
if isfield(files(iSubj),'subID') && ~isempty(files(iSubj).subID)
subjectStr = ['sub-' files(iSubj).subID];
else
subjectStr = sprintf('sub-%3.3d', iSubj);
end
switch bidscase
case 1 % Single-Session Single-Run
fileOut = fullfile(opt.targetdir, subjectStr, 'eeg', [ subjectStr '_task-' opt.taskName '_eeg' files(iSubj).file{1}(end-3:end)]);
copy_data_bids( files(iSubj).file{1}, fileOut, opt.tInfo, opt.trialtype, chanlocs{iSubj}, opt.copydata, opt.bidsOpt, opt.coordsys);
case 2 % Single-Session Mult-Run
for iRun = 1:length(files(iSubj).run)
fileOut = fullfile(opt.targetdir, subjectStr, 'eeg', [ subjectStr '_task-' opt.taskName sprintf('_run-%2.2d', iRun) '_eeg' files(iSubj).file{iRun}(end-3:end) ]);
copy_data_bids( files(iSubj).file{iRun}, fileOut, opt.tInfo, opt.trialtype, chanlocs{iSubj}, opt.copydata, opt.bidsOpt, opt.coordsys);
end
case 3 % Mult-Session Single-Run
for iSess = 1:length(unique(files(iSubj).session))
fileOut = fullfile(opt.targetdir, subjectStr, sprintf('ses-%2.2d', iSess), 'eeg', [ subjectStr sprintf('_ses-%2.2d', iSess) '_task-' opt.taskName '_eeg' files(iSubj).file{iSess}(end-3:end)]);
copy_data_bids( files(iSubj).file{iSess}, fileOut, opt.tInfo, opt.trialtype, chanlocs{iSubj}{iSess}, opt.copydata, opt.bidsOpt, opt.coordsys);
end
case 4 % Mult-Session Mult-Run
for iSess = 1:length(unique(files(iSubj).session))
runindx = find(files(iSubj).session == iSess);
for iSet = runindx
iRun = files(iSubj).run(iSet);
fileOut = fullfile(opt.targetdir, subjectStr, sprintf('ses-%2.2d', iSess), 'eeg', [ subjectStr sprintf('_ses-%2.2d', iSess) '_task-' opt.taskName sprintf('_run-%2.2d', iRun) '_eeg' files(iSubj).file{iSet}(end-3:end)]);
copy_data_bids(files(iSubj).file{iSet}, fileOut, opt.tInfo, opt.trialtype, chanlocs{iSubj}{iSess}, opt.copydata, opt.bidsOpt, opt.coordsys);
end
end
end
end
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function copy_data_bids(fileIn, fileOut, tInfo, trialtype, chanlocs, copydata, bidsOpt, coordsys)
folderOut = fileparts(fileOut);
if ~exist(folderOut)
mkdir(folderOut);
end
if ~exist(fileOut)
end
% if BDF file anonymize records
[~,~,ext] = fileparts(fileOut);
if strcmpi(ext, '.bdf')
fileIDIn = fopen(fileIn,'rb','ieee-le'); % see sopen
fileIDOut = fopen(fileOut,'wb','ieee-le'); % see sopen
data = fread(fileIDIn, Inf);
data(9:9+160-1) = ' ';
fwrite(fileIDOut, data);
fclose(fileIDIn);
fclose(fileIDOut);
tInfo.EEGReference = 'CMS/DRL';
tInfo.Manufacturer = 'BIOSEMI';
EEG = pop_biosig(fileOut);
elseif strcmpi(ext, '.set')
[outfilepath, outfilename,outfileext] = fileparts(fileOut);
if copydata
EEG = pop_loadset(fileIn);
if strcmp(bidsOpt.FileExt,'edf')
pop_writeeeg(EEG, [outfilepath '/' outfilename '.edf'], 'TYPE','EDF');
else
EEG = pop_saveset(EEG, 'filename',[outfilename outfileext], 'filepath', outfilepath);
end
else
copyfile(fileIn, fileOut);
EEG = pop_loadset([outfilename outfileext],outfilepath, 'loadmode', 'info');
end
else
error('Data format not supported');
end
% write event file information
event_helper(fileOut, EEG, trialtype);
% Write channel file information (channels.tsv)
% Note: Consider using here electrodes_to_tsv.m
fid = fopen( [ fileOut(1:end-7) 'channels.tsv' ], 'w');
miscChannels = 0;
if ~isempty(chanlocs)
% Commenting this out for now as it relies on EEGLAB knowing which
% channels are what type. It doesn't.
% EEG.chanlocs = chanlocs;
end
if isempty(EEG.chanlocs)
fprintf(fid, 'name\n');
for iChan = 1:EEG.nbchan, printf(fid, 'E%d\n', iChan); end
else
fprintf(fid, 'name\ttype\tunits\n');
for iChan = 1:length(EEG.chanlocs)
if ~isfield(EEG.chanlocs, 'type') || isempty(EEG.chanlocs(iChan).type)
type = 'n/a';
else
type = EEG.chanlocs(iChan).type;
end
if strcmpi(type, 'eeg')
unit = 'microV';
else
unit = 'n/a';
miscChannels = miscChannels+1;
end
fprintf(fid, '%s\t%s\t%s\n', EEG.chanlocs(iChan).labels, type, unit);
end
end
fclose(fid);
% Write electrode file information (electrodes.tsv)
if ~isempty(EEG.chanlocs) && isfield(EEG.chanlocs, 'X') && ~isempty(EEG.chanlocs(1).X)
fid = fopen( [ fileOut(1:end-7) 'electrodes.tsv' ], 'w');
fprintf(fid, 'name\tx\ty\tz\n');
for iChan = 1:length(EEG.chanlocs)
if isempty(EEG.chanlocs(iChan).X)
fprintf(fid, '%s\tn/a\tn/a\tn/a\n', EEG.chanlocs(iChan).labels );
else
fprintf(fid, '%s\t%f\t%f\t%f\n', EEG.chanlocs(iChan).labels, EEG.chanlocs(iChan).X, EEG.chanlocs(iChan).Y, EEG.chanlocs(iChan).Z );
end
end
fclose(fid);
fid = fopen( [ fileOut(1:end-7) 'coordsystem.json' ], 'w');
fprintf(fid,'%s',coordsys);
fclose(fid);
end
% Write task information (eeg.json) Note: depends on channels
tInfo.EEGChannelCount = EEG.nbchan-miscChannels;
if miscChannels > 0
tInfo.MiscChannelCount = miscChannels;
end
if ~isfield(tInfo, 'EEGReference')
tInfo.EEGReference = EEG.ref;
end
if EEG.trials == 1
tInfo.RecordingType = 'continuous';
else
tInfo.RecordingType = 'epoched';
tInfo.EpochLength = EEG.pnts/EEG.srate;
end
tInfo.RecordingDuration = EEG.pnts/EEG.srate;
tInfo.SamplingFrequency = EEG.srate;
% jsonStr = jsonencode(tInfo);
% fid = fopen( [fileOut(1:end-7) 'eeg.json' ], 'w');
% fprintf(fid, '%s', jsonStr);
% fclose(fid);
tInfoFields = {...
'TaskName' 'REQUIRED' '' '';
'TaskDescription' 'RECOMMENDED' '' '';
'Instructions' 'RECOMMENDED' 'char' '';
'CogAtlasID' 'RECOMMENDED' 'char' '';
'CogPOID' 'RECOMMENDED' 'char' '';
'InstitutionName' 'RECOMMENDED' 'char' '';
'InstitutionAddress' 'RECOMMENDED' 'char' '';
'InstitutionalDepartmentName' ' RECOMMENDED' 'char' '';
'DeviceSerialNumber' 'RECOMMENDED' 'char' '';
'SamplingFrequency' 'REQUIRED' '' '';
'EEGChannelCount' 'REQUIRED' '' '';
'EOGChannelCount' 'REQUIRED' '' 0;
'ECGChannelCount' 'REQUIRED' '' 0;
'EMGChannelCount' 'REQUIRED' '' 0;
'EEGReference' 'REQUIRED' 'char' 'Unknown';
'PowerLineFrequency' 'REQUIRED' '' 0;
'EEGGround' 'RECOMMENDED ' 'char' '';
'MiscChannelCount' ' OPTIONAL' '' '';
'TriggerChannelCount' 'RECOMMENDED' 'double' '';
'EEGPlacementScheme' 'RECOMMENDED' 'char' '';
'Manufacturer' 'RECOMMENDED' 'char' '';
'ManufacturersModelName' 'OPTIONAL' 'char' '';
'CapManufacturer' 'RECOMMENDED' 'char' 'Unknown';
'CapManufacturersModelName' 'OPTIONAL' 'char' '';
'HardwareFilters' 'OPTIONAL' 'char' '';
'SoftwareFilters' 'REQUIRED' 'struct' 'n/a';
'RecordingDuration' 'RECOMMENDED' '' 'n/a';
'RecordingType' 'RECOMMENDED' 'char' '';
'EpochLength' 'RECOMMENDED' '' 'n/a';
'SoftwareVersions' 'RECOMMENDED' 'char' '';
'byJson' 'REQUIRED' 'logical' false;
'SubjectArtefactDescription' 'OPTIONAL' 'char' '' };
tInfo = checkfields(tInfo, tInfoFields, 'tInfo');
% Leaving the below code commented out for potential future use
% toFix = find(contains(tInfoFields(:,3),'cell'));
% if ~isempty(toFix) && opt.tInfo.byJson
% opt.tInfo = jsonArrayFix(opt.tInfo,gInfoFields(toFix));
% end
tInfo = rmfield(tInfo,'byJson');
savejson('',tInfo,[fileOut(1:end-7) 'eeg.json' ]);
% write channel information
% cInfo.name.LongName = 'Channel name';
% cInfo.name.Description = 'Channel name';
% cInfo.type.LongName = 'Channel type';
% cInfo.type.Description = 'Channel type';
% cInfo.units.LongName = 'Channel unit';
% cInfo.units.Description = 'Channel unit';
% jsonStr = jsonencode(cInfo);
% fid = fopen( [fileOut(1:end-7) 'channels.json' ], 'w');
% fprintf(fid, '%s', jsonStr);
% fclose(fid);
% check the fields for the structures
% -----------------------------------
function s = checkfields(s, f, structName)
fields = fieldnames(s);
diffFields = setdiff(fields, f(:,1)');
if ~isempty(diffFields)
error(sprintf('Invalid field name(s) %sfor structure %s', sprintf('%s ',diffFields{:}), structName));
end
for iRow = 1:size(f,1)
if isempty(s) || ~isfield(s, f{iRow,1})
if strcmpi(f{iRow,2}, 'required') % required or optional
if ~iscell(f{iRow,4})
fprintf('Warning: "%s" set to %s\n', f{iRow,1}, num2str(f{iRow,4}));
end
s = setfield(s, {1}, f{iRow,1}, f{iRow,4});
end
elseif ~isempty(f{iRow,3}) && ~isa(s.(f{iRow,1}), f{iRow,3})
% Special case for structs being allowed to be n/a
if strcmp(f{iRow,1},'SoftwareFilters')
disp([f{iRow,1} ' is n/a']);
else
error(sprintf('Parameter %s.%s must be a %s', structName, f{iRow,1}, f{iRow,3}));
end
end
end
% write JSON file
% ---------------
function writejson(fileName, matlabStruct)
jsonStr = jsonencode(matlabStruct);
fid = fopen(fileName, 'w');
if fid == -1, error('Cannot write file - make sure you have writing permission'); end
fprintf(fid, '%s', jsonStr);
fclose(fid);
% write TSV file
% --------------
function writetsv(fileName, matlabArray)
fid = fopen(fileName, 'w');
if fid == -1, error('Cannot write file - make sure you have writing permission'); end
for iRow=1:size(matlabArray,1)
for iCol=1:size(matlabArray,2)
if isempty(matlabArray{iRow,iCol})
disp('Empty value detected, replacing by n/a');
fprintf(fid, 'n/a');
elseif ischar(matlabArray{iRow,iCol})
fprintf(fid, '%s', matlabArray{iRow,iCol});
elseif isnumeric(matlabArray{iRow,iCol}) && rem(matlabArray{iRow,iCol},1) == 0
fprintf(fid, '%d', matlabArray{iRow,iCol});
elseif isnumeric(matlabArray{iRow,iCol})
fprintf(fid, '%1.10f', matlabArray{iRow,iCol});
else
error('Table values can only be string or numerical values');
end
if iCol ~= size(matlabArray,2)
fprintf(fid, '\t');
end
end
fprintf(fid, '\n');
end
fclose(fid);
% Helper function to fix the goofy problems with ingesting arrays and the
% dealing with them as cell arrays in matlab.
function outJson = jsonArrayFix(fixStruct, fields)
outJson = fixStruct;
for i=1:length(fields)
tempArray = cell(0);
oldArray = getfield(fixStruct,fields{i});
for j=1:length(oldArray)
hackyTrick = oldArray{j};
tempArray = [tempArray; hackyTrick{1}];
end
outJson = setfield(outJson,fields{i},tempArray');
end