forked from nipy/nipype
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
2558 lines (2302 loc) · 88.3 KB
/
model.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
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools. This
was written to work with FSL version 4.1.4.
"""
import os
from glob import glob
from shutil import rmtree
from string import Template
import numpy as np
from looseversion import LooseVersion
from nibabel import load
from ...utils.filemanip import simplify_list, ensure_list
from ...utils.misc import human_order_sorted
from ...external.due import BibTeX
from ..base import (
File,
traits,
Tuple,
isdefined,
TraitedSpec,
BaseInterface,
Directory,
InputMultiPath,
OutputMultiPath,
BaseInterfaceInputSpec,
)
from .base import FSLCommand, FSLCommandInputSpec, Info
class Level1DesignInputSpec(BaseInterfaceInputSpec):
interscan_interval = traits.Float(
mandatory=True, desc="Interscan interval (in secs)"
)
session_info = traits.Any(
mandatory=True,
desc=("Session specific information generated by ``modelgen.SpecifyModel``"),
)
bases = traits.Either(
traits.Dict(
traits.Enum("dgamma"), traits.Dict(traits.Enum("derivs"), traits.Bool)
),
traits.Dict(
traits.Enum("gamma"),
traits.Dict(traits.Enum("derivs", "gammasigma", "gammadelay")),
),
traits.Dict(
traits.Enum("custom"), traits.Dict(traits.Enum("bfcustompath"), traits.Str)
),
traits.Dict(traits.Enum("none"), traits.Dict()),
traits.Dict(traits.Enum("none"), traits.Enum(None)),
mandatory=True,
desc=("name of basis function and options e.g., {'dgamma': {'derivs': True}}"),
)
orthogonalization = traits.Dict(
traits.Int,
traits.Dict(traits.Int, traits.Either(traits.Bool, traits.Int)),
desc=(
"which regressors to make orthogonal e.g., "
"{1: {0:0,1:0,2:0}, 2: {0:1,1:1,2:0}} to make the second "
"regressor in a 2-regressor model orthogonal to the first."
),
usedefault=True,
)
model_serial_correlations = traits.Bool(
desc="Option to model serial correlations using an \
autoregressive estimator (order 1). Setting this option is only \
useful in the context of the fsf file. If you set this to False, you need to \
repeat this option for FILMGLS by setting autocorr_noestimate to True",
mandatory=True,
)
contrasts = traits.List(
traits.Either(
Tuple(
traits.Str,
traits.Enum("T"),
traits.List(traits.Str),
traits.List(traits.Float),
),
Tuple(
traits.Str,
traits.Enum("T"),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(traits.Float),
),
Tuple(
traits.Str,
traits.Enum("F"),
traits.List(
traits.Either(
Tuple(
traits.Str,
traits.Enum("T"),
traits.List(traits.Str),
traits.List(traits.Float),
),
Tuple(
traits.Str,
traits.Enum("T"),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(traits.Float),
),
)
),
),
),
desc="List of contrasts with each contrast being a list of the form - \
[('name', 'stat', [condition list], [weight list], [session list])]. if \
session list is None or not provided, all sessions are used. For F \
contrasts, the condition list should contain previously defined \
T-contrasts.",
)
class Level1DesignOutputSpec(TraitedSpec):
fsf_files = OutputMultiPath(File(exists=True), desc="FSL feat specification files")
ev_files = OutputMultiPath(
traits.List(File(exists=True)), desc="condition information files"
)
class Level1Design(BaseInterface):
"""Generate FEAT specific files
Examples
--------
>>> level1design = Level1Design()
>>> level1design.inputs.interscan_interval = 2.5
>>> level1design.inputs.bases = {'dgamma':{'derivs': False}}
>>> level1design.inputs.session_info = 'session_info.npz'
>>> level1design.run() # doctest: +SKIP
"""
input_spec = Level1DesignInputSpec
output_spec = Level1DesignOutputSpec
def _create_ev_file(self, evfname, evinfo):
with open(evfname, "w") as f:
for i in evinfo:
if len(i) == 3:
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
else:
f.write("%f\n" % i[0])
def _create_ev_files(
self,
cwd,
runinfo,
runidx,
ev_parameters,
orthogonalization,
contrasts,
do_tempfilter,
basis_key,
):
"""Creates EV files from condition and regressor information.
Parameters:
-----------
runinfo : dict
Generated by `SpecifyModel` and contains information
about events and other regressors.
runidx : int
Index to run number
ev_parameters : dict
A dictionary containing the model parameters for the
given design type.
orthogonalization : dict
A dictionary of dictionaries specifying orthogonal EVs.
contrasts : list of lists
Information on contrasts to be evaluated
"""
conds = {}
evname = []
if basis_key == "dgamma":
basis_key = "hrf"
elif basis_key == "gamma":
try:
_ = ev_parameters["gammasigma"]
except KeyError:
ev_parameters["gammasigma"] = 3
try:
_ = ev_parameters["gammadelay"]
except KeyError:
ev_parameters["gammadelay"] = 6
ev_template = load_template("feat_ev_" + basis_key + ".tcl")
ev_none = load_template("feat_ev_none.tcl")
ev_ortho = load_template("feat_ev_ortho.tcl")
ev_txt = ""
# generate sections for conditions and other nuisance
# regressors
num_evs = [0, 0]
for field in ["cond", "regress"]:
for i, cond in enumerate(runinfo[field]):
name = cond["name"]
evname.append(name)
evfname = os.path.join(
cwd, "ev_%s_%d_%d.txt" % (name, runidx, len(evname))
)
evinfo = []
num_evs[0] += 1
num_evs[1] += 1
if field == "cond":
for j, onset in enumerate(cond["onset"]):
try:
amplitudes = cond["amplitudes"]
if len(amplitudes) > 1:
amp = amplitudes[j]
else:
amp = amplitudes[0]
except KeyError:
amp = 1
if len(cond["duration"]) > 1:
evinfo.insert(j, [onset, cond["duration"][j], amp])
else:
evinfo.insert(j, [onset, cond["duration"][0], amp])
ev_parameters["cond_file"] = evfname
ev_parameters["ev_num"] = num_evs[0]
ev_parameters["ev_name"] = name
ev_parameters["tempfilt_yn"] = do_tempfilter
if "basisorth" not in ev_parameters:
ev_parameters["basisorth"] = 1
if "basisfnum" not in ev_parameters:
ev_parameters["basisfnum"] = 1
try:
ev_parameters["fsldir"] = os.environ["FSLDIR"]
except KeyError:
if basis_key == "flobs":
raise Exception("FSL environment variables not set")
else:
ev_parameters["fsldir"] = "/usr/share/fsl"
ev_parameters["temporalderiv"] = int(
bool(ev_parameters.get("derivs", False))
)
if ev_parameters["temporalderiv"]:
evname.append(name + "TD")
num_evs[1] += 1
ev_txt += ev_template.substitute(ev_parameters)
elif field == "regress":
evinfo = [[j] for j in cond["val"]]
ev_txt += ev_none.substitute(
ev_num=num_evs[0],
ev_name=name,
tempfilt_yn=do_tempfilter,
cond_file=evfname,
)
ev_txt += "\n"
conds[name] = evfname
self._create_ev_file(evfname, evinfo)
# add ev orthogonalization
for i in range(1, num_evs[0] + 1):
initial = ev_ortho.substitute(c0=i, c1=0, orthogonal=1)
for j in range(num_evs[0] + 1):
try:
orthogonal = int(orthogonalization[i][j])
except (KeyError, TypeError, ValueError, IndexError):
orthogonal = 0
if orthogonal == 1 and initial not in ev_txt:
ev_txt += initial + "\n"
ev_txt += ev_ortho.substitute(c0=i, c1=j, orthogonal=orthogonal)
ev_txt += "\n"
# add contrast info to fsf file
if isdefined(contrasts):
contrast_header = load_template("feat_contrast_header.tcl")
contrast_prolog = load_template("feat_contrast_prolog.tcl")
contrast_element = load_template("feat_contrast_element.tcl")
contrast_ftest_element = load_template("feat_contrast_ftest_element.tcl")
contrastmask_header = load_template("feat_contrastmask_header.tcl")
contrastmask_footer = load_template("feat_contrastmask_footer.tcl")
contrastmask_element = load_template("feat_contrastmask_element.tcl")
# add t/f contrast info
ev_txt += contrast_header.substitute()
con_names = []
for j, con in enumerate(contrasts):
con_names.append(con[0])
con_map = {}
ftest_idx = []
ttest_idx = []
for j, con in enumerate(contrasts):
if con[1] == "F":
ftest_idx.append(j)
for c in con[2]:
if c[0] not in list(con_map.keys()):
con_map[c[0]] = []
con_map[c[0]].append(j)
else:
ttest_idx.append(j)
for ctype in ["real", "orig"]:
for j, con in enumerate(contrasts):
if con[1] == "F":
continue
tidx = ttest_idx.index(j) + 1
ev_txt += contrast_prolog.substitute(
cnum=tidx, ctype=ctype, cname=con[0]
)
count = 0
for c in range(1, len(evname) + 1):
if evname[c - 1].endswith("TD") and ctype == "orig":
continue
count = count + 1
if evname[c - 1] in con[2]:
val = con[3][con[2].index(evname[c - 1])]
else:
val = 0.0
ev_txt += contrast_element.substitute(
cnum=tidx, element=count, ctype=ctype, val=val
)
ev_txt += "\n"
for fconidx in ftest_idx:
fval = 0
if con[0] in con_map and fconidx in con_map[con[0]]:
fval = 1
ev_txt += contrast_ftest_element.substitute(
cnum=ftest_idx.index(fconidx) + 1,
element=tidx,
ctype=ctype,
val=fval,
)
ev_txt += "\n"
# add contrast mask info
ev_txt += contrastmask_header.substitute()
for j, _ in enumerate(contrasts):
for k, _ in enumerate(contrasts):
if j != k:
ev_txt += contrastmask_element.substitute(c1=j + 1, c2=k + 1)
ev_txt += contrastmask_footer.substitute()
return num_evs, ev_txt
def _format_session_info(self, session_info):
if isinstance(session_info, dict):
session_info = [session_info]
return session_info
def _get_func_files(self, session_info):
"""Returns functional files in the order of runs"""
func_files = []
for i, info in enumerate(session_info):
func_files.insert(i, info["scans"])
return func_files
def _run_interface(self, runtime):
cwd = os.getcwd()
fsf_header = load_template("feat_header_l1.tcl")
fsf_postscript = load_template("feat_nongui.tcl")
prewhiten = 0
if isdefined(self.inputs.model_serial_correlations):
prewhiten = int(self.inputs.model_serial_correlations)
basis_key = list(self.inputs.bases.keys())[0]
ev_parameters = dict(self.inputs.bases[basis_key])
session_info = self._format_session_info(self.inputs.session_info)
func_files = self._get_func_files(session_info)
n_tcon = 0
n_fcon = 0
if isdefined(self.inputs.contrasts):
for i, c in enumerate(self.inputs.contrasts):
if c[1] == "T":
n_tcon += 1
elif c[1] == "F":
n_fcon += 1
for i, info in enumerate(session_info):
do_tempfilter = 1
if info["hpf"] == np.inf:
do_tempfilter = 0
num_evs, cond_txt = self._create_ev_files(
cwd,
info,
i,
ev_parameters,
self.inputs.orthogonalization,
self.inputs.contrasts,
do_tempfilter,
basis_key,
)
nim = load(func_files[i])
(_, _, _, timepoints) = nim.shape
fsf_txt = fsf_header.substitute(
run_num=i,
interscan_interval=self.inputs.interscan_interval,
num_vols=timepoints,
prewhiten=prewhiten,
num_evs=num_evs[0],
num_evs_real=num_evs[1],
num_tcon=n_tcon,
num_fcon=n_fcon,
high_pass_filter_cutoff=info["hpf"],
temphp_yn=do_tempfilter,
func_file=func_files[i],
)
fsf_txt += cond_txt
fsf_txt += fsf_postscript.substitute(overwrite=1)
with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f:
f.write(fsf_txt)
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
cwd = os.getcwd()
outputs["fsf_files"] = []
outputs["ev_files"] = []
basis_key = list(self.inputs.bases.keys())[0]
ev_parameters = dict(self.inputs.bases[basis_key])
for runno, runinfo in enumerate(
self._format_session_info(self.inputs.session_info)
):
outputs["fsf_files"].append(os.path.join(cwd, "run%d.fsf" % runno))
outputs["ev_files"].insert(runno, [])
evname = []
for field in ["cond", "regress"]:
for i, cond in enumerate(runinfo[field]):
name = cond["name"]
evname.append(name)
evfname = os.path.join(
cwd, "ev_%s_%d_%d.txt" % (name, runno, len(evname))
)
if field == "cond":
ev_parameters["temporalderiv"] = int(
bool(ev_parameters.get("derivs", False))
)
if ev_parameters["temporalderiv"]:
evname.append(name + "TD")
outputs["ev_files"][runno].append(os.path.join(cwd, evfname))
return outputs
class FEATInputSpec(FSLCommandInputSpec):
fsf_file = File(
exists=True,
mandatory=True,
argstr="%s",
position=0,
desc="File specifying the feat design spec file",
)
class FEATOutputSpec(TraitedSpec):
feat_dir = Directory(exists=True)
class FEAT(FSLCommand):
"""Uses FSL feat to calculate first level stats"""
_cmd = "feat"
input_spec = FEATInputSpec
output_spec = FEATOutputSpec
def _list_outputs(self):
outputs = self._outputs().get()
is_ica = False
outputs["feat_dir"] = None
with open(self.inputs.fsf_file) as fp:
text = fp.read()
if "set fmri(inmelodic) 1" in text:
is_ica = True
for line in text.split("\n"):
if line.find("set fmri(outputdir)") > -1:
try:
outputdir_spec = line.split('"')[-2]
if os.path.exists(outputdir_spec):
outputs["feat_dir"] = outputdir_spec
except:
pass
if not outputs["feat_dir"]:
if is_ica:
outputs["feat_dir"] = glob(os.path.join(os.getcwd(), "*ica"))[0]
else:
outputs["feat_dir"] = glob(os.path.join(os.getcwd(), "*feat"))[0]
return outputs
class FEATModelInputSpec(FSLCommandInputSpec):
fsf_file = File(
exists=True,
mandatory=True,
argstr="%s",
position=0,
desc="File specifying the feat design spec file",
copyfile=False,
)
ev_files = traits.List(
File(exists=True),
mandatory=True,
argstr="%s",
desc="Event spec files generated by level1design",
position=1,
copyfile=False,
)
class FEATModelOutpuSpec(TraitedSpec):
design_file = File(exists=True, desc="Mat file containing ascii matrix for design")
design_image = File(exists=True, desc="Graphical representation of design matrix")
design_cov = File(exists=True, desc="Graphical representation of design covariance")
con_file = File(exists=True, desc="Contrast file containing contrast vectors")
fcon_file = File(desc="Contrast file containing contrast vectors")
class FEATModel(FSLCommand):
"""Uses FSL feat_model to generate design.mat files"""
_cmd = "feat_model"
input_spec = FEATModelInputSpec
output_spec = FEATModelOutpuSpec
def _format_arg(self, name, trait_spec, value):
if name == "fsf_file":
return super()._format_arg(name, trait_spec, self._get_design_root(value))
elif name == "ev_files":
return ""
else:
return super()._format_arg(name, trait_spec, value)
def _get_design_root(self, infile):
_, fname = os.path.split(infile)
return fname.split(".")[0]
def _list_outputs(self):
# TODO: figure out file names and get rid off the globs
outputs = self._outputs().get()
root = self._get_design_root(simplify_list(self.inputs.fsf_file))
design_file = glob(os.path.join(os.getcwd(), "%s*.mat" % root))
assert len(design_file) == 1, "No mat file generated by FEAT Model"
outputs["design_file"] = design_file[0]
design_image = glob(os.path.join(os.getcwd(), "%s.png" % root))
assert len(design_image) == 1, "No design image generated by FEAT Model"
outputs["design_image"] = design_image[0]
design_cov = glob(os.path.join(os.getcwd(), "%s_cov.png" % root))
assert len(design_cov) == 1, "No covariance image generated by FEAT Model"
outputs["design_cov"] = design_cov[0]
con_file = glob(os.path.join(os.getcwd(), "%s*.con" % root))
assert len(con_file) == 1, "No con file generated by FEAT Model"
outputs["con_file"] = con_file[0]
fcon_file = glob(os.path.join(os.getcwd(), "%s*.fts" % root))
if fcon_file:
assert len(fcon_file) == 1, "No fts file generated by FEAT Model"
outputs["fcon_file"] = fcon_file[0]
return outputs
class FILMGLSInputSpec(FSLCommandInputSpec):
in_file = File(
exists=True, mandatory=True, position=-3, argstr="%s", desc="input data file"
)
design_file = File(exists=True, position=-2, argstr="%s", desc="design matrix file")
threshold = traits.Range(
value=1000.0,
low=0.0,
argstr="%f",
position=-1,
usedefault=True,
desc="threshold",
)
smooth_autocorr = traits.Bool(argstr="-sa", desc="Smooth auto corr estimates")
mask_size = traits.Int(argstr="-ms %d", desc="susan mask size")
brightness_threshold = traits.Range(
low=0,
argstr="-epith %d",
desc=("susan brightness threshold, otherwise it is estimated"),
)
full_data = traits.Bool(argstr="-v", desc="output full data")
_estimate_xor = [
"autocorr_estimate_only",
"fit_armodel",
"tukey_window",
"multitaper_product",
"use_pava",
"autocorr_noestimate",
]
autocorr_estimate_only = traits.Bool(
argstr="-ac",
xor=_estimate_xor,
desc=("perform autocorrelation estimatation only"),
)
fit_armodel = traits.Bool(
argstr="-ar",
xor=_estimate_xor,
desc=(
"fits autoregressive model - default is "
"to use tukey with M=sqrt(numvols)"
),
)
tukey_window = traits.Int(
argstr="-tukey %d",
xor=_estimate_xor,
desc="tukey window size to estimate autocorr",
)
multitaper_product = traits.Int(
argstr="-mt %d",
xor=_estimate_xor,
desc=(
"multitapering with slepian tapers "
"and num is the time-bandwidth "
"product"
),
)
use_pava = traits.Bool(argstr="-pava", desc="estimates autocorr using PAVA")
autocorr_noestimate = traits.Bool(
argstr="-noest", xor=_estimate_xor, desc="do not estimate autocorrs"
)
output_pwdata = traits.Bool(
argstr="-output_pwdata",
desc=("output prewhitened data and average design matrix"),
)
results_dir = Directory(
"results",
argstr="-rn %s",
usedefault=True,
desc="directory to store results in",
)
class FILMGLSInputSpec505(FSLCommandInputSpec):
in_file = File(
exists=True,
mandatory=True,
position=-3,
argstr="--in=%s",
desc="input data file",
)
design_file = File(
exists=True, position=-2, argstr="--pd=%s", desc="design matrix file"
)
threshold = traits.Range(
value=1000.0,
low=0.0,
argstr="--thr=%f",
position=-1,
usedefault=True,
desc="threshold",
)
smooth_autocorr = traits.Bool(argstr="--sa", desc="Smooth auto corr estimates")
mask_size = traits.Int(argstr="--ms=%d", desc="susan mask size")
brightness_threshold = traits.Range(
low=0,
argstr="--epith=%d",
desc=("susan brightness threshold, otherwise it is estimated"),
)
full_data = traits.Bool(argstr="-v", desc="output full data")
_estimate_xor = [
"autocorr_estimate_only",
"fit_armodel",
"tukey_window",
"multitaper_product",
"use_pava",
"autocorr_noestimate",
]
autocorr_estimate_only = traits.Bool(
argstr="--ac",
xor=_estimate_xor,
desc=("perform autocorrelation estimation only"),
)
fit_armodel = traits.Bool(
argstr="--ar",
xor=_estimate_xor,
desc=(
"fits autoregressive model - default is "
"to use tukey with M=sqrt(numvols)"
),
)
tukey_window = traits.Int(
argstr="--tukey=%d",
xor=_estimate_xor,
desc="tukey window size to estimate autocorr",
)
multitaper_product = traits.Int(
argstr="--mt=%d",
xor=_estimate_xor,
desc=(
"multitapering with slepian tapers "
"and num is the time-bandwidth "
"product"
),
)
use_pava = traits.Bool(argstr="--pava", desc="estimates autocorr using PAVA")
autocorr_noestimate = traits.Bool(
argstr="--noest", xor=_estimate_xor, desc="do not estimate autocorrs"
)
output_pwdata = traits.Bool(
argstr="--outputPWdata",
desc=("output prewhitened data and average design matrix"),
)
results_dir = Directory(
"results",
argstr="--rn=%s",
usedefault=True,
desc="directory to store results in",
)
class FILMGLSInputSpec507(FILMGLSInputSpec505):
threshold = traits.Float(
default_value=-1000.0,
argstr="--thr=%f",
position=-1,
usedefault=True,
desc="threshold",
)
tcon_file = File(
exists=True, argstr="--con=%s", desc="contrast file containing T-contrasts"
)
fcon_file = File(
exists=True, argstr="--fcon=%s", desc="contrast file containing F-contrasts"
)
mode = traits.Enum(
"volumetric", "surface", argstr="--mode=%s", desc="Type of analysis to be done"
)
surface = File(
exists=True,
argstr="--in2=%s",
desc=("input surface for autocorr smoothing in surface-based analyses"),
)
class FILMGLSOutputSpec(TraitedSpec):
param_estimates = OutputMultiPath(
File(exists=True),
desc=("Parameter estimates for each column of the design matrix"),
)
residual4d = File(
exists=True,
desc=("Model fit residual mean-squared error for each time point"),
)
dof_file = File(exists=True, desc="degrees of freedom")
sigmasquareds = File(
exists=True, desc="summary of residuals, See Woolrich, et. al., 2001"
)
results_dir = Directory(
exists=True, desc="directory storing model estimation output"
)
corrections = File(
exists=True, desc=("statistical corrections used within FILM modeling")
)
thresholdac = File(exists=True, desc="The FILM autocorrelation parameters")
logfile = File(exists=True, desc="FILM run logfile")
class FILMGLSOutputSpec507(TraitedSpec):
param_estimates = OutputMultiPath(
File(exists=True),
desc=("Parameter estimates for each column of the design matrix"),
)
residual4d = File(
exists=True,
desc=("Model fit residual mean-squared error for each time point"),
)
dof_file = File(exists=True, desc="degrees of freedom")
sigmasquareds = File(
exists=True, desc="summary of residuals, See Woolrich, et. al., 2001"
)
results_dir = Directory(
exists=True, desc="directory storing model estimation output"
)
thresholdac = File(exists=True, desc="The FILM autocorrelation parameters")
logfile = File(exists=True, desc="FILM run logfile")
copes = OutputMultiPath(
File(exists=True), desc="Contrast estimates for each contrast"
)
varcopes = OutputMultiPath(
File(exists=True), desc="Variance estimates for each contrast"
)
zstats = OutputMultiPath(File(exists=True), desc="z-stat file for each contrast")
tstats = OutputMultiPath(File(exists=True), desc="t-stat file for each contrast")
fstats = OutputMultiPath(File(exists=True), desc="f-stat file for each contrast")
zfstats = OutputMultiPath(File(exists=True), desc="z-stat file for each F contrast")
class FILMGLS(FSLCommand):
"""Use FSL film_gls command to fit a design matrix to voxel timeseries
Examples
--------
Initialize with no options, assigning them when calling run:
>>> from nipype.interfaces import fsl
>>> fgls = fsl.FILMGLS()
>>> res = fgls.run('in_file', 'design_file', 'thresh', rn='stats') #doctest: +SKIP
Assign options through the ``inputs`` attribute:
>>> fgls = fsl.FILMGLS()
>>> fgls.inputs.in_file = 'functional.nii'
>>> fgls.inputs.design_file = 'design.mat'
>>> fgls.inputs.threshold = 10
>>> fgls.inputs.results_dir = 'stats'
>>> res = fgls.run() #doctest: +SKIP
Specify options when creating an instance:
>>> fgls = fsl.FILMGLS(in_file='functional.nii', \
design_file='design.mat', \
threshold=10, results_dir='stats')
>>> res = fgls.run() #doctest: +SKIP
"""
_cmd = "film_gls"
input_spec = FILMGLSInputSpec
output_spec = FILMGLSOutputSpec
if Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.6"):
input_spec = FILMGLSInputSpec507
output_spec = FILMGLSOutputSpec507
elif Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.4"):
input_spec = FILMGLSInputSpec505
def __init__(self, **inputs):
super(FILMGLS, self).__init__(**inputs)
if Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.6"):
if 'output_type' not in inputs:
if isdefined(self.inputs.mode) and self.inputs.mode == 'surface':
self.inputs.output_type = 'GIFTI'
def _get_pe_files(self, cwd):
files = None
if isdefined(self.inputs.design_file):
with open(self.inputs.design_file) as fp:
for line in fp:
if line.startswith("/NumWaves"):
numpes = int(line.split()[-1])
files = [
self._gen_fname(f"pe{i + 1}.nii", cwd=cwd)
for i in range(numpes)
]
break
return files
def _get_numcons(self):
numtcons = 0
numfcons = 0
if isdefined(self.inputs.tcon_file):
with open(self.inputs.tcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numtcons = int(line.split()[-1])
break
if isdefined(self.inputs.fcon_file):
with open(self.inputs.fcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numfcons = int(line.split()[-1])
break
return numtcons, numfcons
def _list_outputs(self):
outputs = self._outputs().get()
cwd = os.getcwd()
results_dir = os.path.join(cwd, self.inputs.results_dir)
outputs["results_dir"] = results_dir
pe_files = self._get_pe_files(results_dir)
if pe_files:
outputs["param_estimates"] = pe_files
outputs["residual4d"] = self._gen_fname("res4d.nii", cwd=results_dir)
outputs["dof_file"] = os.path.join(results_dir, "dof")
outputs["sigmasquareds"] = self._gen_fname("sigmasquareds.nii", cwd=results_dir)
outputs["thresholdac"] = self._gen_fname("threshac1.nii", cwd=results_dir)
if Info.version() and LooseVersion(Info.version()) < LooseVersion("5.0.7"):
outputs["corrections"] = self._gen_fname("corrections.nii", cwd=results_dir)
outputs["logfile"] = self._gen_fname(
"logfile", change_ext=False, cwd=results_dir
)
if Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.6"):
pth = results_dir
numtcons, numfcons = self._get_numcons()
base_contrast = 1
copes = []
varcopes = []
zstats = []
tstats = []
for i in range(numtcons):
copes.append(
self._gen_fname("cope%d.nii" % (base_contrast + i), cwd=pth)
)
varcopes.append(
self._gen_fname("varcope%d.nii" % (base_contrast + i), cwd=pth)
)
zstats.append(
self._gen_fname("zstat%d.nii" % (base_contrast + i), cwd=pth)
)
tstats.append(
self._gen_fname("tstat%d.nii" % (base_contrast + i), cwd=pth)
)
if copes:
outputs["copes"] = copes
outputs["varcopes"] = varcopes
outputs["zstats"] = zstats
outputs["tstats"] = tstats
fstats = []
zfstats = []
for i in range(numfcons):
fstats.append(
self._gen_fname("fstat%d.nii" % (base_contrast + i), cwd=pth)
)
zfstats.append(
self._gen_fname("zfstat%d.nii" % (base_contrast + i), cwd=pth)
)
if fstats:
outputs["fstats"] = fstats
outputs["zfstats"] = zfstats
return outputs
class FEATRegisterInputSpec(BaseInterfaceInputSpec):
feat_dirs = InputMultiPath(
Directory(exists=True), desc="Lower level feat dirs", mandatory=True
)
reg_image = File(
exists=True,
desc="image to register to (will be treated as standard)",
mandatory=True,
)
reg_dof = traits.Int(12, desc="registration degrees of freedom", usedefault=True)
class FEATRegisterOutputSpec(TraitedSpec):
fsf_file = File(exists=True, desc="FSL feat specification file")
class FEATRegister(BaseInterface):
"""Register feat directories to a specific standard"""
input_spec = FEATRegisterInputSpec
output_spec = FEATRegisterOutputSpec
def _run_interface(self, runtime):
fsf_header = load_template("featreg_header.tcl")
fsf_footer = load_template("feat_nongui.tcl")
fsf_dirs = load_template("feat_fe_featdirs.tcl")
num_runs = len(self.inputs.feat_dirs)
fsf_txt = fsf_header.substitute(
num_runs=num_runs,
regimage=self.inputs.reg_image,
regdof=self.inputs.reg_dof,
)
for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)):
fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir))
fsf_txt += fsf_footer.substitute()
with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f:
f.write(fsf_txt)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["fsf_file"] = os.path.abspath(os.path.join(os.getcwd(), "register.fsf"))
return outputs
class FLAMEOInputSpec(FSLCommandInputSpec):
cope_file = File(
exists=True,
argstr="--copefile=%s",
mandatory=True,
desc="cope regressor data file",
)
var_cope_file = File(
exists=True, argstr="--varcopefile=%s", desc="varcope weightings data file"
)
dof_var_cope_file = File(
exists=True, argstr="--dofvarcopefile=%s", desc="dof data file for varcope data"
)
mask_file = File(
exists=True, argstr="--maskfile=%s", mandatory=True, desc="mask file"
)
design_file = File(
exists=True, argstr="--designfile=%s", mandatory=True, desc="design matrix file"
)
t_con_file = File(
exists=True,
argstr="--tcontrastsfile=%s",
mandatory=True,
desc="ascii matrix specifying t-contrasts",
)
f_con_file = File(
exists=True,
argstr="--fcontrastsfile=%s",
desc="ascii matrix specifying f-contrasts",
)
cov_split_file = File(
exists=True,
argstr="--covsplitfile=%s",
mandatory=True,
desc="ascii matrix specifying the groups the covariance is split into",