regtricks package¶
Subpackages¶
Submodules¶
regtricks.application_helpers module¶
-
regtricks.application_helpers.
aff_trans
(matrix, points)¶ Affine transform a 3D set of points
-
regtricks.application_helpers.
despatch
(data, transform, src_spc, ref_spc, cores, **kwargs)¶ Apply a transform to an array of data, mapping from source space to reference. Essentially this is an extended wrapper for Scipy map_coordinates.
Parameters: - data (array) – np.array of data (3D or 4D)
- transform (Transformation) – between source and reference space
- src_spc (ImageSpace) – in which data currently lies
- ref_spc (ImageSpace) – towards which data will be transformed
- cores (int) – number of cores to use (for 4D data)
- **kwargs – passed onto scipy.ndimage.interpolate.map_coordinates
Returns: (np.array) transformed data
-
regtricks.application_helpers.
interpolate_and_scale
(idx, data, transform, src_spc, ref_spc, **kwargs)¶ Used for partial function application to share interpolation jobs amongst workers of a mp.Pool(). Interpolate data onto the coordinates given in the tuple coords_scale, and multiply the output by the other value in coords_scale. Reshape the output to size out_size.
Parameters: - data (np.ndarray) – 3D, image data
- coords_scale (np.ndarray, np.ndarray) – (N,3) coordinates to interpolate onto (indices into data array), value by which to scale output (int or another np.ndarray for intensity correction)
- out_size (np.ndarray) – 3-vector, shape of output
- **kwargs – passed onto scipy map_coordinates
Returns: (np.ndarray), sized as out_size, interpolated output
-
regtricks.application_helpers.
src_load_helper
(src)¶
-
regtricks.application_helpers.
sum_array_blocks
(array, factor)¶ Sum sub-arrays of a larger array, each of which is sized according to factor. The array is split into smaller subarrays of size given by factor, each of which is summed, and the results returned in a new array, shrunk accordingly.
Parameters: - array – n-dimensional array of data to sum
- factor – n-length tuple, size of sub-arrays to sum over
Returns: - array of size array.shape/factor, each element containing the sum of the
corresponding subarray in the input
regtricks.fnirt_coefficients module¶
-
class
regtricks.fnirt_coefficients.
FNIRTCoefficients
(coeffs, src, ref, constrain_jac=False)¶ Bases:
object
Private encapsulation of FNIRT warp field. Only to be used from within a NonLinearTransformation
Parameters: - nibabel object or path to coefficients file (coeffs;) –
- src – Pathlike or ImageSpace, path to original source for transform
- ref – Pathlike or ImageSpace, path to original reference for transform
- constrain_jac (bool/tuple) – constrain the Jacobian of the transform (default False). If True, default limits of (0.01, 100) are used, otherwise the limits (min,max) can be passed directly.
-
get_cache_value
(ref, postmat)¶ Return cacheable values, if possible, else return None.
When can we cache? If there are only one midmat/postmat, or all of the midmats and postmats are actually the same (due to series expansion required to match the size of the premats), then we can compute and cache displacement field as it will be the same for all workers. If not, then we cannot cache and all workes must compute a new displacement field for each mid/post pair
-
get_displacements
(ref, postmat, at_idx=None)¶ Resolve displacements of transform within reference space with postmat.
Parameters: - ref (ImageSpace) – space within which to resolve displacements
- postmat (Registration/MotionCorrection) – post-warp transform
- at_idx (int) – index number within postmat to use (for MC). Default None, which corresponds to Registration postmats (not MC).
Returns: - Nx3 array of absolute positions of reference voxels in the
grid of the warp’s source space, in FSL coordinates
Return type: (array)
-
jmax
¶
-
jmin
¶
-
class
regtricks.fnirt_coefficients.
NonLinearProduct
(first, first_post, second_pre, second)¶ Bases:
object
Lazy evaluation of the combination of two non-linear warps. The two warps are stored separately as FNIRTCoefficients objects, and combined into a single field via convertwarp when resolve() is called.
Parameters: - first (FNIRTCoefficients) – first warp
- first_post (Registration/MotionCorrection) – after first warp transform
- second_pre (Registration/MotionCorrection) – before second warp transform
- second (FNIRTCoefficients) – second warp
-
get_cache_value
(ref, postmat)¶ Return cacheable values, if possible, else return None.
When can we cache? If there are only one midmat/postmat, or all of the midmats and postmats are actually the same (due to series expansion required to match the size of the premats), then we can compute and cache displacement field as it will be the same for all workers. If not, then we cannot cache and all workes must compute a new displacement field for each mid/post pair
-
get_displacements
(ref, postmat, at_idx=None)¶ Resolve displacements of transform within reference space with postmat.
Parameters: - ref (ImageSpace) – space within which to resolve displacements
- postmat (Registration/MotionCorrection) – post-warp transform
- at_idx (int) – index number within mid/postmat to use (for MC). Default is None, which corresponds to Registration mid/postmats.
Returns: - Nx3 array of absolute positions of reference voxels in the
grid of the warp’s source space, in FSL coordinates
Return type: (array)
-
jmax
¶
-
jmin
¶
-
regtricks.fnirt_coefficients.
det_jacobian
(vec_field, vox_size)¶ Calculate determinant of Jacobian for vector field, with homogenous spacing along each axis. Second order central differences are used to estimate partial derivatives.
Parameters: - vec_field (np.ndarray) – sized XYZ3, where the last dimension corresponds to displacements along the x,y,z axis respectively
- vox_size (np.ndarray) – array sized 3, step size along each spatial axis
Returns: - (np.ndarray), sized XYZ, values of the determinant of the Jacobian
matrix evaluated at each point within the array
-
regtricks.fnirt_coefficients.
get_field
(coeff1, ref, coeff2=None, mid=None, post=None, jmin=None, jmax=None)¶ Resolve coefficients into displacement field via convertwarp.
Parameters: - coeff1 (FNIRTCoefficients) – first warp
- ref (ImageSpace) – reference grid for output
- coeff2 (FNIRTCoefficients) – optional, second warp
- mid (np.ndarray) – optional, between-warp affine matrix
- post (np.ndarray) – optional, after-warp affine matrix
Returns: - np.ndarray, shape Nx3, arranged by voxel index down the rows and
XYZ in columns. Row M in the array gives the position of the reference voxel with linear index M in the source voxel grid of warp1, in FSL coordinates.
regtricks.image_space module¶
ImageSpace: image matrix, inc dimensions, voxel size, vox2world matrix and inverse, of an image. Used for resampling operations between different spaces and also for saving images into said space (eg, save PV estimates into the space of an image)
-
class
regtricks.image_space.
ImageSpace
(img)¶ Bases:
object
Voxel grid of an image, ignoring actual image data.
Parameters: img – Pathlike to image, nibabel Nifti/MGH or FSL Image object -
size
¶ array of voxel counts in each dimension
-
vox_size
¶ array of voxel size in each dimension
-
vox2world
¶ 4x4 affine to transform voxel coords -> world
-
world2vox
¶ inverse of above
-
FSL2vox
¶ Transformation from FSL scaled coordinates to voxels
-
FSL2world
¶ Transformation from FSL scaled coordinates to world
-
bbox_origin
¶ Origin of the image’s bounding box, referenced to first voxel’s corner, not center (ie, -0.5, -0.5, -0.5)
-
classmethod
create_axis_aligned
(bbox_corner, size, vox_size)¶ Create an ImageSpace from bounding box location and voxel size. Note that the voxels will be axis-aligned (no rotation).
Parameters: - bbox_corner – 3-vector, location of the furthest corner of the bounding box, at which the corner of voxel 0 0 0 will lie.
- size – 3-vector, number of voxels in each spatial dimension
- vox_size – 3-vector, size of voxel in each dimension
- Returns
- ImageSpace object
-
file_name
¶
-
fov_size
¶ FoV associated with image, in mm
-
ijk_grid
(indexing='ij')¶ Return a 4D matrix of voxel indices for this space. Default indexing is ‘ij’ (matrix convention), ‘xy’ can also be used - see np.meshgrid for more info.
Returns: - 4D array, size of this space in the first three dimensions, and
- stacked I,J,K in the fourth dimension
-
make_nifti
(data)¶ Construct nibabel Nifti for this voxel grid with data
-
classmethod
manual
(vox2world, size)¶ Manual constructor
-
n_vox
¶ Number of voxels in grid
-
resize
(start, new_size)¶ Resize the FoV of this space, maintaining axis alignment and voxel size. Can be used to both crop and expand the grid. For example, to expand the grid sized X,Y,Z by 10 voxels split equally both before and after each dimension, use (-5,5,5) and (X+5, Y+5, Z+5)
Parameters: - start – sequence of 3 ints, voxel indices by which to shift first voxel (0,0,0 is origin, negative values can be used to expand and positive values to crop)
- new_size – sequence of 3 ints, length in voxels for each dimension, starting from the new origin
Returns: new ImageSpace object
-
resize_voxels
(factor, mode='floor')¶ Resize voxels of this grid.
Parameters: - factor – either a single value, or 3 values in array-like form, by which to multiply voxel size in each dimension
- mode – “floor” or “ceil”, whether to round the grid size up or down if factor does not divide perfectly into the current size
Returns: new ImageSpace object
-
save_image
(data, path)¶ Save 3D or 4D data array at path using this image’s voxel grid
-
classmethod
save_like
(ref, data, path)¶ Save data into the space of an existing image
Parameters: - ref – path to image defining space to use
- data – ndarray (of appropriate dimensions)
- path – path to write to
-
touch
(path, dtype=<class 'float'>)¶ Save empty volume at path
-
transform
(reg)¶ Apply affine transformation to voxel grid of this space. If the reg is a np.array, it must be in world-world terms, and if it is a Registration object, the world-world transform will be used automatically.
Parameters: reg – either a 4x4 np.array (in world-world terms) or Registration Returns: a transformed copy of this image space
-
vox2FSL
¶ Transformation between voxels and FSL coordinates (scaled mm). FLIRT matrices are given in (src FSL) -> (ref FSL) terms. See: https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FLIRT/FAQ
-
vox_size
Voxel size of image
-
voxel_centres
(indexing='ij')¶ Return a 4D matrix of voxel centre coordinates for this space. Default indexing is as for ImageSpace.ijk_grid(), which is ‘ij’ matrix convention. See np.meshgrid for more info.
Returns: - 4D array, size of this space in the first three dimensions, and
- stacked I,J,K in the fourth dimension.
-
world2FSL
¶ Transformation from world coordinates to FSL scaled
-
world2vox
World coordinates to voxels
-
regtricks.multiplication module¶
Functions for combining Transformations
-
regtricks.multiplication.
cast_potential_array
(arr)¶ Helper to convert 4x4 arrays to Registrations if not already
-
regtricks.multiplication.
chain
(*args)¶ Concatenate a series of transformations (Registration, MotionCorrection, NonLinearRegistration). Note that intensity correction should be enabled when creating a NonLinearRegistration object using intensity_correct=True in the constructor prior to using chain().
Parameters: *args – Transform objects, given in the order that they need to be applied (eg, for A -> B -> C, give them in that order and they will be multiplied as C @ B @ A) Returns: Transform object representing the complete transformation
-
regtricks.multiplication.
get_highest_type
(first, second)¶ When combining two arbitrary transforms, the output will be of the same type as the “highest” of the two arguments (this is the “type promotion”). This function returns the highest type of two input objects, according to:
Registration LOWEST MotionCorrection NonLinearReigstration NonLinearMotionCorrection HIGHEST
Once the higest type is known, the actual multiplication is handled by that class’ invididual method, as below in this submodule
Parameters: - first (transformation) – order doesn’t matter
- second (transformation) – order doesn’t matter
Returns: type object of the highest class
-
regtricks.multiplication.
moco
(lhs, rhs)¶ Combine either a Registration and MoCo, or two MoCos. Return a MotionCorrection.
-
regtricks.multiplication.
nonlinearmoco
(lhs, rhs)¶ Combine either a Registration and NLMC, a MoCo and NLMC, a NLR and NLMC, or two NLMCs. Note at most 2 non-linear transforms can be combined. Return a NonLinearMotionCorrection.
-
regtricks.multiplication.
nonlinearreg
(lhs, rhs)¶ Combine either a Registration and NLR, a MoCo and NLR, or two NLRs. Note at most 2 non-linear transforms can be combined. Return a NonLinearRegistration.
-
regtricks.multiplication.
registration
(lhs, rhs)¶ Combine two Registrations, return a Registration.
regtricks.wrappers module¶
-
regtricks.wrappers.
flirt
(src, ref, **kwargs)¶ FLIRT registration wrapper. If any of the output arguments are given (out/o and omat), FLIRT will run in command line mode and save the outputs at those paths, and nothing will be returned. If none of the outputs are given, no outputs will be saved and a Registration will be returned. See fsl.wrappers.flirt.flirt for full docs.
Parameters: - src – image to register
- ref – target to register on to
- out/o – where to save output
- omat – save registration matrix
- **kwargs – as for FLIRT
Returns: Registration object
-
regtricks.wrappers.
fnirt
(src, ref, **kwargs)¶
-
regtricks.wrappers.
mcflirt
(src, refvol=-1, **kwargs)¶ MCFLIRT motion correction wrapper. If an output path is given, MCFLIRT will run in command line mode, save the output and return None. If no output path is given, a MotionCorrection and Nibabel image for the frame used as the reference will be returned. See fsl.wrappers.flirt.mcflirt for full docs.
Parameters: - src – (Pathlike) image to register
- refvol – target frame to register on to, default is N/2
- out – where to save output
- **kwargs – as for MCFLIRT
Returns: MotionCorrection object
regtricks.x5_interface module¶
X5 interface for regtricks. With thanks to Paul McCarthy; this is almost a direct copy of his fslpy.transform.x5 module
-
exception
regtricks.x5_interface.
X5Error
¶ Bases:
Exception
-
regtricks.x5_interface.
check_is_x5
(path)¶
-
regtricks.x5_interface.
load_manager
(path)¶ Load transformation objects from X5 format
-
regtricks.x5_interface.
read_affine
(group)¶ Load a single or stack of (4,4) arrays to X5 group
-
regtricks.x5_interface.
read_imagespace
(group)¶ Read ImageSpace properties (size, voxel size, vox2world) into X5 format, and return ImageSpace object
-
regtricks.x5_interface.
read_metadata
(group)¶ Read X5 format metadata
-
regtricks.x5_interface.
save_manager
(reg, path)¶ Save Registration or MotionCorrection objects in X5 format
-
regtricks.x5_interface.
write_affine
(group, matrix, inverse)¶ Write a single or stack of (4,4) arrays to X5 group
-
regtricks.x5_interface.
write_imagespace
(group, spc)¶ Write ImageSpace properties (size, voxel size, vox2world) into X5 format
-
regtricks.x5_interface.
write_metadata
(group)¶ Write X5 format metadata