File: python_interface_devel.rst

package info (click to toggle)
nipype 0.5.3-2wheezy2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,884 kB
  • sloc: python: 36,872; tcl: 597; makefile: 167
file content (55 lines) | stat: -rw-r--r-- 1,989 bytes parent folder | download
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
.. python_interface_devel:

===========================
How to wrap a Python script
===========================

This is a minimal pure python interface. As you can see all you need to do is to
do is to define inputs, outputs, _run_interface() (not run()), and _list_outputs. 

.. testcode::
	
    from nipype.interfaces.base import BaseInterface, \
        BaseInterfaceInputSpec, traits, File
    from nipype.utils.filemanip import split_filename
        
    import nibabel as nb
    import numpy as np
    import os
    
    class SimpleThresholdInputSpec(BaseInterfaceInputSpec):
        volume = File(exists=True, desc='volume to be thresholded', mandatory=True)
        threshold = traits.Float(desc='everything below this value will be set to zero',
                                 mandatory=True)
        
        
    class SimpleThresholdOutputSpec(TraitedSpec):
        thresholded_volume = File(exists=True, desc="thresholded volume")
        
    
    class SimpleThreshold(BaseInterface):
        input_spec = SimpleThresholdInputSpec
        output_spec = SimpleThresholdOutputSpec
        
        def _run_interface(self, runtime):
            fname = self.inputs.volume
            img = nb.load(fname)
            data = np.array(img.get_data())
            
            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.get_affine(), img.get_header())
            _, base, _ = split_filename(fname)
            nb.save(new_img, base + '_thresholded.nii')
            
            return runtime
        
        def _list_outputs(self):
            outputs = self._outputs().get()
            fname = self.inputs.volume
            _, base, _ = split_filename(fname)
            outputs["thresholded_volume"] = os.path.abspath(base + '_thresholded.nii')
            return outputs