forked from agahkarakuzu/ismrm20
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqMRFit_BIDS.m
385 lines (242 loc) · 10.3 KB
/
qMRFit_BIDS.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
function qMRFit_BIDS(inputDir)
try
BIDS = bids.layout(inputDir);
catch
error('Cannot load BIDS layout for the provided directory.');
end
% Create derivatives folder
derivDir = [BIDS.dir filesep 'derivatives' filesep 'qMRLab'];
if ~exist(derivDir, 'dir')
mkdir(derivDir);
end
BIDS_subjects = bids.query(BIDS,'subjects');
for sub_iter = 1:length(BIDS_subjects)
BIDS_types = bids.query(BIDS,'types','sub',BIDS_subjects(sub_iter));
for type_iter = 1:length(BIDS_types)
protomapper = getMapper(BIDS_types{type_iter});
if ~isempty(protomapper)
% This means that suffix has a correspondance in qMRLab
% Create subject folder under derivatives
curSubDir = [derivDir filesep 'sub-' BIDS_subjects{sub_iter}];
if ~exist(curSubDir, 'dir')
mkdir(curSubDir);
end
% If there are additional naming entities, other than those required
% for a grouping suffix, we need to iterate over them.
extra = checkExtraEntities(BIDS,protomapper,sub_iter,BIDS_types{type_iter});
if ~isempty(extra)
%TODO: Deal with more than one extra entities later.
extras = unique({BIDS.subjects(sub_iter).anat.(cell2mat(extra))});
for extra_iter = 1:length(extras)
files = bids.query(BIDS,'data','sub',BIDS_subjects(sub_iter),cell2mat(extra),extras(extra_iter),'type',BIDS_types(type_iter));
metas = bids.query(BIDS,'metadata','sub',BIDS_subjects(sub_iter),cell2mat(extra),extras(extra_iter),'type',BIDS_types(type_iter));
[Model,data] = qMRLabBIDSmapper(files,metas,protomapper);
disp(['Fitting ' Model.ModelName ' for ' 'sub-' BIDS_subjects{sub_iter} cell2mat(extra) ' ' extras{extra_iter}])
FitResults = FitData(data,Model,0);
FitResultsSave_nii(FitResults,files{1},curSubDir);
renameMapsSaveJsons(BIDS,files,BIDS_subjects{sub_iter},curSubDir,protomapper,Model.xnames,cell2mat(extra),extras{extra_iter});
% FIT HERE BUT MANAGE OUTPUT FOLDERS AND OUTPUT NAMES PROPERLY
% YOU NEED TO CREATE DERIVATIVES FOLDER/SUBJECT/qMRLab
%
end
else
% TODO: Put 47-52 into a function and manage here as well.
end
end
end
end
end
function protomapper = getMapper(cur_type)
% For each type defined in qMRLab, there is a protocol mapper
% called <subffix>_BIDSmapper.json under src/common/BIDS_protomaps
qmrTypeList = dir(fullfile('./BIDS_protomaps', '*.json'));
tmp = struct2cell(qmrTypeList); % Cell matrix
qmrTypeList = tmp(1,:); % Cell array, 1st index is "name" field
% Check if the current type is defined within qMRLab
if ismember([cur_type '.json'],qmrTypeList)
protomapper = json2struct(['./BIDS_protomaps/' cur_type '.json']);
else
protomapper = [];
end
end
function extra = checkExtraEntities(BIDS,protomapper,sub_iter,cur_type)
anat = BIDS.subjects(sub_iter).anat;
for ii =1:length(anat)
if strcmp(anat(ii).type,cur_type)
idx = not(structfun(@isempty, anat(ii)));
fnames = fieldnames(anat(ii));
extra = setxor(fnames(idx),[protomapper.REQUIREDEntities,{'filename' 'ext' 'type' 'sub'}]);
end
end
end
function [Model,data] = qMRLabBIDSmapper(datas,metas,protomapper)
% ================== Instantiate qMRLab object
eval(['Model=' protomapper.qMRLabModel ';']);
% =================== DATA START
% ===============================================================
% ROUTE ACTION: MERGE
if strcmp(protomapper.routeAction,'merge')
% ---------------------------------------------- DATA START
tmp = load_nii_data(datas{1});
sz = size(tmp);
DATA = [];
if ndims(tmp)==2
if strcmp(protomapper.singleton,'1')
DATA = zeros(sz(1),sz(2),1,length(datas));
else
DATA = zeros(sz(1),sz(2),length(datas));
end
elseif ndims(tmp)==3
DATA = zeros(sz(1),sz(2),sz(3),length(datas));
else
error('Data is not a volume or a slice.');
end
for ii=1:length(datas)
if ndims(tmp)==2 && ~strcmp(protomapper.singleton,'1')
DATA(:,:,ii) = double(load_nii_data(datas{ii}));
else
DATA(:,:,:,ii) = double(load_nii_data(datas{ii}));
end
end
data = struct();
data.(protomapper.dataFieldName) = DATA;
clear('tmp','DATA');
% ---------------------------------------------- DATA END
if ~isstruct(metas)
str = cell2struct(metas,'tmp');
metas = [str.tmp];
end
params = setxor('foreach',fieldnames(protomapper.protMap));
for ii=1:length(params)
cur_param = cell2mat(params(ii));
if strcmp(protomapper.protMap.(cur_param).order,'col_first')
Model.Prot.(protomapper.protMap.(cur_param).qMRLabProt).Mat(:,ii) = ...
[metas(:).(cur_param)].*protomapper.protMap.(cur_param).scale;
else
Model.Prot.(protomapper.protMap.(cur_param).qMRLabProt).Mat(ii,:) = ...
[metas(:).(cur_param)].*protomapper.protMap.(cur_param).scale;
end
end
% ==================================================
elseif strcmp(protomapper.routeAction,'distribute')
% ===============================================================
% ROUTE ACTION: DISTRIBUTE
% ===============================================================
% TODO: For other models like mt_sat, we'll distribute data.
end
end
function renameMapsSaveJsons(BIDS,files,curSubName,fileDir,protomapper,xnames,varargin)
for ii=1:length(xnames)
f = dir(fullfile(fileDir,[xnames{ii} '.nii.gz']));
if ~isempty(f)
if nargin>6
newname = ['sub-' curSubName '_' varargin{1} '-' varargin{2} '_' protomapper.outputMap.(xnames{ii})];
else
newname = ['sub-' curSubName '_' protomapper.outputMap.(xnames{ii})];
end
movefile([fileDir filesep f.name],[fileDir filesep newname '.nii.gz']);
provenance = getProvenance(BIDS,files,protomapper);
savejson('',provenance,[fileDir filesep newname '.json']);
end
end
f = dir(fullfile(fileDir,'FitResults.mat'));
if ~isempty(f)
newname = newname(1:(max(strfind(newname,'_'))-1));
movefile([fileDir filesep f.name],[fileDir filesep newname '_FitResults.mat']);
end
end
function FitProvenance = getProvenance(BIDS,files,protomapper)
FitProvenance = struct();
FitProvenance.BasedOn = regexprep(files,BIDS.dir(1:max(strfind(BIDS.dir,filesep))),'','ignorecase');
FitProvenance.EstimationSoftwareName = 'qMRLab';
FitProvenance.EstimationSoftwareVer = qMRLabVer;
FitProvenance.EstimationReference = protomapper.estimationPaper;
FitProvenance.EstimationAlgorithm = protomapper.estimationAlgorithm;
if moxunit_util_platform_is_octave
FitProvenance.EstimationDate = strftime('%Y-%m-%d %H:%M:%S', localtime (time ()));
[FitProvenance.EstimationSoftwareEnv, FitProvenance.MaxSize, FitProvenance.Endian] = computer;
FitProvenance.EstimationSoftwareEnvDetails = GetOSDetails();
FitProvenance.EstimationSoftwareLang = ['Octave ' OCTAVE_VERSION()];
Fitprovenance.EstimationSoftwareLangDetails = pkg('list');
else
FitProvenance.EstimationDate = datetime(now,'ConvertFrom','datenum');
[FitProvenance.EstimationSoftwareEnv, FitProvenance.MaxSize, FitProvenance.Endian] = computer;
FitProvenance.EstimationSoftwareEnvDetails = GetOSDetails();
FitProvenance.EstimationSoftwareLang = ['Matlab ' version('-release')];
FitProvenance.EstimationSoftwareLangDetails = ver;
end
end
function details = GetOSDetails
type = computer;
if moxunit_util_platform_is_octave
if ~isempty(strfind(type,'apple')) % OSX Octave
[st,out] = unix('cat /etc/os-release');
if ~st
details = out;
else
details = [];
end
end
if ~isempty(strfind(type,'linux')) % GNU Linux Octave
[st,out] = unix('system_profiler SPSoftwareDataType');
if ~st
details = out;
else
details = [];
end
end
if ~isempty(strfind(type,'windows')) % GNU Linux Octave
[st,out] = system('winver');
if ~st
details = out;
else
details = [];
end
end
else % MATLAB
if strncmp(type,'MAC',3)
[st,out] = unix('system_profiler SPSoftwareDataType');
if ~st
details = rmUserInfoOSX(out);
else
details = [];
end
end
if strncmp(type,'GLNX',4)
[st,out] = unix('cat /etc/os-release');
if ~st
details = out;
else
details = [];
end
end
if ~isempty(strfind(type,'WIN'))
[st,out] = system('winver');
if ~st
details = out;
else
details = [];
end
end
end
end
function out = rmUserInfoOSX(ipt)
usridx = strfind(ipt,'User Name');
pcidx = strfind(ipt,'Computer Name');
nwlines = strfind(ipt,char(10));
if ~isempty(usridx)
ipt = hideUser(usridx,nwlines,ipt);
end
if ~isempty(pcidx)
ipt = hideUser(pcidx,nwlines,ipt);
end
out = ipt;
end
function out = hideUser(idx,nwlines,ipt)
tmp = nwlines - idx;
tmp = min(tmp(tmp>0));
interval = idx:idx+min(tmp)-1;
ipt(interval) = '*';
ipt(max(interval)+1) = char(10);
out = ipt;
end