forked from incf-nidash/nidmresults-fsl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsl_exporter.py
1850 lines (1520 loc) · 75 KB
/
fsl_exporter.py
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
"""
Export neuroimaging results created with feat in FSL following NIDM-Results
specification.
@author: Camille Maumet <c.m.j.maumet@warwick.ac.uk>
@copyright: University of Warwick 2013-2014
"""
from nidmresults.exporter import NIDMExporter
from nidmresults.objects.constants import *
from nidmresults.objects.modelfitting import *
from nidmresults.objects.contrast import *
from nidmresults.objects.inference import *
from nidmfsl.fsl_exporter.objects.fsl_objects import *
import re
import os
import sys
import glob
import json
import scipy.ndimage
import numpy as np
import subprocess
import warnings
import numpy.linalg as npla
from nibabel.affines import apply_affine
# If "nidmresults" code is available locally work on the source code (used
# only for development)
FSL_EXPORTER_DIR = os.path.dirname(os.path.realpath(__file__))
NIDM_FSL_DIR = os.path.dirname(FSL_EXPORTER_DIR)
NIDM_RESULTS_FSL_DIR = os.path.dirname(NIDM_FSL_DIR)
NIDM_RESULTS_SRC_DIR = os.path.join(
os.path.dirname(NIDM_RESULTS_FSL_DIR), "nidmresults")
if os.path.isdir(NIDM_RESULTS_SRC_DIR):
sys.path.append(NIDM_RESULTS_SRC_DIR)
class FSLtoNIDMExporter(NIDMExporter, object):
"""
Parse an FSL result directory to extract the pieces information to be
stored in NIDM-Results and generate a NIDM-Results export.
"""
def __init__(self, feat_dir, version="1.3.0-rc2", out_dirname=None,
zipped=True, groups=None):
# Absolute path to feat directory
feat_dir = os.path.abspath(feat_dir)
# Check if the FEAT dir exists (and append ".feat" if needed)
if not os.path.isdir(feat_dir):
if os.path.isdir(feat_dir + ".feat"):
feat_dir = feat_dir + ".feat"
else:
raise Exception("No such a directory: " + feat_dir)
if feat_dir.endswith("/"):
feat_dir = feat_dir[:-1]
# Create output name if it was not set
if not out_dirname:
out_dirname = os.path.basename(feat_dir)
out_dir = os.path.join(feat_dir, out_dirname)
# Ignore rc* in version number
version = version.split("-")[0]
try:
super(FSLtoNIDMExporter, self).__init__(version, out_dir, zipped)
# Check if feat_dir exists
print("Exporting NIDM results from "+feat_dir)
if not os.path.isdir(feat_dir):
raise Exception("Unknown directory: "+str(feat_dir))
self.feat_dir = feat_dir
self.design_file = os.path.join(self.feat_dir, 'design.fsf')
self.coord_space = None
self.t_contrast_names_by_num = dict()
self.f_contrast_names_by_num = dict()
self.groups = groups
self.without_group_versions = ["0.1.0", "0.2.0", "1.0.0", "1.1.0",
"1.2.0"]
# Path to FSL library (None if unavailable)
self.fsl_path = os.getenv('FSLDIR')
except Exception:
self.export_dir = out_dir
self.cleanup()
raise
def parse(self):
"""
Parse an FSL result directory to extract the pieces information to be
stored in NIDM-Results.
"""
try:
# Load design.fsf file
design_file_open = open(self.design_file, 'r')
self.design_txt = design_file_open.read()
fmri_level_re = r'.*set fmri\(level\) (?P<info>\d+).*'
fmri_level = int(self._search_in_fsf(fmri_level_re))
self.first_level = (fmri_level == 1)
self.analyses_num = dict()
if self.first_level:
# stat_dir = list([os.path.join(self.feat_dir, 'stats')])
self.analysis_dirs = list([self.feat_dir])
self.analyses_num[self.feat_dir] = ""
if self.groups is None:
self.num_subjects = 1
else:
raise Exception("Groups specified as input in"
"a first-level analysis: (groups="
",".join(str(self.groups))+")")
else:
if not self.groups:
# Number of subject per groups was introduced in 1.3.0
if self.version['num'] not in self.without_group_versions:
raise Exception("Group analysis with unspecified"
"groups.")
# If feat was called with the GUI then the analysis directory
# is in the nested cope folder.
self.analysis_dirs = glob.glob(
os.path.join(self.feat_dir, 'cope*.feat'))
if not self.analysis_dirs:
self.analysis_dirs = list([self.feat_dir])
self.analyses_num[self.feat_dir] = ""
else:
num_analyses = len(self.analysis_dirs)
if num_analyses > 1:
max_digits = len(str(len(self.analysis_dirs)))
for analysis in self.analysis_dirs:
s = re.compile('cope\d+.feat')
ana_num = s.search(analysis)
ana_num = ana_num.group()
ana_num = ana_num.replace("cope", "").replace(
".feat", "")
self.analyses_num[analysis] = \
("_{0:0>" + str(max_digits) + "}").format(
ana_num)
else:
# There is a single analysis, no need to add a prefix
self.analyses_num[self.analysis_dirs[0]] = ""
super(FSLtoNIDMExporter, self).parse()
except Exception:
self.cleanup()
raise
def _add_namespaces(self):
"""
Overload of parent _add_namespaces to add FSL namespace.
"""
super(FSLtoNIDMExporter, self)._add_namespaces()
self.doc.add_namespace(FSL)
def _find_software(self):
"""
Return an object of type Software describing the version of FSL used to
compute the current analysis.
"""
version_re = r'.*set fmri\(version\) (?P<info>\d+\.?\d+).*'
feat_version = self._search_in_fsf(version_re)
software = FSLNeuroimagingSoftware(feat_version=feat_version)
return software
def _get_exporter(self):
"""
Return an object of type NIDM-Results Exporter Software describing the
exporter used to compute the current analysis.
"""
exporter = FSLExporterSoftware()
return exporter
def _find_model_fitting(self):
"""
Parse FSL result directory to retreive model fitting information.
Return a list of objects of type ModelFitting.
"""
self.model_fittings = dict()
for analysis_dir in self.analysis_dirs:
design_matrix = self._get_design_matrix(analysis_dir)
data = self._get_data()
error_model = self._get_error_model()
rms_map = self._get_residual_mean_squares_map(analysis_dir)
param_estimates = self._get_param_estimate_maps(analysis_dir)
mask_map = self._get_mask_map(analysis_dir)
grand_mean_map = self._get_grand_mean(
mask_map.file.path, analysis_dir)
activity = self._get_model_parameters_estimations(error_model)
# Assuming MRI data
machine = ImagingInstrument("mri")
# Group or Person
if self.version['num'] not in ["1.0.0", "1.1.0", "1.2.0"]:
if self.first_level:
subjects = [Person()]
else:
subjects = list()
for group_name, numsub in self.groups:
subjects.append(Group(
num_subjects=int(numsub), group_name=group_name))
else:
subjects = None
model_fitting = ModelFitting(
activity, design_matrix, data,
error_model, param_estimates, rms_map, mask_map,
grand_mean_map, machine, subjects)
self.model_fittings[analysis_dir] = model_fitting
return self.model_fittings
def _find_contrasts(self):
"""
Parse FSL result directory to retreive information about contrasts.
Return a dictionary of (key, value) pairs where key is a tuple
containing the identifier of a ModelParametersEstimation object and a
tuple of identifiers of ParameterEstimateMap objects, and value is an
object of type Contrast.
"""
contrasts = dict()
for analysis_dir in self.analysis_dirs:
# Retreive the Model Parameters Estimations activity corresponding
# to current analysis directory.
mf_id = self.model_fittings[analysis_dir].activity.id
stat_dir = os.path.join(analysis_dir, 'stats')
# Degrees of freedom
dof_file = open(os.path.join(stat_dir, 'dof'), 'r')
dof = float(dof_file.read())
# We must get the T statistics first. We need to have recorded all
# T statistics in order to then record F statistics.
exc_sets_t = glob.glob(os.path.join(analysis_dir,
'thresh_zstat*.nii.gz'))
exc_sets_f = glob.glob(os.path.join(analysis_dir,
'thresh_zfstat*.nii.gz'))
# If we have F contrasts we need to record certain T contrast
# details.
if len(exc_sets_f) > 0:
numOfTCons = len(exc_sets_t)
tWeights = ['']*numOfTCons
tNames = ['']*numOfTCons
# This ordering is important. T statistics must be recorded first.
exc_sets = exc_sets_t + exc_sets_f
for filename in exc_sets:
con_num, stat_type, stat_num_idx = self._get_stat_num(
filename, analysis_dir, exc_sets)
if stat_type == 'T':
# Contrast name
name_re = r'.*set fmri\(conname_real\.' + str(con_num) +\
'\) "(?P<info>[^"]+)".*'
contrast_name = self._search_in_fsf(name_re)
self.t_contrast_names_by_num[con_num] = contrast_name
# Contrast weights
weights_re = r'.*set fmri\(con_real' + str(con_num) +\
'\.\d+\) (?P<info>-?\d+)'
weight_search = re.compile(weights_re)
contrast_weights = str(
re.findall(weight_search,
self.design_txt)).replace("'", '')
# If we have F contrasts we need to record some T contrast
# details.
if len(exc_sets_f) > 0:
tWeights[con_num-1] = [
float(i) for i in re.findall(
weight_search, self.design_txt)]
tNames[con_num-1] = contrast_name
# For parameter estimate maps.
pe_weights = contrast_weights
# Effect dof
effdof = float(1)
else:
# Record relations between T and F stats.
TtoF_re = r'.*set fmri\(ftest_real' + str(con_num) +\
'\.\d+\) (?P<info>-?\d+)'
TtoF_search = re.compile(TtoF_re)
TtoF_vec = re.findall(TtoF_search, self.design_txt)
TtoF_vec = [float(i) for i in TtoF_vec]
# Using the T contrast weights that have been recorded
# already, create the F contrast weight matrix and contrast
# name.
contrast_weights = []
contrast_name = ''
pe_weights = [0]*len(tWeights[0])
for i in range(numOfTCons):
if TtoF_vec[i] == 1:
contrast_weights.append(tWeights[i])
contrast_name += tNames[i].strip() + ' & '
# Record parameter estimates used.
weightsZero = [int(j != 0) for j in tWeights[i]]
pe_weights = [sum(i) for i in
zip(weightsZero, pe_weights)]
# Compute the effect degrees of freedom as the rank of the
# contrast weight matrix.
effdof = float(np.linalg.matrix_rank(
np.array(contrast_weights)))
# Convert contrast_weights to string representation.
contrast_weights = str(contrast_weights).replace("'", '')
# Remove last ' & ' from contrast name.
contrast_name = contrast_name[:-3]
# These will ve used for determining which parameters were
# used.
pe_weights = str(pe_weights).replace("'", '')
# Record the contrast name.
self.f_contrast_names_by_num[con_num] = contrast_name
# Contrast estimation activity
estimation = ContrastEstimation(con_num, contrast_name)
# Contrast Weights object
weights = ContrastWeights(stat_num_idx, contrast_name,
contrast_weights, stat_type)
# Find which parameter estimates were used to compute the
# contrast
pe_ids = list()
pe_index = 1
pe_weights = pe_weights.replace(' ', '')
pe_weights = pe_weights.replace('[', '')
pe_weights = pe_weights.replace(']', '')
pe_weights = pe_weights.split(',')
# Whenever a non-zero element is found in pe_weights, the
# parameter estimate map identified by the corresponding
# index is in use
for beta_index in pe_weights:
if abs(float(beta_index)) != 0:
for model_fitting in list(
self.model_fittings.values()):
for pe in model_fitting.param_estimates:
if int(pe.num) == pe_index:
pe_ids.append(pe.id)
pe_index += 1
# Convert to immutable tuple to be used as key
pe_ids = tuple(pe_ids)
# Statistic Map
stat_file = os.path.join(
stat_dir,
stat_type.lower() + 'stat' + str(con_num) + '.nii.gz')
stat_map = StatisticMap(
location=stat_file, stat_type=stat_type,
contrast_name=contrast_name, dof=dof,
coord_space=self.coord_space, effdof=effdof,
contrast_num=stat_num_idx)
# Z-Statistic Map
if stat_type == "F":
z_stat_file = os.path.join(
stat_dir,
'zfstat' + str(con_num) + '.nii.gz')
elif stat_type == "T":
z_stat_file = os.path.join(
stat_dir,
'zstat' + str(con_num) + '.nii.gz')
# Create the Z statistic map file.
z_stat_map = StatisticMap(
location=z_stat_file, stat_type='Z',
contrast_name=contrast_name, dof=dof,
coord_space=self.coord_space,
contrast_num=stat_num_idx,
effdof=effdof)
if stat_type is "T":
# Contrast Map
con_file = os.path.join(stat_dir,
'cope' + str(con_num) + '.nii.gz')
contrast_map = ContrastMap(con_file, stat_num_idx,
contrast_name, self.coord_space)
# Contrast Variance and Standard Error Maps
varcontrast_file = os.path.join(
stat_dir, 'varcope' + str(con_num) + '.nii.gz')
is_variance = True
std_err_map = ContrastStdErrMap(
stat_num_idx,
varcontrast_file, is_variance, self.coord_space,
self.coord_space, export_dir=self.export_dir)
std_err_map_or_mean_sq_map = std_err_map
elif stat_type is "F":
contrast_map = None
sigma_sq_file = os.path.join(
stat_dir, 'sigmasquareds.nii.gz')
expl_mean_sq_map = ContrastExplainedMeanSquareMap(
stat_file, sigma_sq_file, stat_num_idx,
self.coord_space)
std_err_map_or_mean_sq_map = expl_mean_sq_map
else:
raise Exception("Unknown statistic type: "+stat_type)
con = Contrast(
stat_num_idx, contrast_name, weights, estimation,
contrast_map, std_err_map_or_mean_sq_map, stat_map,
z_stat_map)
contrasts.setdefault((mf_id, pe_ids), list()).append(con)
return contrasts
def _get_stat_num(self, filename, analysis_dir, exc_sets):
ana_num = self.analyses_num[analysis_dir]
s = re.compile('zf?stat\d+')
zstatnum = s.search(filename)
zstatnum = zstatnum.group()
if zstatnum.startswith("zstat"):
stat_type = "T"
con_num = zstatnum.replace('zstat', '')
elif zstatnum.startswith("zfstat"):
stat_type = "F"
con_num = zstatnum.replace('zfstat', '')
con_num = int(con_num)
# If more than one excursion set is reported, we need to
# use an index in the file names of the file exported in
# nidm
if len(exc_sets) > 1 or len(self.analysis_dirs) > 1:
stat_num_idx = ana_num + '_' + \
stat_type.upper() + "{0:0>3}".format(con_num)
else:
stat_num_idx = ""
return (con_num, stat_type, stat_num_idx)
def _find_inferences(self):
"""
Parse FSL result directory to retreive information about inference
along with peaks and clusters. Return a dictionary of (key, value)
pairs where key is the identifier of a ContrastEstimation object and
value is an object of type Inference.
"""
inferences = dict()
# Any contrast masking?
m = re.search(r"set fmri\(conmask1_1\) (?P<con_maskg>[0|1])",
self.design_txt)
assert m is not None
contrast_masking = bool(int(m.group("con_maskg")))
for analysis_dir in self.analysis_dirs:
exc_sets = glob.glob(os.path.join(analysis_dir,
'thresh_z*.nii.gz'))
# Find excursion sets (in a given feat directory we have one
# excursion set per contrast)
for filename in exc_sets:
stat_num, stat_type, stat_num_idx = self._get_stat_num(
filename, analysis_dir, exc_sets)
# Find corresponding contrast estimation activity
con_id = None
for contrasts in list(self.contrasts.values()):
for contrast in contrasts:
if contrast.contrast_num == stat_num_idx:
con_id = contrast.estimation.id
assert con_id is not None
if stat_type == 'T':
# Inference activity
inference_act = InferenceActivity(
contrast_name=self.t_contrast_names_by_num[stat_num])
# Excursion set png image
visualisation = os.path.join(
analysis_dir,
'rendered_thresh_zstat' + str(stat_num) + '.png')
else:
# Inference activity
inference_act = InferenceActivity(
contrast_name=self.f_contrast_names_by_num[stat_num])
# Excursion set png image
visualisation = os.path.join(
analysis_dir,
'rendered_thresh_zfstat' + str(stat_num) + '.png')
# Excursion set png image
zFileImg = filename
# Cluster Labels Map
cluster_labels_map = os.path.join(
analysis_dir, 'tmp_clustmap' + stat_num_idx + '.nii.gz')
excset_img = nib.load(filename)
# Get cluster connectivity
# There is not table display listing peaks and clusters for
# voxelwise correction
feat_post_log_file = os.path.join(
analysis_dir, 'logs', 'feat4_post')
if os.path.isfile(feat_post_log_file):
with open(feat_post_log_file, 'r') as log:
feat_post_log = log.read()
connectivity = self._get_connectivity(feat_post_log)
else:
warnings.warn(
"Log file feat4_post not found, " +
"connectivity information will not be reported")
feat_post_log = None
connectivity = 26 # FSL's default
if connectivity == 6:
structure = np.array([[[0, 0, 0],
[0, 1, 0],
[0, 0, 0]],
[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]],
[[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]], dtype='uint8')
elif connectivity == 18:
structure = np.array([[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]]], dtype='uint8')
if connectivity == 26:
structure = np.array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]], dtype='uint8')
else:
raise Exception('Unknown connectivity: ' +
str(connectivity))
# Compute connected clusters from excursion set
labels, num_labels = scipy.ndimage.label(excset_img.get_data(),
structure)
# Update labels to match FSL's table
# If clusters are available in voxel space
if stat_type == 'T':
cluster_vox_file = glob.glob(
os.path.join(analysis_dir,
'cluster_zstat' + str(stat_num) + '.txt'))
else:
cluster_vox_file = glob.glob(
os.path.join(
analysis_dir, 'cluster_zfstat' + str(stat_num) +
'.txt'))
if not cluster_vox_file:
cluster_vox_tab = None
elif len(cluster_vox_file) > 1:
print(cluster_vox_file)
warnings.warn("Found more than 1 cluster vox file")
else:
with warnings.catch_warnings():
# Ignore "Empty input file" for no significant cluster
warnings.simplefilter("ignore")
cluster_vox_tab = np.loadtxt(cluster_vox_file[0],
skiprows=1)
# If cluster vox table was not found look for coordinates in
# world space and convert to voxel space
if cluster_vox_tab is None:
cluster_file = glob.glob(
os.path.join(analysis_dir,
'cluster*' + str(stat_num) + '*_std.txt'))
if not cluster_file:
cluster_mm_tab = None
elif len(cluster_file) > 1:
print(cluster_file)
warnings.warn("Found more than 1 cluster file")
else:
with warnings.catch_warnings():
# Ignore "Empty input file" for no significant
# cluster
warnings.simplefilter("ignore")
cluster_mm_tab = np.loadtxt(cluster_file[0],
skiprows=1)
if cluster_mm_tab is not None:
# Work out which are z-max xyz columns.
xcol = self._get_column_indices(
cluster_file[0], 'Z-MAX X')[0]
# Transform cluster positions in mm into voxels
# Read in coordinates of clusters in mm space
cluster_mm = cluster_mm_tab[:, xcol:(xcol+3)]
# Read in excursion set image header to obtain
# world to voxel mapping
excset_img = nib.load(filename)
worldToVox = npla.inv(excset_img.affine)
# Transform cluster coordinates to voxel space
cluster_vox = apply_affine(worldToVox, cluster_mm)
# Record coordinates
cluster_vox_tab = cluster_mm_tab
cluster_vox_tab[:, xcol:(xcol+3)] = cluster_vox
if cluster_vox_tab is not None:
# If we have a voxel table it was either derived from the
# mm table and must have the same column layout...
if not cluster_vox_file:
cluster_file = glob.glob(
os.path.join(analysis_dir,
'cluster*' + str(stat_num) +
'*_std.txt'))
# Work out which are z-max xyz columns and cluster
# labels id.
xcol = self._get_column_indices(
cluster_file[0], 'Z-MAX X')[0]
clidcol = self._get_column_indices(
cluster_file[0], 'Cluster Index')[0]
# Or we had a cluster_vox_file already!
else:
# Work out which are z-max xyz columns and cluster
# labels id.
xcol = self._get_column_indices(
cluster_vox_file[0], 'Z-MAX X')[0]
clidcol = self._get_column_indices(
cluster_vox_file[0], 'Cluster Index')[0]
# Relabel using a different set of labels to avoid conflict
# when doing the replacment with FSL labels
labels = labels*max(num_labels, 10000)
# Replace existing labels by FSL labels
for i in range(0, np.shape(cluster_vox_tab)[0]):
clid = cluster_vox_tab[i, clidcol]
x, y, z = cluster_vox_tab[i, xcol:(xcol+3)]
labels[labels == labels[int(x), int(y), int(z)]] = clid
clusterlabels_img = nib.Nifti1Image(
labels,
excset_img.affine)
nib.save(clusterlabels_img, cluster_labels_map)
temporary = True
clust_map = ClusterLabelsMap(
cluster_labels_map, self.coord_space,
suffix=stat_num_idx,
temporary=temporary)
# FIXME: When doing contrast masking is the excursion set
# stored in thresh_zstat the one after or before contrast
# masking?
# If before: is there a way to get the excursion set after
# contrast masking?
# If after: how can we get the contrast masks? cf. report:
# "After all thresholding, zstat1 was masked with
# thresh_zstat2.
# --> fsl_contrast_mask
if stat_type == 'T':
visu_filename = 'ExcursionSet' + stat_num_idx + '.png'
else:
visu_filename = 'ExcursionSet' + stat_num_idx + '.png'
visualisation = Image(visualisation, visu_filename)
exc_set = ExcursionSet(
zFileImg, self.coord_space, visualisation,
suffix=stat_num_idx, clust_map=clust_map)
# Height Threshold
prob_re = r'.*set fmri\(prob_thresh\) (?P<info>\d+\.?\d+).*'
z_re = r'.*set fmri\(z_thresh\) (?P<info>\d+\.?\d+).*'
type_re = r'.*set fmri\(thresh\) (?P<info>\d+).*'
prob_thresh = float(self._search_in_fsf(prob_re))
z_thresh = float(self._search_in_fsf(z_re))
thresh_type = int(self._search_in_fsf(type_re))
# FIXME: deal with 0 = no thresh?
voxel_uncorr = (thresh_type == 1)
voxel_corr = (thresh_type == 2)
cluster_thresh = (thresh_type == 3)
stat_threshold = None
extent_p_corr = None
p_corr_threshold = None
p_uncorr_threshold = None
if voxel_uncorr:
p_uncorr_threshold = prob_thresh
elif voxel_corr:
p_corr_threshold = prob_thresh
else:
stat_threshold = z_thresh
extent_p_corr = prob_thresh
height_thresh = HeightThreshold(
stat_threshold,
p_corr_threshold, p_uncorr_threshold)
# Extent Threshold
extent_thresh = ExtentThreshold(p_corr=extent_p_corr)
# Clusters (and associated peaks)
clusters = self._get_clusters_peaks(
analysis_dir,
stat_num, stat_type, len(exc_sets))
if clusters is not None:
# Peak and Cluster are only reported for cluster-wise
# thresholds
peak_criteria = PeakCriteria(
stat_num,
self._get_peak_dist(feat_post_log),
self._get_num_peaks(feat_post_log))
clus_criteria = ClusterCriteria(
stat_num,
connectivity)
else:
# Missing peaks and clusters (this happens for voxel-wise
# threshold with FSL < x.x)
clusters = None
peak_criteria = None
clus_criteria = None
# Display mask
contrast_masks = list()
display_mask = list()
if contrast_masking:
# Find all contrast masking definitions for current stat
con_mask_defs = re.findall(
r"set fmri\(conmask" + str(stat_num) + "_\d+\) 1",
self.design_txt)
for con_mask_def in con_mask_defs:
m = re.search(
r"set fmri\(conmask" + str(stat_num) +
"_(?P<c2>\d+)\) 1",
con_mask_def)
assert m is not None
c2 = int(m.group("c2"))
if not (stat_num == 1 and c2 == 1):
contrast_masks.append(c2)
conmask_file = os.path.join(
analysis_dir,
'thresh_zstat' + str(c2) + '.nii.gz')
display_mask.append(DisplayMaskMap(
stat_num,
conmask_file, c2, self.coord_space))
# Search space
search_space = self._get_search_space(analysis_dir)
inference = Inference(
inference_act, height_thresh,
extent_thresh, peak_criteria, clus_criteria,
display_mask, exc_set, clusters, search_space,
self.software.id)
inferences.setdefault(con_id, list()).append(inference)
return inferences
def _get_design_matrix(self, analysis_dir):
"""
Parse FSL result directory to retreive information about the design
matrix. Return an object of type DesignMatrix.
"""
design_mat_file = os.path.join(analysis_dir, 'design.mat')
design_mat_fid = open(design_mat_file, 'r')
design_mat_values = np.loadtxt(design_mat_fid, skiprows=5, ndmin=2)
design_mat_image = os.path.join(analysis_dir, 'design.png')
# Regressor names (not taking into account HRF model)
regnames_re = r'.*set fmri\(evtitle\d+\).*'
ev_names = re.findall(regnames_re, self.design_txt)
orig_ev = dict()
for ev_name in ev_names:
regname_re = r'.*set fmri\(evtitle(?P<num>\d+)\)\s*"(?P<name>.*)"'
info_search = re.compile(regname_re)
info_found = info_search.search(ev_name)
num = info_found.group('num')
name = info_found.group('name')
orig_ev[int(num)] = name
# For first-level fMRI only
if self.first_level:
# Design-type: event, mixed or block
# Deal only with the "custom" option (latest NIDM-Results version
# do not include design type)
onsets_re = r'.*set fmri\(custom(?P<num>\d+)\)\s*"(?P<file>.*)".*'
r = re.compile(onsets_re)
onsets = [m.groupdict() for m in r.finditer(self.design_txt)]
max_duration = 0
min_duration = 36000
missing_onset_file = list()
for onset in onsets:
if os.path.isfile(onset['file']):
aa = np.loadtxt(onset['file'], ndmin=2)
max_duration = max(
max_duration, np.amax(aa[:, 2], axis=None))
min_duration = min(
min_duration, np.amin(aa[:, 2], axis=None))
else:
missing_onset_file.append(onset['file'])
max_duration = None
if max_duration is not None:
if max_duration <= 1:
design_type = NIDM_EVENT_RELATED_DESIGN
elif min_duration > 1:
design_type = NIDM_BLOCK_BASED_DESIGN
else:
design_type = NIDM_MIXED_DESIGN
else:
design_type = None
# HRF model
prev_hrf = None
for ev_num, ev_name in list(orig_ev.items()):
m = re.search(
r"set fmri\(convolve" + str(ev_num) + "\) (?P<hrf>\d)",
self.design_txt)
assert m is not None
hrf = int(m.group("hrf"))
if prev_hrf is not None:
# Sanity check: all regressors should have the same hrf
if (prev_hrf != hrf):
raise Exception('Inconsistency: all regressors ' +
'must have the same type of HRF (' +
str(prev_hrf) + ' and ' + str(hrf) +
' found)')
prev_hrf = hrf
if hrf == 1: # 1: Gaussian
hrf_model = [NIDM_GAUSSIAN_HRF]
elif hrf == 2: # 2 : Gamma
if self.version['num'] in ["1.0.0", "1.1.0", "1.2.0"]:
hrf_model = [NIDM_GAMMA_HRF]
else:
hrf_model = [FSL_FSLS_GAMMA_HRF]
elif hrf == 3: # 3 : Double-Gamma HRF
hrf_model = [FSL_FSLS_GAMMA_DIFFERENCE_HRF]
elif hrf == 4: # 4 : Gamma basis functions
hrf_model = [NIDM_GAMMA_HRB]
elif hrf == 5: # 5 : Sine basis functions
hrf_model = [NIDM_SINE_BASIS_SET]
elif hrf == 6: # 6 : FIR basis functions
hrf_model = [NIDM_FINITE_IMPULSE_RESPONSE_HRB]
# Drift model
m = re.search(
r"set fmri\(paradigm_hp\) (?P<cut_off>\d+)", self.design_txt)
assert m is not None
cut_off = float(m.group("cut_off"))
drift_model = DriftModel(
FSL_GAUSSIAN_RUNNING_LINE_DRIFT_MODEL, cut_off)
else:
hrf = None
design_type = None
hrf_model = None
drift_model = None
real_ev = list()
for ev_num, ev_name in list(orig_ev.items()):
real_ev.append(ev_name)
# basis functions
if hrf and hrf > 3:
if hrf == 4:
basis = 'GammaBasis'
elif hrf == 5:
basis = 'SineBasis'
elif hrf == 6:
basis = 'FIRBasis'
# Number of basis functions
fir_basis_num_re = \
r'.*set fmri\(basisfnum'+str(ev_num)+'\) (?P<info>[\d]+).*'
fir_basis_num = int(self._search_in_fsf(fir_basis_num_re))
for i in range(1, fir_basis_num):
real_ev.append(ev_name+'*'+basis+'_'+str(i))
# Add one regressor name if there is an extra column for a temporal
# derivative
tempo_deriv_re = \
r'.*set fmri\(deriv_yn'+str(ev_num)+'\) (?P<info>[\d]+).*'
tempo_deriv = bool(int(self._search_in_fsf(tempo_deriv_re)))
if tempo_deriv:
real_ev.append(ev_name+'*temporal_derivative')
# Add regressor names for motion regressors
m = re.search(
r"set fmri\(motionevs\) (?P<motionreg>\d+)", self.design_txt)
assert m is not None
motion_reg = int(m.group("motionreg"))
# 6 motion regressors added
if motion_reg == 1:
real_ev.extend(('mot_1', 'mot_2', 'mot_3',
'mot_4', 'mot_5', 'mot_6'))
elif motion_reg == 2:
real_ev.extend(('mot_01', 'mot_02', 'mot_03', 'mot_04', 'mot_05',
'mot_06', 'mot_07', 'mot_08', 'mot_09', 'mot_10',
'mot_11', 'mot_12', 'mot_13', 'mot_14', 'mot_15',
'mot_16', 'mot_17', 'mot_18', 'mot_19', 'mot_20',
'mot_21', 'mot_22', 'mot_23', 'mot_24'))
elif not motion_reg == 0:
raise Exception('Unknow value for motion regressors: '
+ str(motion_reg))
# Sanity check: one regressor name per column of the design matrix
if (len(real_ev) != design_mat_values.shape[1]):
print(design_mat_values.shape)
print(real_ev)
raise Exception('Inconsistency: ' +
'number of columns in the design matrix (' +
str(design_mat_values.shape[1]) + ') ' +
'is not equal to number of regressor names (' +
str(len(real_ev)) + ')')
design_matrix = DesignMatrix(design_mat_values, design_mat_image,
real_ev, design_type, hrf_model,
drift_model,
self.analyses_num[analysis_dir])
return design_matrix
def _get_data(self):
"""
Parse FSL result directory to retreive information about the data.
Return an object of type Data.
"""
# Assuming functional data
mri_protocol = "fmri"
grand_mean_scaling = True