-
Notifications
You must be signed in to change notification settings - Fork 523
/
misc.py
1683 lines (1342 loc) · 51.4 KB
/
misc.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
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Miscellaneous algorithms."""
import os
import os.path as op
import nibabel as nb
import numpy as np
from math import floor, ceil
import itertools
import warnings
from .. import logging
from . import metrics as nam
from ..interfaces.base import (
BaseInterface,
traits,
TraitedSpec,
File,
InputMultiPath,
OutputMultiPath,
BaseInterfaceInputSpec,
isdefined,
DynamicTraitedSpec,
Undefined,
)
from ..utils.filemanip import fname_presuffix, split_filename, ensure_list
from . import confounds
iflogger = logging.getLogger("nipype.interface")
class PickAtlasInputSpec(BaseInterfaceInputSpec):
atlas = File(
exists=True, desc="Location of the atlas that will be used.", mandatory=True
)
labels = traits.Either(
traits.Int,
traits.List(traits.Int),
desc=(
"Labels of regions that will be included in the mask. Must be\
compatible with the atlas used."
),
mandatory=True,
)
hemi = traits.Enum(
"both",
"left",
"right",
desc="Restrict the mask to only one hemisphere: left or right",
usedefault=True,
)
dilation_size = traits.Int(
usedefault=True,
desc="Defines how much the mask will be dilated (expanded in 3D).",
)
output_file = File(desc="Where to store the output mask.")
class PickAtlasOutputSpec(TraitedSpec):
mask_file = File(exists=True, desc="output mask file")
class PickAtlas(BaseInterface):
"""Returns ROI masks given an atlas and a list of labels. Supports dilation
and left right masking (assuming the atlas is properly aligned).
"""
input_spec = PickAtlasInputSpec
output_spec = PickAtlasOutputSpec
def _run_interface(self, runtime):
nim = self._get_brodmann_area()
nb.save(nim, self._gen_output_filename())
return runtime
def _gen_output_filename(self):
if not isdefined(self.inputs.output_file):
output = fname_presuffix(
fname=self.inputs.atlas,
suffix="_mask",
newpath=os.getcwd(),
use_ext=True,
)
else:
output = os.path.realpath(self.inputs.output_file)
return output
def _get_brodmann_area(self):
nii = nb.load(self.inputs.atlas)
origdata = np.asanyarray(nii.dataobj)
newdata = np.zeros(origdata.shape)
if not isinstance(self.inputs.labels, list):
labels = [self.inputs.labels]
else:
labels = self.inputs.labels
for lab in labels:
newdata[origdata == lab] = 1
if self.inputs.hemi == "right":
newdata[int(floor(float(origdata.shape[0]) / 2)) :, :, :] = 0
elif self.inputs.hemi == "left":
newdata[: int(ceil(float(origdata.shape[0]) / 2)), :, :] = 0
if self.inputs.dilation_size != 0:
from scipy.ndimage.morphology import grey_dilation
newdata = grey_dilation(
newdata,
(
2 * self.inputs.dilation_size + 1,
2 * self.inputs.dilation_size + 1,
2 * self.inputs.dilation_size + 1,
),
)
return nb.Nifti1Image(newdata, nii.affine, nii.header)
def _list_outputs(self):
outputs = self._outputs().get()
outputs["mask_file"] = self._gen_output_filename()
return outputs
class SimpleThresholdInputSpec(BaseInterfaceInputSpec):
volumes = InputMultiPath(
File(exists=True), desc="volumes to be thresholded", mandatory=True
)
threshold = traits.Float(
desc="volumes to be thresholdedeverything below this value will be set\
to zero",
mandatory=True,
)
class SimpleThresholdOutputSpec(TraitedSpec):
thresholded_volumes = OutputMultiPath(File(exists=True), desc="thresholded volumes")
class SimpleThreshold(BaseInterface):
"""Applies a threshold to input volumes"""
input_spec = SimpleThresholdInputSpec
output_spec = SimpleThresholdOutputSpec
def _run_interface(self, runtime):
for fname in self.inputs.volumes:
img = nb.load(fname)
data = img.get_fdata()
active_map = data > self.inputs.threshold
thresholded_map = np.zeros(data.shape)
thresholded_map[active_map] = data[active_map]
new_img = nb.Nifti1Image(thresholded_map, img.affine, img.header)
_, base, _ = split_filename(fname)
nb.save(new_img, base + "_thresholded.nii")
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["thresholded_volumes"] = []
for fname in self.inputs.volumes:
_, base, _ = split_filename(fname)
outputs["thresholded_volumes"].append(
os.path.abspath(base + "_thresholded.nii")
)
return outputs
class ModifyAffineInputSpec(BaseInterfaceInputSpec):
volumes = InputMultiPath(
File(exists=True),
desc="volumes which affine matrices will be modified",
mandatory=True,
)
transformation_matrix = traits.Array(
value=np.eye(4),
shape=(4, 4),
desc="transformation matrix that will be left multiplied by the\
affine matrix",
usedefault=True,
)
class ModifyAffineOutputSpec(TraitedSpec):
transformed_volumes = OutputMultiPath(File(exist=True))
class ModifyAffine(BaseInterface):
"""Left multiplies the affine matrix with a specified values. Saves the volume
as a nifti file.
"""
input_spec = ModifyAffineInputSpec
output_spec = ModifyAffineOutputSpec
def _gen_output_filename(self, name):
_, base, _ = split_filename(name)
return os.path.abspath(base + "_transformed.nii")
def _run_interface(self, runtime):
for fname in self.inputs.volumes:
img = nb.load(fname)
affine = img.affine
affine = np.dot(self.inputs.transformation_matrix, affine)
nb.save(
nb.Nifti1Image(img.dataobj, affine, img.header),
self._gen_output_filename(fname),
)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["transformed_volumes"] = []
for fname in self.inputs.volumes:
outputs["transformed_volumes"].append(self._gen_output_filename(fname))
return outputs
class CreateNiftiInputSpec(BaseInterfaceInputSpec):
data_file = File(exists=True, mandatory=True, desc="ANALYZE img file")
header_file = File(
exists=True, mandatory=True, desc="corresponding ANALYZE hdr file"
)
affine = traits.Array(desc="affine transformation array")
class CreateNiftiOutputSpec(TraitedSpec):
nifti_file = File(exists=True)
class CreateNifti(BaseInterface):
"""Creates a nifti volume"""
input_spec = CreateNiftiInputSpec
output_spec = CreateNiftiOutputSpec
def _gen_output_file_name(self):
_, base, _ = split_filename(self.inputs.data_file)
return os.path.abspath(base + ".nii")
def _run_interface(self, runtime):
with open(self.inputs.header_file, "rb") as hdr_file:
hdr = nb.AnalyzeHeader.from_fileobj(hdr_file)
if isdefined(self.inputs.affine):
affine = self.inputs.affine
else:
affine = None
with open(self.inputs.data_file, "rb") as data_file:
data = hdr.data_from_fileobj(data_file)
img = nb.Nifti1Image(data, affine, hdr)
nb.save(img, self._gen_output_file_name())
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["nifti_file"] = self._gen_output_file_name()
return outputs
class GzipInputSpec(TraitedSpec):
in_file = File(exists=True, mandatory=True, desc="file to (de)compress")
mode = traits.Enum(
"compress", "decompress", usedefault=True, desc="compress or decompress"
)
class GzipOutputSpec(TraitedSpec):
out_file = File()
class Gzip(BaseInterface):
"""Gzip wrapper
>>> from nipype.algorithms.misc import Gzip
>>> gzip = Gzip(in_file='tpms_msk.nii.gz', mode="decompress")
>>> res = gzip.run()
>>> res.outputs.out_file # doctest: +ELLIPSIS
'.../tpms_msk.nii'
>>> gzip = Gzip(in_file='tpms_msk.nii')
>>> res = gzip.run()
>>> res.outputs.out_file # doctest: +ELLIPSIS
'.../tpms_msk.nii.gz'
.. testcleanup::
>>> os.unlink('tpms_msk.nii')
"""
input_spec = GzipInputSpec
output_spec = GzipOutputSpec
def _gen_output_file_name(self):
_, base, ext = split_filename(self.inputs.in_file)
if self.inputs.mode == "decompress" and ext[-3:].lower() == ".gz":
ext = ext[:-3]
elif self.inputs.mode == "compress":
ext = f"{ext}.gz"
return os.path.abspath(base + ext)
def _run_interface(self, runtime):
import gzip
import shutil
if self.inputs.mode == "compress":
open_input, open_output = open, gzip.open
else:
open_input, open_output = gzip.open, open
with open_input(self.inputs.in_file, "rb") as in_file:
with open_output(self._gen_output_file_name(), "wb") as out_file:
shutil.copyfileobj(in_file, out_file)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_file"] = self._gen_output_file_name()
return outputs
class GunzipInputSpec(GzipInputSpec):
mode = traits.Enum("decompress", usedefault=True, desc="decompress or compress")
class Gunzip(Gzip):
"""Gunzip wrapper
>>> from nipype.algorithms.misc import Gunzip
>>> gunzip = Gunzip(in_file='tpms_msk.nii.gz')
>>> res = gunzip.run()
>>> res.outputs.out_file # doctest: +ELLIPSIS
'.../tpms_msk.nii'
.. testcleanup::
>>> os.unlink('tpms_msk.nii')
"""
input_spec = GunzipInputSpec
def replaceext(in_list, ext):
out_list = list()
for filename in in_list:
path, name, _ = split_filename(op.abspath(filename))
out_name = op.join(path, name) + ext
out_list.append(out_name)
return out_list
def _matlab2csv(in_array, name, reshape):
output_array = np.asarray(in_array)
if reshape:
if len(np.shape(output_array)) > 1:
output_array = np.reshape(
output_array, (np.shape(output_array)[0] * np.shape(output_array)[1], 1)
)
iflogger.info(np.shape(output_array))
output_name = op.abspath(name + ".csv")
np.savetxt(output_name, output_array, delimiter=",")
return output_name
class Matlab2CSVInputSpec(TraitedSpec):
in_file = File(exists=True, mandatory=True, desc="Input MATLAB .mat file")
reshape_matrix = traits.Bool(
True,
usedefault=True,
desc="The output of this interface is meant for R, so matrices will be\
reshaped to vectors by default.",
)
class Matlab2CSVOutputSpec(TraitedSpec):
csv_files = OutputMultiPath(
File(
desc="Output CSV files for each variable saved in the input .mat\
file"
)
)
class Matlab2CSV(BaseInterface):
"""
Save the components of a MATLAB .mat file as a text file with comma-separated values (CSVs).
CSV files are easily loaded in R, for use in statistical processing.
For further information, see cran.r-project.org/doc/manuals/R-data.pdf
Example
-------
>>> from nipype.algorithms import misc
>>> mat2csv = misc.Matlab2CSV()
>>> mat2csv.inputs.in_file = 'cmatrix.mat'
>>> mat2csv.run() # doctest: +SKIP
"""
input_spec = Matlab2CSVInputSpec
output_spec = Matlab2CSVOutputSpec
def _run_interface(self, runtime):
import scipy.io as sio
in_dict = sio.loadmat(op.abspath(self.inputs.in_file))
# Check if the file has multiple variables in it. If it does, loop
# through them and save them as individual CSV files.
# If not, save the variable as a single CSV file using the input file
# name and a .csv extension.
saved_variables = list()
for key in list(in_dict.keys()):
if not key.startswith("__"):
if isinstance(in_dict[key][0], np.ndarray):
saved_variables.append(key)
else:
iflogger.info(
"One of the keys in the input file, %s, is "
"not a Numpy array",
key,
)
if len(saved_variables) > 1:
iflogger.info("%i variables found:", len(saved_variables))
iflogger.info(saved_variables)
for variable in saved_variables:
iflogger.info(
"...Converting %s - type %s - to CSV",
variable,
type(in_dict[variable]),
)
_matlab2csv(in_dict[variable], variable, self.inputs.reshape_matrix)
elif len(saved_variables) == 1:
_, name, _ = split_filename(self.inputs.in_file)
variable = saved_variables[0]
iflogger.info(
"Single variable found %s, type %s:", variable, type(in_dict[variable])
)
iflogger.info(
"...Converting %s to CSV from %s", variable, self.inputs.in_file
)
_matlab2csv(in_dict[variable], name, self.inputs.reshape_matrix)
else:
iflogger.error("No values in the MATLAB file?!")
return runtime
def _list_outputs(self):
import scipy.io as sio
outputs = self.output_spec().get()
in_dict = sio.loadmat(op.abspath(self.inputs.in_file))
saved_variables = list()
for key in list(in_dict.keys()):
if not key.startswith("__"):
if isinstance(in_dict[key][0], np.ndarray):
saved_variables.append(key)
else:
iflogger.error(
"One of the keys in the input file, %s, is "
"not a Numpy array",
key,
)
if len(saved_variables) > 1:
outputs["csv_files"] = replaceext(saved_variables, ".csv")
elif len(saved_variables) == 1:
_, name, ext = split_filename(self.inputs.in_file)
outputs["csv_files"] = op.abspath(name + ".csv")
else:
iflogger.error("No values in the MATLAB file?!")
return outputs
def merge_csvs(in_list):
for idx, in_file in enumerate(in_list):
try:
in_array = np.loadtxt(in_file, delimiter=",")
except ValueError:
try:
in_array = np.loadtxt(in_file, delimiter=",", skiprows=1)
except ValueError:
with open(in_file, "r") as first:
header_line = first.readline()
header_list = header_line.split(",")
n_cols = len(header_list)
try:
in_array = np.loadtxt(
in_file,
delimiter=",",
skiprows=1,
usecols=list(range(1, n_cols)),
)
except ValueError:
in_array = np.loadtxt(
in_file,
delimiter=",",
skiprows=1,
usecols=list(range(1, n_cols - 1)),
)
if idx == 0:
out_array = in_array
else:
out_array = np.dstack((out_array, in_array))
out_array = np.squeeze(out_array)
iflogger.info("Final output array shape:")
iflogger.info(np.shape(out_array))
return out_array
def remove_identical_paths(in_files):
import os.path as op
from ..utils.filemanip import split_filename
if len(in_files) > 1:
out_names = list()
commonprefix = op.commonprefix(in_files)
lastslash = commonprefix.rfind("/")
commonpath = commonprefix[0 : (lastslash + 1)]
for fileidx, in_file in enumerate(in_files):
path, name, ext = split_filename(in_file)
in_file = op.join(path, name)
name = in_file.replace(commonpath, "")
name = name.replace("_subject_id_", "")
out_names.append(name)
else:
path, name, ext = split_filename(in_files[0])
out_names = [name]
return out_names
def maketypelist(rowheadings, shape, extraheadingBool, extraheading):
typelist = []
if rowheadings:
typelist.append(("heading", "a40"))
if len(shape) > 1:
for idx in range(1, (min(shape) + 1)):
typelist.append((str(idx), float))
else:
for idx in range(1, (shape[0] + 1)):
typelist.append((str(idx), float))
if extraheadingBool:
typelist.append((extraheading, "a40"))
iflogger.info(typelist)
return typelist
def makefmtlist(output_array, typelist, rowheadingsBool, shape, extraheadingBool):
fmtlist = []
if rowheadingsBool:
fmtlist.append("%s")
if len(shape) > 1:
output = np.zeros(max(shape), typelist)
for idx in range(1, min(shape) + 1):
output[str(idx)] = output_array[:, idx - 1]
fmtlist.append("%f")
else:
output = np.zeros(1, typelist)
for idx in range(1, len(output_array) + 1):
output[str(idx)] = output_array[idx - 1]
fmtlist.append("%f")
if extraheadingBool:
fmtlist.append("%s")
fmt = ",".join(fmtlist)
return fmt, output
class MergeCSVFilesInputSpec(TraitedSpec):
in_files = InputMultiPath(
File(exists=True),
mandatory=True,
desc="Input comma-separated value (CSV) files",
)
out_file = File(
"merged.csv", usedefault=True, desc="Output filename for merged CSV file"
)
column_headings = traits.List(
traits.Str,
desc="List of column headings to save in merged CSV file\
(must be equal to number of input files). If left undefined, these\
will be pulled from the input filenames.",
)
row_headings = traits.List(
traits.Str,
desc="List of row headings to save in merged CSV file\
(must be equal to number of rows in the input files).",
)
row_heading_title = traits.Str(
"label",
usedefault=True,
desc="Column heading for the row headings\
added",
)
extra_column_heading = traits.Str(desc="New heading to add for the added field.")
extra_field = traits.Str(
desc="New field to add to each row. This is useful for saving the\
group or subject ID in the file."
)
class MergeCSVFilesOutputSpec(TraitedSpec):
csv_file = File(desc="Output CSV file containing columns ")
class MergeCSVFiles(BaseInterface):
"""
Merge several CSV files into a single CSV file.
This interface is designed to facilitate data loading in the R environment.
If provided, it will also incorporate column heading names into the
resulting CSV file.
CSV files are easily loaded in R, for use in statistical processing.
For further information, see cran.r-project.org/doc/manuals/R-data.pdf
Example
-------
>>> from nipype.algorithms import misc
>>> mat2csv = misc.MergeCSVFiles()
>>> mat2csv.inputs.in_files = ['degree.mat','clustering.mat']
>>> mat2csv.inputs.column_headings = ['degree','clustering']
>>> mat2csv.run() # doctest: +SKIP
"""
input_spec = MergeCSVFilesInputSpec
output_spec = MergeCSVFilesOutputSpec
def _run_interface(self, runtime):
extraheadingBool = False
extraheading = ""
rowheadingsBool = False
"""
This block defines the column headings.
"""
if isdefined(self.inputs.column_headings):
iflogger.info("Column headings have been provided:")
headings = self.inputs.column_headings
else:
iflogger.info("Column headings not provided! Pulled from input filenames:")
headings = remove_identical_paths(self.inputs.in_files)
if isdefined(self.inputs.extra_field):
if isdefined(self.inputs.extra_column_heading):
extraheading = self.inputs.extra_column_heading
iflogger.info("Extra column heading provided: %s", extraheading)
else:
extraheading = "type"
iflogger.info('Extra column heading was not defined. Using "type"')
headings.append(extraheading)
extraheadingBool = True
if len(self.inputs.in_files) == 1:
iflogger.warning("Only one file input!")
if isdefined(self.inputs.row_headings):
iflogger.info(
'Row headings have been provided. Adding "labels"' "column header."
)
prefix = '"{p}","'.format(p=self.inputs.row_heading_title)
csv_headings = prefix + '","'.join(itertools.chain(headings)) + '"\n'
rowheadingsBool = True
else:
iflogger.info("Row headings have not been provided.")
csv_headings = '"' + '","'.join(itertools.chain(headings)) + '"\n'
iflogger.info("Final Headings:")
iflogger.info(csv_headings)
"""
Next we merge the arrays and define the output text file
"""
output_array = merge_csvs(self.inputs.in_files)
_, name, ext = split_filename(self.inputs.out_file)
if not ext == ".csv":
ext = ".csv"
out_file = op.abspath(name + ext)
with open(out_file, "w") as file_handle:
file_handle.write(csv_headings)
shape = np.shape(output_array)
typelist = maketypelist(rowheadingsBool, shape, extraheadingBool, extraheading)
fmt, output = makefmtlist(
output_array, typelist, rowheadingsBool, shape, extraheadingBool
)
if rowheadingsBool:
row_heading_list = self.inputs.row_headings
row_heading_list_with_quotes = []
for row_heading in row_heading_list:
row_heading_with_quotes = '"' + row_heading + '"'
row_heading_list_with_quotes.append(row_heading_with_quotes)
row_headings = np.array(row_heading_list_with_quotes, dtype="|S40")
output["heading"] = row_headings
if isdefined(self.inputs.extra_field):
extrafieldlist = []
if len(shape) > 1:
mx = shape[0]
else:
mx = 1
for idx in range(0, mx):
extrafieldlist.append(self.inputs.extra_field)
iflogger.info(len(extrafieldlist))
output[extraheading] = extrafieldlist
iflogger.info(output)
iflogger.info(fmt)
with open(out_file, "a") as file_handle:
np.savetxt(file_handle, output, fmt, delimiter=",")
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
_, name, ext = split_filename(self.inputs.out_file)
if not ext == ".csv":
ext = ".csv"
out_file = op.abspath(name + ext)
outputs["csv_file"] = out_file
return outputs
class AddCSVColumnInputSpec(TraitedSpec):
in_file = File(
exists=True, mandatory=True, desc="Input comma-separated value (CSV) files"
)
out_file = File(
"extra_heading.csv", usedefault=True, desc="Output filename for merged CSV file"
)
extra_column_heading = traits.Str(desc="New heading to add for the added field.")
extra_field = traits.Str(
desc="New field to add to each row. This is useful for saving the\
group or subject ID in the file."
)
class AddCSVColumnOutputSpec(TraitedSpec):
csv_file = File(desc="Output CSV file containing columns ")
class AddCSVColumn(BaseInterface):
"""
Short interface to add an extra column and field to a text file.
Example
-------
>>> from nipype.algorithms import misc
>>> addcol = misc.AddCSVColumn()
>>> addcol.inputs.in_file = 'degree.csv'
>>> addcol.inputs.extra_column_heading = 'group'
>>> addcol.inputs.extra_field = 'male'
>>> addcol.run() # doctest: +SKIP
"""
input_spec = AddCSVColumnInputSpec
output_spec = AddCSVColumnOutputSpec
def _run_interface(self, runtime):
in_file = open(self.inputs.in_file, "r")
_, name, ext = split_filename(self.inputs.out_file)
if not ext == ".csv":
ext = ".csv"
out_file = op.abspath(name + ext)
out_file = open(out_file, "w")
firstline = in_file.readline()
firstline = firstline.replace("\n", "")
new_firstline = firstline + ',"' + self.inputs.extra_column_heading + '"\n'
out_file.write(new_firstline)
for line in in_file:
new_line = line.replace("\n", "")
new_line = new_line + "," + self.inputs.extra_field + "\n"
out_file.write(new_line)
in_file.close()
out_file.close()
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
_, name, ext = split_filename(self.inputs.out_file)
if not ext == ".csv":
ext = ".csv"
out_file = op.abspath(name + ext)
outputs["csv_file"] = out_file
return outputs
class AddCSVRowInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):
in_file = File(mandatory=True, desc="Input comma-separated value (CSV) files")
_outputs = traits.Dict(traits.Any, value={}, usedefault=True)
def __setattr__(self, key, value):
if key not in self.copyable_trait_names():
if not isdefined(value):
super(AddCSVRowInputSpec, self).__setattr__(key, value)
self._outputs[key] = value
else:
if key in self._outputs:
self._outputs[key] = value
super(AddCSVRowInputSpec, self).__setattr__(key, value)
class AddCSVRowOutputSpec(TraitedSpec):
csv_file = File(desc="Output CSV file containing rows ")
class AddCSVRow(BaseInterface):
"""
Simple interface to add an extra row to a CSV file.
.. note:: Requires `pandas <http://pandas.pydata.org/>`_
.. warning:: Multi-platform thread-safe execution is possible with
`lockfile <https://pythonhosted.org/lockfile/lockfile.html>`_. Please
recall that (1) this module is alpha software; and (2) it should be
installed for thread-safe writing.
If lockfile is not installed, then the interface is not thread-safe.
Example
-------
>>> from nipype.algorithms import misc
>>> addrow = misc.AddCSVRow()
>>> addrow.inputs.in_file = 'scores.csv'
>>> addrow.inputs.si = 0.74
>>> addrow.inputs.di = 0.93
>>> addrow.inputs.subject_id = 'S400'
>>> addrow.inputs.list_of_values = [ 0.4, 0.7, 0.3 ]
>>> addrow.run() # doctest: +SKIP
"""
input_spec = AddCSVRowInputSpec
output_spec = AddCSVRowOutputSpec
def __init__(self, infields=None, force_run=True, **kwargs):
super(AddCSVRow, self).__init__(**kwargs)
undefined_traits = {}
self._infields = infields
self._have_lock = False
self._lock = None
if infields:
for key in infields:
self.inputs.add_trait(key, traits.Any)
self.inputs._outputs[key] = Undefined
undefined_traits[key] = Undefined
self.inputs.trait_set(trait_change_notify=False, **undefined_traits)
if force_run:
self._always_run = True
def _run_interface(self, runtime):
try:
import pandas as pd
except ImportError as e:
raise ImportError(
"This interface requires pandas " "(http://pandas.pydata.org/) to run."
) from e
try:
from filelock import SoftFileLock
self._have_lock = True
except ImportError:
from warnings import warn
warn(
(
"Python module filelock was not found: AddCSVRow will not be"
" thread-safe in multi-processor execution"
)
)
input_dict = {}
for key, val in list(self.inputs._outputs.items()):
# expand lists to several columns
if key == "trait_added" and val in self.inputs.copyable_trait_names():
continue
if isinstance(val, list):
for i, v in enumerate(val):
input_dict["%s_%d" % (key, i)] = v
else:
input_dict[key] = val
df = pd.DataFrame([input_dict])
if self._have_lock:
self._lock = SoftFileLock("%s.lock" % self.inputs.in_file)
# Acquire lock
self._lock.acquire()
if op.exists(self.inputs.in_file):
formerdf = pd.read_csv(self.inputs.in_file, index_col=0)
df = pd.concat([formerdf, df], ignore_index=True)
with open(self.inputs.in_file, "w") as f:
df.to_csv(f)
if self._have_lock:
self._lock.release()
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["csv_file"] = self.inputs.in_file
return outputs
def _outputs(self):
return self._add_output_traits(super(AddCSVRow, self)._outputs())
def _add_output_traits(self, base):
return base
class CalculateNormalizedMomentsInputSpec(TraitedSpec):
timeseries_file = File(
exists=True,
mandatory=True,
desc="Text file with timeseries in columns and timepoints in rows,\
whitespace separated",
)
moment = traits.Int(
mandatory=True,
desc="Define which moment should be calculated, 3 for skewness, 4 for\
kurtosis.",
)
class CalculateNormalizedMomentsOutputSpec(TraitedSpec):
moments = traits.List(traits.Float(), desc="Moments")
class CalculateNormalizedMoments(BaseInterface):
"""
Calculates moments of timeseries.
Example
-------
>>> from nipype.algorithms import misc
>>> skew = misc.CalculateNormalizedMoments()
>>> skew.inputs.moment = 3
>>> skew.inputs.timeseries_file = 'timeseries.txt'
>>> skew.run() # doctest: +SKIP
"""
input_spec = CalculateNormalizedMomentsInputSpec
output_spec = CalculateNormalizedMomentsOutputSpec
def _run_interface(self, runtime):
self._moments = calc_moments(self.inputs.timeseries_file, self.inputs.moment)
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["skewness"] = self._moments
return outputs
def calc_moments(timeseries_file, moment):
"""Returns nth moment (3 for skewness, 4 for kurtosis) of timeseries
(list of values; one per timeseries).
Keyword arguments:
timeseries_file -- text file with white space separated timepoints in rows
"""
import scipy.stats as stats
timeseries = np.genfromtxt(timeseries_file)
m2 = stats.moment(timeseries, 2, axis=0)
m3 = stats.moment(timeseries, moment, axis=0)
zero = m2 == 0
return np.where(zero, 0, m3 / m2 ** (moment / 2.0))
class AddNoiseInputSpec(TraitedSpec):
in_file = File(