Skip to content

Commit

Permalink
Merge pull request #1 from satra/fix/ants
Browse files Browse the repository at this point in the history
Fix/ants
  • Loading branch information
blakedewey committed Nov 7, 2014
2 parents 8fc7d32 + b2a1e3d commit b87be8b
Show file tree
Hide file tree
Showing 11 changed files with 333 additions and 74 deletions.
2 changes: 1 addition & 1 deletion nipype/interfaces/ants/segmentation.py
Expand Up @@ -500,7 +500,7 @@ def _format_arg(self, opt, spec, val):
if priors_directory is not '':
retval = "-p %s/BrainSegmentationPrior%%02d" % priors_directory
else:
retval = "-p BrainSegmentationPrior%02d"
retval = "-p BrainSegmentationPrior%02d"
retval += ext
return retval
return super(ANTSCommand, self)._format_arg(opt, spec, val)
Expand Down
9 changes: 4 additions & 5 deletions nipype/interfaces/spm/__init__.py
Expand Up @@ -4,12 +4,11 @@

from .base import (Info, SPMCommand, logger, no_spm, scans_for_fname,
scans_for_fnames)
from .preprocess import (SliceTiming, Realign, Coregister, Normalize, Segment,
Smooth, NewSegment, DARTEL, DARTELNorm2MNI,
CreateWarped, VBMSegment)
from .preprocess import (SliceTiming, Realign, Coregister, Normalize,
Normalize12, Segment, Smooth, NewSegment, DARTEL,
DARTELNorm2MNI, CreateWarped, VBMSegment)
from .model import (Level1Design, EstimateModel, EstimateContrast, Threshold,
OneSampleTTestDesign, TwoSampleTTestDesign,
PairedTTestDesign, MultipleRegressionDesign)
from .utils import (Analyze2nii, CalcCoregAffine, ApplyTransform, Reslice,
ApplyInverseDeformation,ResliceToReference,DicomImport)

