external

Calls to external packages

test Run tests for module using nose.

Module: external.fsl

FSL IO

Dpy(fname[, mode, compression])

Methods

FSLError Class signals error in FSL processing
InTemporaryDirectory([suffix, prefix, dir]) Create, return, and change directory to a temporary directory
Popen(args[, bufsize, executable, stdin, …]) Execute a child program in a new process.
affine_transform(input, matrix[, offset, …]) Apply an affine transformation.
apply_warp(in_nii, affine_mat, nonlin_nii, …)
bet(in_nii, out_nii[, options])
create_displacements(fin, fmat, fnonlin, …) Create displacements using FSL’s FLIRT and FNIRT tools
dcm2nii(dname, outdir[, filt, options])
eddy_correct(in_nii, out_nii[, ref])
flirt2aff(mat, in_img, ref_img) Transform from in_img voxels to ref_img voxels given mat
flirt2aff_files(matfile, in_fname, ref_fname) Map from in_fname image voxels to ref_fname voxels given matfile
have_flirt() Return True if we can call flirt without error
mc(input, coordinates[, output, order, …]) Map the input array to new coordinates by interpolation.
pipe(cmd[, print_sto, print_ste]) A tine pipeline system to run external tools.
pjoin(a, *p) Join two or more pathname components, inserting ‘/’ as needed.
run_flirt_imgs(in_img, ref_img[, dof, flags]) Run flirt on nibabel images, returning affine
warp_displacements(ffa, flaff, fdis, fref, ffaw) Warp an image using fsl displacements
warp_displacements_tracks(fdpy, ffa, fmat, …) Warp tracks from native space to the FMRIB58/MNI space
write_bvals_bvecs(bvals, bvecs[, outpath, …]) Write FSL FDT bvals and bvecs files

test

dipy.external.test(label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None, timer=False)

Run tests for module using nose.

Parameters:
label : {‘fast’, ‘full’, ‘’, attribute identifier}, optional

Identifies the tests to run. This can be a string to pass to the nosetests executable with the ‘-A’ option, or one of several special values. Special values are: * ‘fast’ - the default - which corresponds to the nosetests -A

option of ‘not slow’.

  • ‘full’ - fast (as above) and slow tests as in the ‘no -A’ option to nosetests - this is the same as ‘’.
  • None or ‘’ - run all tests.

attribute_identifier - string passed directly to nosetests as ‘-A’.

verbose : int, optional

Verbosity value for test outputs, in the range 1-10. Default is 1.

extra_argv : list, optional

List with any extra arguments to pass to nosetests.

doctests : bool, optional

If True, run doctests in module. Default is False.

coverage : bool, optional

