-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbids_reexport.m
278 lines (248 loc) · 10.5 KB
/
bids_reexport.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
% BIDS_REEXPORT - re-export BIDS dataset (dataset which was imported in
% EEGLAB) as a BIDS derivative
% Usage:
% bids_reexport(ALLEEG, key, val);
%
% Input:
% ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
% 'generatedBy' - [struct] structure indicating how the data was generated.
% For example:
% generatedBy.Name = 'NEMAR-pipeline';
% generatedBy.Description = 'A validated EEG pipeline for preprocessing and decomposition of EEG datasets';
% generatedBy.Version = '1.0';
% generatedBy.CodeURL = 'https://github.com/sccn/NEMAR-pipeline/blob/main/eeg_nemar_preprocess.m';
% generatedBy.desc = 'nemar'; % optional description for file naming
%
% 'checkderivative' - [string] provide a folder as a string containing
% the original BIDS repository and check that the folder
% names are identical. If not, issue an error.
%
% 'targetdir' - [string] target directory. Default is 'bidsexport' in the
% current folder.
%
% Author: Arnaud Delorme, 2023
% Copyright (C) 2023 Arnaud Delorme
%
% 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.
function bids_reexport(ALLEEG1, varargin)
if ~isfield(ALLEEG1, 'task') || ~isfield(ALLEEG1, 'BIDS')
error('Task or BIDS field not found in array of EEG');
end
opt = finputcheck(varargin, { ...
'generatedBy' 'struct' {} struct([]); ...
'checkderivative' 'string' {} ''; ...
'targetdir' 'string' {} fullfile(pwd, 'bidsexport'); ...
}, 'bids_reexport');
if isstr(opt), error(opt); end
% Set up derivative directory
derivativeDir = fullfile(opt.targetdir, 'derivatives', 'eeglab');
if ~exist(derivativeDir, 'dir')
mkdir(derivativeDir);
end
% export the data
% ---------------
if isempty(opt.generatedBy)
opt.generatedBy(1).Name = 'EEGLAB';
opt.generatedBy(1).Description = 'EEGLAB BIDS derivative processing pipeline';
opt.generatedBy(1).Version = eeg_getversion;
opt.generatedBy(1).CodeURL = 'https://github.com/sccn/eeglab';
end
tasks = unique({ ALLEEG1.task });
if length(tasks) == 1
tasks = tasks{1};
else
tasks = 'Multiple';
end
BIDS = ALLEEG1(1).BIDS;
if ~isfield(BIDS.gInfo, 'README')
BIDS.gInfo.README = '';
end
if ~isfield(BIDS.gInfo, 'CHANGES')
BIDS.gInfo.CHANGES = '';
end
% Set up derivative dataset description while preserving existing values
if ~isfield(BIDS.gInfo, 'Name')
BIDS.gInfo.Name = 'EEGLAB derivatives';
end
if ~isfield(BIDS.gInfo, 'BIDSVersion')
BIDS.gInfo.BIDSVersion = '1.8.0';
end
if ~isfield(BIDS.gInfo, 'PipelineDescription')
BIDS.gInfo.PipelineDescription.Name = opt.generatedBy(1).Name;
BIDS.gInfo.PipelineDescription.Version = opt.generatedBy(1).Version;
BIDS.gInfo.PipelineDescription.Description = opt.generatedBy(1).Description;
end
if ~isfield(BIDS.gInfo, 'GeneratedBy')
BIDS.gInfo.GeneratedBy = opt.generatedBy;
end
% Handle source dataset tracking
if isfield(BIDS.gInfo, 'DatasetDOI')
if ~isfield(BIDS.gInfo, 'SourceDatasets')
BIDS.gInfo.SourceDatasets.DOI = BIDS.gInfo.DatasetDOI;
end
BIDS.gInfo = rmfield(BIDS.gInfo, 'DatasetDOI');
end
% Write derivative dataset description
jsonwrite(fullfile(derivativeDir, 'dataset_description.json'), BIDS.gInfo, struct('indent',' '));
% Group files by subject
uniqueSubjects = unique({ALLEEG1.subject});
for i = 1:length(uniqueSubjects)
% Find all files for this subject
subjectIndices = find(strcmp({ALLEEG1.subject}, uniqueSubjects{i}));
% Initialize arrays for this subject's files
data(i).file = cell(1, length(subjectIndices));
data(i).task = cell(1, length(subjectIndices));
data(i).run = zeros(1, length(subjectIndices));
data(i).session = zeros(1, length(subjectIndices));
% Fill in data for each file
for j = 1:length(subjectIndices)
idx = subjectIndices(j);
data(i).file{j} = fullfile(ALLEEG1(idx).filepath, ALLEEG1(idx).filename);
data(i).task{j} = ALLEEG1(idx).task;
data(i).run(j) = ALLEEG1(idx).run;
data(i).session(j) = ALLEEG1(idx).session;
end
end
% Reconstruct pInfo by aggregating data from all subjects while preserving order
% First, find the first subject that has pInfo to establish initial field order
allFields = {};
for i = 1:length(ALLEEG1)
if isfield(ALLEEG1(i).BIDS, 'pInfo') && ~isempty(ALLEEG1(i).BIDS.pInfo)
allFields = ALLEEG1(i).BIDS.pInfo(1,:);
break;
end
end
% Then add any additional fields from other subjects while preserving order
for i = 1:length(ALLEEG1)
if isfield(ALLEEG1(i).BIDS, 'pInfo') && ~isempty(ALLEEG1(i).BIDS.pInfo)
newFields = ALLEEG1(i).BIDS.pInfo(1,:);
for j = 1:length(newFields)
if ~ismember(newFields{j}, allFields)
allFields{end+1} = newFields{j};
end
end
end
end
% Create new pInfo cell array with headers
if ~isempty(allFields)
BIDS.pInfo = cell(length(uniqueSubjects) + 1, length(allFields));
BIDS.pInfo(1,:) = allFields;
% Fill in values for each subject
for i = 1:length(uniqueSubjects)
subjectIdx = find(strcmp({ALLEEG1.subject}, uniqueSubjects{i}), 1);
if isfield(ALLEEG1(subjectIdx).BIDS, 'pInfo') && ~isempty(ALLEEG1(subjectIdx).BIDS.pInfo)
for j = 1:length(allFields)
fieldIdx = find(strcmp(allFields{j}, ALLEEG1(subjectIdx).BIDS.pInfo(1,:)));
if ~isempty(fieldIdx)
BIDS.pInfo(i+1,j) = ALLEEG1(subjectIdx).BIDS.pInfo(2,fieldIdx);
end
end
end
end
end
% Compare with original data if available
if ~isempty(opt.checkderivative)
try
% Import original BIDS dataset
[~, ALLEEG2] = pop_importbids(opt.checkderivative, 'subjects', 1, 'bidschanloc','on','bidsevent', 'on');
% Compare first dataset to determine changes
ALLEEG1(1) = eeg_compare_bids(ALLEEG1(1), ALLEEG2(1));
% Only add desc if changes were detected
if ALLEEG1(1).etc.compare.data_changed || ...
ALLEEG1(1).etc.compare.events_changed || ...
ALLEEG1(1).etc.compare.chanlocs_changed
% Build desc based on what changed using camelCase
changes = {};
if ALLEEG1(1).etc.compare.data_changed
changes{end+1} = 'data';
end
if ALLEEG1(1).etc.compare.events_changed
changes{end+1} = 'events';
end
if ALLEEG1(1).etc.compare.chanlocs_changed
changes{end+1} = 'electrodes';
end
% Convert changes to camelCase and combine
if ~isempty(changes)
% Capitalize first letter of each word except first
for i = 1:length(changes)
if i > 1
changes{i} = [upper(changes{i}(1)) changes{i}(2:end)];
end
end
desc = strjoin(changes, '');
% Set desc in generatedBy
if isfield(opt.generatedBy, 'desc')
desc = [opt.generatedBy.desc desc];
end
opt.generatedBy.desc = desc;
end
end
catch
warning('Could not load or compare with original dataset.');
end
end
% Check to see if BIDS has all the needed fileds, otherwise borrow from ALLEEG2
required_fields = {'gInfo', 'pInfo', 'pInfoDesc', 'tInfo', 'eInfo', 'scannedElectrodes', 'eInfoDesc'};
for i = 1:length(required_fields)
if ~isfield(BIDS, required_fields{i}) || isempty(BIDS.(required_fields{i}))
if exist('ALLEEG2', 'var') && isfield(ALLEEG2(1).BIDS, required_fields{i})
BIDS.(required_fields{i}) = ALLEEG2(1).BIDS.(required_fields{i});
warning('bids_reexport, the BIDS structure is missing required field %s, borrowing from original dataset', required_fields{i});
else
warning('bids_reexport, the BIDS structure is missing required field %s, the program may likely crash', required_fields{i});
end
end
end
if isempty(opt.generatedBy)
BIDS.gInfo.GeneratedBy = BIDS.gInfo.GeneratedBy;
else
BIDS.gInfo.GeneratedBy = opt.generatedBy;
end
if isempty(BIDS.pInfoDesc), BIDS.pInfoDesc = struct([]); end
% Set up export options
options = { 'targetdir', derivativeDir, ...
'taskName', tasks,...
'gInfo', BIDS.gInfo, ...
'pInfo', BIDS.pInfo, ...
'pInfoDesc', BIDS.pInfoDesc, ...
'README', BIDS.gInfo.README, ...
'CHANGES', BIDS.gInfo.CHANGES, ...
'renametype', {}, ...
'tInfo', BIDS.tInfo, ...
'eInfo', BIDS.eInfo };
if isfield(BIDS, 'scannedElectrodes') && BIDS.scannedElectrodes
options = [ options { 'elecexport' 'on' } ];
end
% Export the data
bids_export(data, options{:});
% Compare with original if requested
if ~isempty(opt.checkderivative)
fprintf('Comparing BIDS folders %s vs %s\n', opt.checkderivative, derivativeDir);
bids_compare(opt.checkderivative, derivativeDir, false);
end