ApplyInverseDeformation, ResliceToReference, DicomImport)
4 changes: 2 additions & 2 deletions nipype/interfaces/spm/base.py
Expand Up @@ -467,7 +467,7 @@ def _make_matlab_command(self, contents, postscript=None):
fprintf('SPM path: %s\\n', which('spm'));
spm('Defaults','fMRI');
if strcmp(name, 'SPM8') || strcmp(name, 'SPM12b'),
if strcmp(name, 'SPM8') || strcmp(name(1:5), 'SPM12'),
spm_jobman('initcfg');
spm_get_defaults('cmdline', 1);
end\n
Expand Down Expand Up @@ -502,7 +502,7 @@ def _make_matlab_command(self, contents, postscript=None):
"""
if self.inputs.use_mcr:
mscript += """
if strcmp(name, 'SPM8') || strcmp(name, 'SPM12b'),
if strcmp(name, 'SPM8') || strcmp(name(1:5), 'SPM12'),
close(\'all\', \'force\');
end;
"""
Expand Down
6 changes: 3 additions & 3 deletions nipype/interfaces/spm/model.py
Expand Up @@ -92,7 +92,7 @@ class Level1DesignOutputSpec(TraitedSpec):
class Level1Design(SPMCommand):
"""Generate an SPM design matrix
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=61
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=59
Examples
--------
Expand Down Expand Up @@ -182,7 +182,7 @@ class EstimateModelOutputSpec(TraitedSpec):
class EstimateModel(SPMCommand):
"""Use spm_spm to estimate the parameters of a model
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=71
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=69
Examples
--------
Expand Down Expand Up @@ -744,7 +744,7 @@ class FactorialDesignOutputSpec(TraitedSpec):
class FactorialDesign(SPMCommand):
"""Base class for factorial designs
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=79
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=77
"""

Expand Down
274 changes: 218 additions & 56 deletions nipype/interfaces/spm/preprocess.py

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions nipype/interfaces/spm/tests/test_auto_Normalize.py
Expand Up @@ -5,16 +5,15 @@
def test_Normalize_inputs():
input_map = dict(DCT_period_cutoff=dict(field='eoptions.cutoff',
),
affine_regularization_type=dict(field='eoptions.regype',
affine_regularization_type=dict(field='eoptions.regtype',
),
apply_to_files=dict(copyfile=True,
field='subj.resample',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
jobtype=dict(usedefault=True,
),
jobtype=dict(),
matlab_cmd=dict(),
mfile=dict(usedefault=True,
),
Expand Down
71 changes: 71 additions & 0 deletions nipype/interfaces/spm/tests/test_auto_Normalize12.py
@@ -0,0 +1,71 @@
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.spm.preprocess import Normalize12

def test_Normalize12_inputs():
input_map = dict(affine_regularization_type=dict(field='eoptions.affreg',
),
apply_to_files=dict(copyfile=True,
field='subj.resample',
),
bias_fwhm=dict(field='eoptions.biasfwhm',
),
bias_regularization=dict(field='eoptions.biasreg',
),
deformation_file=dict(copyfile=False,
field='subj.def',
mandatory=True,
xor=['image_to_align', 'tpm'],
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
image_to_align=dict(copyfile=True,
field='subj.vol',
mandatory=True,
xor=['deformation_file'],
),
jobtype=dict(),
matlab_cmd=dict(),
mfile=dict(usedefault=True,
),
paths=dict(),
sampling_distance=dict(field='eoptions.samp',
),
smoothness=dict(field='eoptions.fwhm',
),
tpm=dict(copyfile=False,
field='eoptions.tpm',
mandatory=False,
xor=['deformation_file'],
),
use_mcr=dict(),
use_v8struct=dict(min_ver='8',
usedefault=True,
),
warping_regularization=dict(field='eoptions.reg',
),
write_bounding_box=dict(field='woptions.bb',
),
write_interp=dict(field='woptions.interp',
),
write_voxel_sizes=dict(field='woptions.vox',
),
)
inputs = Normalize12.input_spec()

for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_Normalize12_outputs():
output_map = dict(deformation_field=dict(),
normalized_files=dict(),
normalized_image=dict(),
)
outputs = Normalize12.output_spec()

for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value

16 changes: 15 additions & 1 deletion nipype/interfaces/spm/tests/test_preprocess.py
Expand Up @@ -85,10 +85,24 @@ def test_normalize_list_outputs():
filelist, outdir, cwd = create_files_in_directory()
norm = spm.Normalize(source=filelist[0])
yield assert_true, norm._list_outputs()['normalized_source'][0].startswith('w')
norm = spm.Normalize(source=filelist[0],apply_to_files=filelist[1])
norm = spm.Normalize(source=filelist[0], apply_to_files=filelist[1])
yield assert_true, norm._list_outputs()['normalized_files'][0].startswith('w')
clean_directory(outdir, cwd)

def test_normalize12():
yield assert_equal, spm.Normalize12._jobtype, 'spatial'
yield assert_equal, spm.Normalize12._jobname, 'normalise'
yield assert_equal, spm.Normalize12().inputs.jobtype, 'estwrite'

def test_normalize12_list_outputs():
filelist, outdir, cwd = create_files_in_directory()
norm12 = spm.Normalize12(image_to_align=filelist[0])
yield assert_true, norm12._list_outputs()['normalized_image'][0].startswith('w')
norm12 = spm.Normalize12(image_to_align=filelist[0],
apply_to_files=filelist[1])
yield assert_true, norm12._list_outputs()['normalized_files'][0].startswith('w')
clean_directory(outdir, cwd)

@skipif(no_spm)
def test_segment():
if spm.Info.version()['name'] == "SPM12":
Expand Down
9 changes: 9 additions & 0 deletions nipype/interfaces/utility.py
@@ -1,5 +1,14 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Various utilities
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data'))
>>> os.chdir(datadir)
"""

import os
import re
from cPickle import dumps, loads
Expand Down
5 changes: 4 additions & 1 deletion nipype/pipeline/plugins/ipython.py
Expand Up @@ -22,6 +22,8 @@ def execute_task(pckld_task, node_config, updatehash):
from nipype import config, logging
traceback=None
result=None
import os
cwd = os.getcwd()
try:
config.update_config(node_config)
logging.update_logging(config)
Expand All @@ -31,6 +33,7 @@ def execute_task(pckld_task, node_config, updatehash):
except:
traceback = format_exc()
result = task.result
os.chdir(cwd)
return result, traceback, gethostname()

class IPythonPlugin(DistributedPluginBase):
Expand Down Expand Up @@ -72,7 +75,7 @@ def run(self, graph, config, updatehash=False):

def _get_result(self, taskid):
if taskid not in self.taskmap:
raise ValueError('Task %d not in pending list'%taskid)
raise ValueError('Task %d not in pending list' % taskid)
if self.taskmap[taskid].ready():
result, traceback, hostname = self.taskmap[taskid].get()
result_out = dict(result=None, traceback=None)
Expand Down
6 changes: 4 additions & 2 deletions nipype/workflows/dmri/fsl/utils.py
Expand Up @@ -381,9 +381,11 @@ def recompose_xfm(in_bval, in_xfms):
return out_files


def b0_average(in_dwi, in_bval, out_file=None):
def b0_average(in_dwi, in_bval, max_b=10.0, out_file=None):
"""
A function that averages the *b0* volumes from a DWI dataset.
As current dMRI data are being acquired with all b-values > 0.0,
the *lowb* volumes are selected by specifying the parameter max_b.
.. warning:: *b0* should be already registered (head motion artifact should
be corrected).
Expand All @@ -403,7 +405,7 @@ def b0_average(in_dwi, in_bval, out_file=None):
imgs = np.array(nb.four_to_three(nb.load(in_dwi)))
bval = np.loadtxt(in_bval)
b0s = [im.get_data().astype(np.float32)
for im in imgs[np.where(bval == 0)]]
for im in imgs[np.where(bval <= max_b)]]
b0 = np.average(np.array(b0s), axis=0)

hdr = imgs[0].get_header().copy()
Expand Down

0 comments on commit b87be8b

Please sign in to comment.