If True, report coverage of NumPy code. Default is False. (This requires the `coverage module:

raise_warnings : None, str or sequence of warnings, optional

This specifies which warnings to configure as ‘raise’ instead of being shown once during the test execution. Valid strings are:

  • “develop” : equals (Warning,)
  • “release” : equals (), don’t raise on any warnings.

The default is to use the class initialization value.

timer : bool or int, optional

Timing of individual tests with nose-timer (which needs to be installed). If True, time tests and report on all of them. If an integer (say N), report timing results for N slowest tests.

Returns:
result : object

Returns the result of running the tests as a nose.result.TextTestResult object.

Notes

Each NumPy module exposes test in its namespace to run all tests for it. For example, to run all tests for numpy.lib:

>>> np.lib.test() 

Examples

>>> result = np.lib.test() 
Running unit tests for numpy.lib
...
Ran 976 tests in 3.933s

OK

>>> result.errors 
[]
>>> result.knownfail 
[]

Dpy

class dipy.external.fsl.Dpy(fname, mode='r', compression=0)

Bases: object

Methods

read_track() read one track each time
read_tracks() read the entire tractography
read_tracksi(indices) read tracks with specific indices
write_track(track) write on track each time
write_tracks(tracks) write many tracks together
close  
version  
__init__(fname, mode='r', compression=0)

Advanced storage system for tractography based on HDF5

Parameters:
fname : str, full filename
mode : ‘r’ read

‘w’ write ‘r+’ read and write only if file already exists

compression : 0 no compression to 9 maximum compression

Examples

>>> import os
>>> from tempfile import mkstemp #temp file
>>> from dipy.io.dpy import Dpy
>>> def dpy_example():
...     fd,fname = mkstemp()
...     fname += '.dpy'#add correct extension
...     dpw = Dpy(fname,'w')
...     A=np.ones((5,3))
...     B=2*A.copy()
...     C=3*A.copy()
...     dpw.write_track(A)
...     dpw.write_track(B)
...     dpw.write_track(C)
...     dpw.close()
...     dpr = Dpy(fname,'r')
...     dpr.read_track()
...     dpr.read_track()
...     dpr.read_tracksi([0, 1, 2, 0, 0, 2])
...     dpr.close()
...     os.remove(fname) #delete file from disk
>>> dpy_example()
close()
read_track()

read one track each time

read_tracks()

read the entire tractography

read_tracksi(indices)

read tracks with specific indices

version()
write_track(track)

write on track each time

write_tracks(tracks)

write many tracks together

FSLError

class dipy.external.fsl.FSLError

Bases: Exception

Class signals error in FSL processing

Attributes:
args

Methods

with_traceback Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
__init__($self, /, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

InTemporaryDirectory

class dipy.external.fsl.InTemporaryDirectory(suffix='', prefix='tmp', dir=None)

Bases: nibabel.tmpdirs.TemporaryDirectory

Create, return, and change directory to a temporary directory

Examples

>>> import os
>>> my_cwd = os.getcwd()
>>> with InTemporaryDirectory() as tmpdir:
...     _ = open('test.txt', 'wt').write('some text')
...     assert os.path.isfile('test.txt')
...     assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
>>> os.path.exists(tmpdir)
False
>>> os.getcwd() == my_cwd
True

Methods

cleanup  
__init__(suffix='', prefix='tmp', dir=None)

Initialize self. See help(type(self)) for accurate signature.

Popen

class dipy.external.fsl.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=<object object>, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None)

Bases: object

Execute a child program in a new process.

For a complete description of the arguments see the Python documentation.

Arguments:

args: A string, or a sequence of program arguments.

bufsize: supplied as the buffering argument to the open() function when
creating the stdin/stdout/stderr pipe file objects

executable: A replacement program to execute.

stdin, stdout and stderr: These specify the executed programs’ standard
input, standard output and standard error file handles, respectively.
preexec_fn: (POSIX only) An object to be called in the child process
just before the child is executed.

close_fds: Controls closing or inheriting of file descriptors.

shell: If true, the command will be executed through the shell.

cwd: Sets the current directory before the child is executed.

env: Defines the environment variables for the new process.

universal_newlines: If true, use universal line endings for file
objects stdin, stdout and stderr.

startupinfo and creationflags (Windows only)

restore_signals (POSIX only)

start_new_session (POSIX only)

pass_fds (POSIX only)

encoding and errors: Text mode encoding and error handling to use for
file objects stdin, stdout and stderr.
Attributes:
stdin, stdout, stderr, pid, returncode

Methods

communicate([input, timeout]) Interact with process: Send data to stdin.
kill() Kill the process with SIGKILL
poll() Check if child process has terminated.
send_signal(sig) Send a signal to the process.
terminate() Terminate the process with SIGTERM
wait([timeout, endtime]) Wait for child process to terminate.
__init__(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=<object object>, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None)

Create new Popen instance.

communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

The optional “input” argument should be data to be sent to the child process (if self.universal_newlines is True, this should be a string; if it is False, “input” should be bytes), or None, if no data should be sent to the child.

communicate() returns a tuple (stdout, stderr). These will be bytes or, if self.universal_newlines was True, a string.

kill()

Kill the process with SIGKILL

poll()

Check if child process has terminated. Set and return returncode attribute.

send_signal(sig)

Send a signal to the process.

terminate()

Terminate the process with SIGTERM

wait(timeout=None, endtime=None)

Wait for child process to terminate. Returns returncode attribute.

affine_transform

dipy.external.fsl.affine_transform(input, matrix, offset=0.0, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True)

Apply an affine transformation.

Given an output image pixel index vector o, the pixel value is determined from the input image at position np.dot(matrix, o) + offset.

Parameters:
input : array_like

The input array.

matrix : ndarray

The inverse coordinate transformation matrix, mapping output coordinates to input coordinates. If ndim is the number of dimensions of input, the given matrix must have one of the following shapes:

  • (ndim, ndim): the linear transformation matrix for each output coordinate.
  • (ndim,): assume that the 2D transformation matrix is diagonal, with the diagonal specified by the given value. A more efficient algorithm is then used that exploits the separability of the problem.
  • (ndim + 1, ndim + 1): assume that the transformation is specified using homogeneous coordinates [1]. In this case, any value passed to offset is ignored.
  • (ndim, ndim + 1): as above, but the bottom row of a homogeneous transformation matrix is always [0, 0, ..., 1], and may be omitted.
offset : float or sequence, optional

The offset into the array where the transform is applied. If a float, offset is the same for each axis. If a sequence, offset should contain one value for each axis.

output_shape : tuple of ints, optional

Shape tuple.

output : array or dtype, optional

The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.

order : int, optional

The order of the spline interpolation, default is 3. The order has to be in the range 0-5.

mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the input array is extended when the filter overlaps a border. Default is ‘reflect’. Behavior for each valid value is as follows:

‘reflect’ (d c b a | a b c d | d c b a)

The input is extended by reflecting about the edge of the last pixel.

‘constant’ (k k k k | a b c d | k k k k)

The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.

‘nearest’ (a a a a | a b c d | d d d d)

The input is extended by replicating the last pixel.

‘mirror’ (d c b | a b c d | c b a)

The input is extended by reflecting about the center of the last pixel.

‘wrap’ (a b c d | a b c d | a b c d)

The input is extended by wrapping around to the opposite edge.

cval : scalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0.

prefilter : bool, optional

Determines if the input array is prefiltered with spline_filter before interpolation. The default is True, which will create a temporary float64 array of filtered values if order > 1. If setting this to False, the output will be slightly blurred if order > 1, unless the input is prefiltered, i.e. it is the result of calling spline_filter on the original input.

Returns:
affine_transform : ndarray

The transformed input.

Notes

The given matrix and offset are used to find for each point in the output the corresponding coordinates in the input by an affine transformation. The value of the input at those coordinates is determined by spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode.

Changed in version 0.18.0: Previously, the exact interpretation of the affine transformation depended on whether the matrix was supplied as a one-dimensional or two-dimensional array. If a one-dimensional array was supplied to the matrix parameter, the output pixel value at index o was determined from the input image at position matrix * (o + offset).

References

[1](1, 2) https://en.wikipedia.org/wiki/Homogeneous_coordinates

apply_warp

dipy.external.fsl.apply_warp(in_nii, affine_mat, nonlin_nii, out_nii)

bet

dipy.external.fsl.bet(in_nii, out_nii, options=' -F -f .2 -g 0')

create_displacements

dipy.external.fsl.create_displacements(fin, fmat, fnonlin, finvw, fdisp, fdispa, fref)

Create displacements using FSL’s FLIRT and FNIRT tools

Parameters:
fin : filename of initial source image
fmat : filename of .mat (flirt)
fnonlin : filename of fnirt output
finvw : filename of invwarp displacements (invwarp)
fdis : filename of fnirtfileutils
fdisa : filename of fnirtfileutils (with other parameters)
fref : filename of reference image e.g. (FMRIB58_FA_1mm.nii.gz)

dcm2nii

dipy.external.fsl.dcm2nii(dname, outdir, filt='*.dcm', options='-d n -g n -i n -o')

eddy_correct

dipy.external.fsl.eddy_correct(in_nii, out_nii, ref=0)

flirt2aff

dipy.external.fsl.flirt2aff(mat, in_img, ref_img)

Transform from in_img voxels to ref_img voxels given mat

Parameters:
mat : (4,4) array

contents (as array) of output -omat transformation file from flirt

in_img : img

image passed (as filename) to flirt as -in image

ref_img : img

image passed (as filename) to flirt as -ref image

Returns:
aff : (4,4) array

Transform from voxel coordinates in in_img to voxel coordinates in ref_img

Notes

Thanks to Mark Jenkinson and Jesper Andersson for the correct statements here, apologies for any errors we’ve added.

flirt registers an in image to a ref image. It can produce (with the -omat option) - a 4 x 4 affine matrix giving the mapping from inspace to refspace.

The rest of this note is to specify what inspace and refspace are.

In what follows, a voxtrans for an image is the 4 by 4 affine np.diag([vox_i, vox_j, vox_k, 1]) where vox_i etc are the voxel sizes for the first second and third voxel dimension. vox_i etc are always positive.

If the input image has an affine with a negative determinant, then the mapping from voxel coordinates in the input image to inspace is simply voxtrans for the input image. If the reference image has a negative determinant, the mapping from voxel space in the reference image to refspace is simply voxtrans for the reference image.

A negative determinant for the image affine is the common case, of an image with a x voxel flip. Analyze images don’t store affines and flirt assumes a negative determinant in these cases.

For positive determinant affines, flirt starts inspace and / or refspace with an x voxel flip. The mapping implied for an x voxel flip for image with shape (N_i, N_j, N_k) is:

[[-1, 0, 0, N_i - 1],
[ 0, 1, 0, 0], [ 0, 0, 1, 0], [ 0, 0, 0, 1]]

If the input image has an affine with a positive determinant, then mapping from input image voxel coordinates to inspace is np.dot(input_voxtrans, input_x_flip) - where input_x_flip is the matrix above with N_i given by the input image first axis length. Similarly the mapping from reference voxel coordinates to refspace, if the reference image has a positive determinant, is np.dot(ref_voxtrans, ref_x_flip) - where ref_x_flip is the matrix above with N_i given by the reference image first axis length.

flirt2aff_files

dipy.external.fsl.flirt2aff_files(matfile, in_fname, ref_fname)

Map from in_fname image voxels to ref_fname voxels given matfile

See flirt2aff() docstring for details.

Parameters:
matfile : str

filename of output -omat transformation file from flirt

in_fname : str

filename for image passed to flirt as -in image

ref_fname : str

filename for image passed to flirt as -ref image

Returns:
aff : (4,4) array

Transform from voxel coordinates in image for in_fname to voxel coordinates in image for ref_fname

have_flirt

dipy.external.fsl.have_flirt()

Return True if we can call flirt without error

Relies on the fact that flirt produces text on stdout when called with no arguments

mc

dipy.external.fsl.mc(input, coordinates, output=None, order=3, mode='constant', cval=0.0, prefilter=True)

Map the input array to new coordinates by interpolation.

The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order.

The shape of the output is derived from that of the coordinate array by dropping the first axis. The values of the array along the first axis are the coordinates in the input array at which the output value is found.

Parameters:
input : array_like

The input array.

coordinates : array_like

The coordinates at which input is evaluated.

output : array or dtype, optional

The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.

order : int, optional

The order of the spline interpolation, default is 3. The order has to be in the range 0-5.

mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the input array is extended when the filter overlaps a border. Default is ‘reflect’. Behavior for each valid value is as follows:

‘reflect’ (d c b a | a b c d | d c b a)

The input is extended by reflecting about the edge of the last pixel.

‘constant’ (k k k k | a b c d | k k k k)

The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.

‘nearest’ (a a a a | a b c d | d d d d)

The input is extended by replicating the last pixel.

‘mirror’ (d c b | a b c d | c b a)

The input is extended by reflecting about the center of the last pixel.

‘wrap’ (a b c d | a b c d | a b c d)

The input is extended by wrapping around to the opposite edge.

cval : scalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0.

prefilter : bool, optional

Determines if the input array is prefiltered with spline_filter before interpolation. The default is True, which will create a temporary float64 array of filtered values if order > 1. If setting this to False, the output will be slightly blurred if order > 1, unless the input is prefiltered, i.e. it is the result of calling spline_filter on the original input.

Returns:
map_coordinates : ndarray

The result of transforming the input. The shape of the output is derived from that of coordinates by dropping the first axis.

See also

spline_filter, geometric_transform, scipy.interpolate

Examples

>>> from scipy import ndimage
>>> a = np.arange(12.).reshape((4, 3))
>>> a
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.]])
>>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
array([ 2.,  7.])

Above, the interpolated value of a[0.5, 0.5] gives output[0], while a[2, 1] is output[1].

>>> inds = np.array([[0.5, 2], [0.5, 4]])
>>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
array([  2. , -33.3])
>>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
array([ 2.,  8.])
>>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
array([ True, False], dtype=bool)

pipe

dipy.external.fsl.pipe(cmd, print_sto=True, print_ste=True)

A tine pipeline system to run external tools.

For more advanced pipelining use nipype http://www.nipy.org/nipype

cmd : String
Command line to be run
print_sto : boolean
Print standard output (stdout) or not (default: True)
print_ste : boolean
Print standard error (stderr) or not (default: True)

pjoin

dipy.external.fsl.pjoin(a, *p)

Join two or more pathname components, inserting ‘/’ as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.

run_flirt_imgs

dipy.external.fsl.run_flirt_imgs(in_img, ref_img, dof=6, flags='')

Run flirt on nibabel images, returning affine

Parameters:
in_img : SpatialImage

image to register

ref_img : SpatialImage

image to register to

dof : int, optional

degrees of freedom for registration (default 6)

flags : str, optional

other flags to pass to flirt command string

Returns:
in_vox2out_vox : (4,4) ndarray

affine such that, if [i, j, k] is a coordinate in voxels in the in_img, and [p, q, r] are the equivalent voxel coordinates in the reference image, then ``[p, q, r] = np.dot(in_vox2out_vox[:3,:3]),

[i, j, k] + in_vox2out_vox[:3,3])``

warp_displacements

dipy.external.fsl.warp_displacements(ffa, flaff, fdis, fref, ffaw, order=1)

Warp an image using fsl displacements

Parameters:
ffa : filename of nifti to be warped
flaff : filename of .mat (flirt)
fdis : filename of displacements (fnirtfileutils)
fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)
ffaw : filename for the output warped image

warp_displacements_tracks

dipy.external.fsl.warp_displacements_tracks(fdpy, ffa, fmat, finv, fdis, fdisa, fref, fdpyw)

Warp tracks from native space to the FMRIB58/MNI space

We use here the fsl displacements. Have a look at create_displacements to see an example of how to use these displacements.

Parameters:
fdpy : filename of the .dpy file with the tractography
ffa : filename of nifti to be warped
fmat : filename of .mat (flirt)
fdis : filename of displacements (fnirtfileutils)
fdisa : filename of displacements (fnirtfileutils + affine)
finv : filename of invwarp displacements (invwarp)
fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)
fdpyw : filename of the warped tractography

write_bvals_bvecs

dipy.external.fsl.write_bvals_bvecs(bvals, bvecs, outpath=None, prefix='')

Write FSL FDT bvals and bvecs files

Parameters:
bvals : (N,) sequence

Vector with diffusion gradient strength (one per diffusion acquisition, N=no of acquisitions)

bvecs : (N, 3) array-like

diffusion gradient directions

outpath : None or str

path to write FDT bvals, bvecs text files None results in current working directory.

prefix : str

prefix for bvals, bvecs files in directory. Defaults to ‘’