5
5
6
6
Change directory to provide relative paths for doctests
7
7
>>> import os
8
- >>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
8
+ >>> filepath = os.path.dirname(os.path.realpath(__file__) )
9
9
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data'))
10
10
>>> os.chdir(datadir)
11
11
34
34
from ..interfaces .base import (BaseInterface , traits , TraitedSpec , File ,
35
35
InputMultiPath , OutputMultiPath ,
36
36
BaseInterfaceInputSpec , isdefined ,
37
- DynamicTraitedSpec )
37
+ DynamicTraitedSpec )
38
38
from nipype .utils .filemanip import fname_presuffix , split_filename
39
39
iflogger = logging .getLogger ('interface' )
40
40
@@ -785,7 +785,7 @@ def _list_outputs(self):
785
785
786
786
class AddCSVRowInputSpec (DynamicTraitedSpec , BaseInterfaceInputSpec ):
787
787
in_file = traits .File (mandatory = True , desc = 'Input comma-separated value (CSV) files' )
788
- _outputs = traits .Dict ( traits .Any , value = {}, usedefault = True )
788
+ _outputs = traits .Dict (traits .Any , value = {}, usedefault = True )
789
789
790
790
def __setattr__ (self , key , value ):
791
791
if key not in self .copyable_trait_names ():
@@ -876,7 +876,7 @@ def _run_interface(self, runtime):
876
876
877
877
if op .exists (self .inputs .in_file ):
878
878
formerdf = pd .read_csv (self .inputs .in_file , index_col = 0 )
879
- df = pd .concat ([formerdf , df ], ignore_index = True )
879
+ df = pd .concat ([formerdf , df ], ignore_index = True )
880
880
881
881
with open (self .inputs .in_file , 'w' ) as f :
882
882
df .to_csv (f )
@@ -993,25 +993,25 @@ class AddNoise(BaseInterface):
993
993
output_spec = AddNoiseOutputSpec
994
994
995
995
def _run_interface (self , runtime ):
996
- in_image = nb .load ( self .inputs .in_file )
996
+ in_image = nb .load (self .inputs .in_file )
997
997
in_data = in_image .get_data ()
998
998
snr = self .inputs .snr
999
999
1000
- if isdefined ( self .inputs .in_mask ):
1001
- in_mask = nb .load ( self .inputs .in_mask ).get_data ()
1000
+ if isdefined (self .inputs .in_mask ):
1001
+ in_mask = nb .load (self .inputs .in_mask ).get_data ()
1002
1002
else :
1003
- in_mask = np .ones_like ( in_data )
1003
+ in_mask = np .ones_like (in_data )
1004
1004
1005
1005
result = self .gen_noise (in_data , mask = in_mask , snr_db = snr ,
1006
1006
dist = self .inputs .dist , bg_dist = self .inputs .bg_dist )
1007
1007
res_im = nb .Nifti1Image (result , in_image .get_affine (), in_image .get_header ())
1008
1008
res_im .to_filename (self ._gen_output_filename ())
1009
1009
return runtime
1010
1010
1011
- def _gen_output_filename ( self ):
1012
- if not isdefined ( self .inputs .out_file ):
1013
- _ , base , _ = split_filename ( self .inputs .in_file )
1014
- out_file = os .path .abspath ( base + ( '_SNR% 03.2f' % self .inputs .snr ) + '.nii.gz' )
1011
+ def _gen_output_filename (self ):
1012
+ if not isdefined (self .inputs .out_file ):
1013
+ _ , base , ext = split_filename (self .inputs .in_file )
1014
+ out_file = os .path .abspath ('%s_SNR% 03.2f%s ' % ( base , self .inputs .snr , ext ) )
1015
1015
else :
1016
1016
out_file = self .inputs .out_file
1017
1017
@@ -1030,30 +1030,31 @@ def gen_noise(self, image, mask=None, snr_db=10.0, dist='normal', bg_dist='norma
1030
1030
from math import sqrt
1031
1031
snr = sqrt (np .power (10.0 , snr_db / 10.0 ))
1032
1032
1033
- if dist == 'normal' :
1034
- noise = np .random .normal (size = image .shape )
1035
- else :
1036
- raise NotImplementedError ('Only normal distribution is supported' )
1037
-
1038
1033
if mask is None :
1039
1034
mask = np .ones_like (image )
1040
1035
1041
1036
signal = image [mask > 0 ].reshape (- 1 )
1042
1037
signal = signal - signal .mean ()
1043
- S = (signal .var ())** 2
1038
+ sigma_s = signal .var ()
1039
+ sigma_n = sqrt ((sigma_s ** 2 )/ snr )
1040
+
1041
+ if dist == 'normal' :
1042
+ noise = np .random .normal (size = image .shape , scale = sigma_n )
1043
+ else :
1044
+ raise NotImplementedError ('Only normal distribution is supported' )
1044
1045
1045
1046
if np .any (mask == 0 ):
1046
1047
if bg_dist == 'rayleigh' :
1047
- bg_noise = np .random .rayleigh (size = image .shape )
1048
+ bg_noise = np .random .rayleigh (size = image .shape , scale = sigma_n )
1048
1049
noise [mask == 0 ] = bg_noise [mask == 0 ]
1049
1050
1050
- im_noise = image + noise * ( S / snr )
1051
+ im_noise = image + noise
1051
1052
return im_noise
1052
1053
1053
1054
1054
1055
class NormalizeProbabilityMapSetInputSpec (TraitedSpec ):
1055
1056
in_files = InputMultiPath (File (exists = True , mandatory = True ,
1056
- desc = 'The tpms to be normalized' ) )
1057
+ desc = 'The tpms to be normalized' ))
1057
1058
in_mask = File (exists = True , mandatory = False ,
1058
1059
desc = 'Masked voxels must sum up 1.0, 0.0 otherwise.' )
1059
1060
@@ -1080,10 +1081,10 @@ class NormalizeProbabilityMapSet(BaseInterface):
1080
1081
def _run_interface (self , runtime ):
1081
1082
mask = None
1082
1083
1083
- if isdefined ( self .inputs .in_mask ):
1084
+ if isdefined (self .inputs .in_mask ):
1084
1085
mask = self .inputs .in_mask
1085
1086
1086
- self ._out_filenames = normalize_tpms ( self .inputs .in_files , mask )
1087
+ self ._out_filenames = normalize_tpms (self .inputs .in_files , mask )
1087
1088
return runtime
1088
1089
1089
1090
def _list_outputs (self ):
@@ -1092,7 +1093,7 @@ def _list_outputs(self):
1092
1093
return outputs
1093
1094
1094
1095
1095
- def normalize_tpms ( in_files , in_mask = None , out_files = [] ):
1096
+ def normalize_tpms (in_files , in_mask = None , out_files = []):
1096
1097
"""
1097
1098
Returns the input tissue probability maps (tpms, aka volume fractions)
1098
1099
normalized to sum up 1.0 at each voxel within the mask.
@@ -1101,16 +1102,16 @@ def normalize_tpms( in_files, in_mask=None, out_files=[] ):
1101
1102
import numpy as np
1102
1103
import os .path as op
1103
1104
1104
- in_files = np .atleast_1d ( in_files ).tolist ()
1105
+ in_files = np .atleast_1d (in_files ).tolist ()
1105
1106
1106
- if len (out_files )!= len (in_files ):
1107
- for i ,finname in enumerate ( in_files ):
1108
- fname ,fext = op .splitext ( op .basename ( finname ) )
1107
+ if len (out_files ) != len (in_files ):
1108
+ for i ,finname in enumerate (in_files ):
1109
+ fname ,fext = op .splitext (op .basename (finname ) )
1109
1110
if fext == '.gz' :
1110
- fname ,fext2 = op .splitext ( fname )
1111
+ fname ,fext2 = op .splitext (fname )
1111
1112
fext = fext2 + fext
1112
1113
1113
- out_file = op .abspath (fname + '_norm' + ( '_% 02d' % i ) + fext )
1114
+ out_file = op .abspath ('%s_norm_% 02d%s ' % ( fname , i , fext ) )
1114
1115
out_files += [out_file ]
1115
1116
1116
1117
imgs = [nib .load (fim ) for fim in in_files ]
@@ -1120,39 +1121,39 @@ def normalize_tpms( in_files, in_mask=None, out_files=[] ):
1120
1121
img_data [img_data > 0.0 ] = 1.0
1121
1122
hdr = imgs [0 ].get_header ().copy ()
1122
1123
hdr ['data_type' ]= 16
1123
- hdr .set_data_dtype ( ' float32' )
1124
- nib .save ( nib .Nifti1Image ( img_data .astype (np .float32 ), imgs [0 ].get_affine (), hdr ), out_files [0 ] )
1124
+ hdr .set_data_dtype (np . float32 )
1125
+ nib .save (nib .Nifti1Image (img_data .astype (np .float32 ), imgs [0 ].get_affine (), hdr ), out_files [0 ])
1125
1126
return out_files [0 ]
1126
1127
1127
- img_data = np .array ( [ im .get_data () for im in imgs ] ).astype ( 'f32' )
1128
+ img_data = np .array ([ im .get_data () for im in imgs ] ).astype (np . float32 )
1128
1129
#img_data[img_data>1.0] = 1.0
1129
1130
img_data [img_data < 0.0 ] = 0.0
1130
- weights = np .sum ( img_data , axis = 0 )
1131
+ weights = np .sum (img_data , axis = 0 )
1131
1132
1132
- msk = np .ones_like ( imgs [0 ].get_data () )
1133
+ msk = np .ones_like (imgs [0 ].get_data ())
1133
1134
msk [ weights <= 0 ] = 0
1134
1135
1135
1136
if not in_mask is None :
1136
- msk = nib .load ( in_mask ).get_data ()
1137
+ msk = nib .load (in_mask ).get_data ()
1137
1138
msk [ msk <= 0 ] = 0
1138
1139
msk [ msk > 0 ] = 1
1139
1140
1140
- msk = np .ma .masked_equal ( msk , 0 )
1141
+ msk = np .ma .masked_equal (msk , 0 )
1141
1142
1142
1143
1143
- for i ,out_file in enumerate ( out_files ):
1144
- data = np .ma .masked_equal ( img_data [i ], 0 )
1144
+ for i ,out_file in enumerate (out_files ):
1145
+ data = np .ma .masked_equal (img_data [i ], 0 )
1145
1146
probmap = data / weights
1146
1147
hdr = imgs [i ].get_header ().copy ()
1147
1148
hdr ['data_type' ]= 16
1148
- hdr .set_data_dtype ( 'float32' )
1149
- nib .save ( nib .Nifti1Image ( probmap .astype (np .float32 ), imgs [i ].get_affine (), hdr ), out_file )
1149
+ hdr .set_data_dtype ('float32' )
1150
+ nib .save (nib .Nifti1Image (probmap .astype (np .float32 ), imgs [i ].get_affine (), hdr ), out_file )
1150
1151
1151
1152
return out_files
1152
1153
1153
1154
1154
1155
# Deprecated interfaces ---------------------------------------------------------
1155
- class Distance ( nam .Distance ):
1156
+ class Distance (nam .Distance ):
1156
1157
"""Calculates distance between two volumes.
1157
1158
1158
1159
.. deprecated:: 0.10.0
@@ -1164,7 +1165,7 @@ def __init__(self, **inputs):
1164
1165
" please use nipype.algorithms.metrics.Distance" ),
1165
1166
DeprecationWarning )
1166
1167
1167
- class Overlap ( nam .Overlap ):
1168
+ class Overlap (nam .Overlap ):
1168
1169
"""Calculates various overlap measures between two maps.
1169
1170
1170
1171
.. deprecated:: 0.10.0
@@ -1177,7 +1178,7 @@ def __init__(self, **inputs):
1177
1178
DeprecationWarning )
1178
1179
1179
1180
1180
- class FuzzyOverlap ( nam .FuzzyOverlap ):
1181
+ class FuzzyOverlap (nam .FuzzyOverlap ):
1181
1182
"""Calculates various overlap measures between two maps, using a fuzzy
1182
1183
definition.
1183
1184
0 commit comments