Transform
This file contains functions and classes related to translating coordinates across various coordinate systems, such as FreeSurfer, Pycortex, scanner, and ITK-Snap.
- fmriproc.transform.ants_applytopoints()[source]
Wrapper for antsApplyTransformToPoints to warp a coordinate specified in chicken_file to a new space using trafo_file. Run
lazyfmri.utils.make_chicken_csv()and call_antsregistration from 1 space to another first.- Parameters:
chicken_file (str) – output from lazyfmri.utils.make_chicken_csv containing the coordinate that needs to be warped
output_file (str) – output csv file containing the warped point in LPS-convention! Swap the first and second dimensions to make the coordinate RAS
trafo_file (str) – ANTs-transformation file mapping between the spaces. You can also specify ‘identity’, in which case ‘call_createident’ will be called
invert (int, optional) – invert the specified transformation; this is the case where you have a coordinate in space A, and the transformation is from space A-to-B, and you’d like the coordinate in space B. This might seem counterintuitive, but this is how the transformations are applied within antsApplyTransformsToPoints.
- Returns:
filename of output csv file containing the warped point in LPS-convention, output_file
- Return type:
str
Example
>>> fn = ants_applytopoints("input.csv", "output.csv", "trafo.mat") >>> fn 'output.csv'
- fmriproc.transform.ants_applytrafo()[source]
Python wrapper for call_antsapplytransforms to apply a given transformation, and a set fixed/moving images. See call_antsapplytransforms for more information on the actual call.
- Parameters:
fixed (str|nibabel.Nifti1Image) – string to nifti reference image (.nii.gz) or nibabel.Nifti1Image that will be con-verted temporarily to a file (fixed.nii.gz) in the working directory
moving (str|nibabel.Nifti1Image) – moving (to-be-registered) image (.nii.gz) or nibabel.Nifti1Image that will be converted temporarily to a file (moving.nii.gz) in the working directory
trafo (str|list) – list or single path to transformation files in order of application
interp (str) – interpolation type: ‘lin’ (linear), ‘nn’ (NearestNeighbor), gau (Gaussian), bspl<order>, cws CosineWindowedSinc), wws (WelchWindowedSinc), hws (HammingWindowed-Sinc), lws (LanczosWindowedSinc); default = ‘nn’
invert (int|list) – list or single integer with the length of trafo-list to specify which transformations to invert or not. Default = 0 for all, meaning use as they are specified: do not invert
output (str) – output name for warped file
return_type (str) – whether you’d like the filename returned (return_type=’file’) or a nibabel.Nifti1Image (return_type=”nb”)
- Returns:
str – if return_type=”str”, then a filename is returned
nibabel.Nifti1Image – if return_type=”nb”, a nibabel.Nifti1Image is returned
Example
>>> ants_applytrafo(fixed.nii.gz, moving.nii.gz, trafo=[f1.mat,f2.mat], invert=[0,0], output="outputfile.nii.gz", return_type="file") 'outputfile.nii.gz'
- fmriproc.transform.ants_registration()[source]
python wrapper for call_antsregistration to perform registration with ANTs in the python environment. Requires the same input as call_antsregistration
- Parameters:
fixed (str) – string to nifti reference image (.nii.gz)
moving (str) – moving (to-be-registered) image (.nii.gz)
reg_type (str) – type of transformation (default = ‘rigid’)
base (output) – output basename (stuff will be appended)
- Returns:
path to transform file
- Return type:
str
Examples
>>> trafo = ants_registration(fixed="fixed.nii.gz", moving="moving.nii.gz", output="output_") >>> trafo '/path/to/output_genaff.mat'
- fmriproc.transform.ctx2tkr()[source]
Convert a coordinate from Pycortex to FreeSurfer’s TKR (surface) definition. Basically it adds the offset back (https://gallantlab.github.io/pycortex/_modules/cortex/freesurfer.html) that is added by Pycortex. With this particular function, you can apply that offset matrix to a given image, or enter a list of coordinate to which to apply the offset to. To just get the offset, specify the subject (needed for all operations), with ‘hm’ set to False (3x1 coordinate array) or True (4x4 homogenous matrix with offset in translation column).
- Parameters:
subject (str) – subject-ID corresponding to the name in the pycortex filestore directory (mandatory!! for looking up how much the image has been moved when imported from FreeSurfer to Pycortex)
img (nb.Nifti1Image, str) – nifti image or path to nifti image to which to apply the offset to
coord (list) – one or multiple coordinates to apply the offset to (e.g., left|right hemisphere) in list format (also when entering just 1 coordinate)
correct (bool) – actually apply the matrix to an input image and return the nifti image with padded affine matrix. Should be used in combination with ‘img’
hm (bool) – if True: output a homogenous (4,4) matrix with the offset in the translation column if False: just the offset values (3,)
ret (bool) – used in combination with the list of coordinates to return the corrected coordinates in a list. Artifact from when this was part of a class and included the corrected coordinates in the class object itself
pad_ones (bool) – pad the coordinates with a ‘1’ if the length does not match the (4,4) surf2orig matrix to ensure proper dot product
- Returns:
np.ndarray – offset coordinates; 4x4 or 3x1 (depending on the ‘hm’ flag) array containing the offset values
list – corrected coordinates if coord-input was a list
nb.Nifti1Image – new nifti image with corrected affine matrix
Examples
>>> offset = ctx2tkr('sub-001', hm=False) >>> corr_coordinates = ctx2tkr('sub-001', coord=[coord1,coord2], ret=True) >>> corr_nifti = ctx2trk('sub-001', img=input.nii.gz, correct=True)
- fmriproc.transform.ctx2vert()[source]
Finds the closest vertices given an RAS coordinate as defined by pycortex. It uses np.closeall with a customizable rtol-value. If this function does not return anything, increase the rtol. If the original coordinate is not on the surface, results might differ.
Procedure to view CRS in orig.mgz on the surface in Pycortex (also see fs2vert): >>> from cxutils import optimal >>> from fmriproc import transform >>> pp = optimal.CalcBestVertex(subject) >>> fs_coord = np.array([187,177,41]) >>> fs2tkr = transform.fs2tkr(‘sub-001’, coord=fs_coord) >>> tkr2ctx = transform.tkr2ctx(‘sub-001’, coord=fs2tkr) >>> vert = transform.ctx2vert(pp.surface.lh_surf_data[0], coord=tkr2ctx) >>> import cortex >>> mm = pp.surface.label_to_mask(subject=’sub-001’, lh_arr=vert, hemi=’lh’) >>> cortex.webview(mm[‘whole_roi_v’])
It runs through the surface-array and calculates the similarity between the RAS coordinates in there and the specified coordinate with a given tolerance. All elements of the coordinate should be as close to 1 as possible, showing more similarities between the given coordinate and the coordinate that has a vertex attached to it. Because of this iterative nature, the process takes a few seconds, so it’s not that your system is slow per se. Returns a list of indices where the coordinate has passed the tolerance test. You can verify this by entering the indices in FreeView on the given surface. E.g., if you used lh.fiducial, enter the vertex in that box.
- Parameters:
surf (str) – surface to extract the vertex from (e.g., lh.fiducial)
coord (numpy.ndarray|list) – numpy array or list containing the coord in Pycortex convention
rtol (float) – error margin in mm
- Returns:
vertex number corresponding to coord in surface surf
- Return type:
int
- fmriproc.transform.fs2rawavg()[source]
Inverse of
fmriproc.transform.rawavg2fs()- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
coord (numpy.ndarray|list) – containing the coordinate in FreeSurfer rawavg convention (voxels)
fs_dir (str, optional) – FreeSurfer directory (default = SUBJECTS_DIR)
- Returns:
numpy array containing the coord in rawavg.mgz voxel convention
- Return type:
numpy.ndarray
- fmriproc.transform.fs2tkr()[source]
Option [4] from https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems: “I have a CRS from a voxel in the orig.mgz volume and want to compute the RAS in surface space (tkrRAS) for this point”
- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
coord (numpy.ndarray|list) – containing the coordinate in FreeSurfer RAS convention
ref (str, optional) – reference image to use for translation to Surface RAS convention (default = orig.mgz)
fs_dir (str, optional) – FreeSurfer directory (default = SUBJECTS_DIR)
strip_lead (bool) – if True, a numpy array with shape (4,) with the last element being 1 is returned. If False, a numpy array with shape (3,) is returned
- Returns:
numpy array containing the coord in Surface RAS convention
- Return type:
numpy.ndarray
- fmriproc.transform.fs2vert(subject, coord=None, hemi='lh')[source]
ctx2vert
Warp a CRS-point from orig.mgz to Pycortex as described in
fmriproc.transform.ctx2vert().- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
coord (numpy.ndarray|list) – numpy array or list containing the coord in Pycortex convention
hemi (str) – hemisphere to extract the vertex from (should be lh or rh)
- Returns:
Dictionary collecting outputs under the following keys
vert_nr (int): vertex number corresponding to the input coordinate coord
vert_obj (dict): output from
cxutils.optimal.CalcBestVert.label_to_mask(), consisting of numpy.ndarrays representing a boolean mask of the vertex
- Return type:
dict
- fmriproc.transform.get_ras2vox(img)[source]
fetch the ras2vox matrix from an image (Rorig on the FreeSurfer wiki)
- fmriproc.transform.get_tkrreg()[source]
Implementation of tkregister2 by sending a command to the command line.
- Parameters:
subject (str) – subject-ID corresponding to the name in the pycortex filestore directory (mandatory!! for looking up how much the image has been moved when imported from FreeSurfer to Pycortex)
mov (str) – moving image
targ (str) – reference image (will default to orig.mgz if left empty)
out_file (str) – output file of transformation file
fs_dir (str) – FreeSurfer directory (default = SUBJECTS_DIR)
return_type (str) – if file, out_file is returned if arr, out_file will be read into a numpy.ndarray
- Returns:
str – if return_type==”file”, `out_file is returned
numpy.ndarray – if return_type==”arr”, `out_file is returned
- fmriproc.transform.get_vox2ras(img)[source]
fetch the vox2ras matrix from an image (Norig on the FreeSurfer wiki)
- fmriproc.transform.get_vox2ras_tkr(img)[source]
fetch the vox2ras-tkr matrix from an image (Torig/Tmov on the FreeSurfer wiki)
- fmriproc.transform.mri_surf2surf()[source]
From https://nipype.readthedocs.io/en/latest/api/generated/nipype.interfaces.freesurfer.utils.html#surfacetransform: Wrapped executable: mri_surf2surf. Transform a surface file from one subject to another via a spherical registration. Both the source and target subject must reside in your Subjects Directory, and they must have been processed with recon-all, unless you are transforming to one of the icosahedron meshes.
- Parameters:
src_file (str, optional) – Surface file with source values. Maps to a command-line argument: –sval %s, by default None
src_subj (str, optional) – Subject id for source surface. Maps to a command-line argument: –srcsubject %s, by default None
trg_subj (str, optional) – Subject id of target surface. Maps to a command-line argument: –trgsubject %s, by default None
out_file (str, optional) – Surface file to write. Maps to a command-line argument: –tval %s, by default None
hemi (str, optional) – Hemisphere to transform. Maps to a command-line argument: –hemi %s, by default None
Example
>>> from fmriproc.transform import mri_surf2surf >>> surf_file = mri_surf2surf(src_file="lh.V1_fsaverage", src_subj="fsaverage", trg_subj="sub-001", out_file="lh.V1_fsnative", hemi="lh")
- fmriproc.transform.native_to_scanner()[source]
This function returns the RAS coordinates in scanner space given a coordinate in native anatomy space. Required inputs are an anatomical image to derive the VOX-to-RAS conversion from and a voxel coordinate. Conversely, if you have a RAS coordinate, you can set the ‘inv’ flag to True to get the voxel coordinate corresponding to that RAS-coordinate. To make the output 1x4, the addone-flag is set to true. Set to false if you’d like 1x3 coordinate.
- Parameters:
anat (str) – nifti image to derive the ras2vox (and vice versa) conversion
coord (numpy.ndarray) – numpy array containing a coordinate to convert
inv (bool) – False if ‘coord’ is voxel, True if coord is RAS
addone (bool) – False if you don’t want a trailing 1, returning a 1x3 array, or True if you want a trailing 1 to make a matrix homogenous
- Returns:
(3,) or (4,) array containing the input coordinate coord in scanner convention (if coord is in voxel convention and inv==False) or voxel convention (if coord is in scanner convention and inv==True)
- Return type:
numpy.ndarray
Examples
>>> # vox2ras >>> native_to_scanner('sub-001_space-ses1_hemi-L_vert-875.nii.gz', np.array([142, 48, 222])) array([ -7.42000937, -92.96745521, -15.27866316, 1. ]) >>> # ras2vox >>> native_to_scanner('sub-001_space-ses1_hemi-L_vert-875.nii.gz', np.array([ -7.42000937, -92.96745521, -15.27866316]), inv=True) array([142, 48, 222, 1]) >>> # disable trailing '1' >>> native_to_scanner('sub-001_space-ses1_hemi-L_vert-875.nii.gz', np.array([142, 48, 222]), addone=False) array([ -7.42000937, -92.96745521, -15.27866316])
- fmriproc.transform.rawavg2fs()[source]
Option [6] from https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems: “I have a CRS from a voxel in my functional/diffusion/ASL/rawavg/etc “mov” volume and want to compute the CRS for the corresponding point in the orig.mgz”
- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
coord (numpy.ndarray|list) – containing the coordinate in FreeSurfer rawavg convention (voxels)
fs_dir (str, optional) – FreeSurfer directory (default = SUBJECTS_DIR)
- Returns:
numpy array containing the coord in orig.mgz voxel convention
- Return type:
numpy.ndarray
- fmriproc.transform.rawavg2lowres()[source]
Transform a file from rawavg in another session (e.g., lowres) via a registration matrix. Uses
fmriproc.transform.ants_applytransform()- Parameters:
fixed (str) – reference image (e.g., lowres)
moving (str) – moving image (e.g., rawavg)
matrix (str) – transformation file mapping moving to fixed
inv (bool) – if transformation file maps fixed to moving, we can invert the matrix by setting inv=True
out_file (str) – output file representing moving in fixed-space
- Returns:
filename of output file representing moving in fixed-space
- Return type:
str
- fmriproc.transform.tkr2ctx()[source]
Add the surfmove-correction that Pycortex internally applies to FreeSurfer coordinates (see
cxutils.pycortex.get_ctxsurfmove())- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
coord (numpy.ndarray|list) – numpy array or list containing the coord in Surface RAS convention
- Returns:
numpy array containing the coord in Pycortex convention
- Return type:
numpy.ndarray
- fmriproc.transform.tkr2fs()[source]
Convert a coordinate from FreeSurfer’s TKR (surface) definition to FreeSurfer’s anatomical (volume) definition. This involves the procedure described here: https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems scenario [3]: “I have a point on the surface (“Vertex RAS” in tksurfer) and want to compute the Scanner RAS in orig.mgz that corresponds to this point”.
- Parameters:
subject (str) – subject-ID corresponding to the name in the pycortex filestore directory (mandatory!! for looking up how much the image has been moved when imported from FreeSurfer to Pycortex)
img (nb.Nifti1Image, str) – nifti image or path to nifti image to which to apply the offset to
coord (list) – one or multiple coordinates to apply the offset to (e.g., left|right hemisphere) in list format (also when entering just 1 coordinate)
fs_dir (str, optional) – FreeSurfer directory (default = SUBJECTS_DIR)
pad_ones (bool) – pad the coordinates with a ‘1’ if the length does not match the (4,4) surf2orig matrix to ensure proper dot product
- Returns:
np.ndarray – (4,4) array containing the transformation from Surface RAS to Scanner RAS
list – corrected coordinates if coord-input was a list
Examples
>>> off,coord = tkr2fs('sub-001', coord=[tkr_coord1,tkr_coord2])
- fmriproc.transform.tkr2rawavg()[source]
Computes the transformation from FreeSurfer TKR space (orig.mgz) to the native space (rawavg.nii.gz). It a ssumes the FreeSurfer and native space differ, which is not necessarily the case if you already have isotropic native data. You can either specify the registration file as per the output of tkregister2 or have this function create that file (register.dat by default)
- Parameters:
subject (str) – subject-ID corresponding to the name in the pycortex filestore directory (mandatory!! for looking up how much the image has been moved when imported from FreeSurfer to Pycortex)
matrix (str) – path to ANTs-format registration file (either the .txt or .mat file, doesn’t really matter for ants_applytrafo)
reg (bool) – create the matrix mapping FreeSurfer to native instead of specifying a matrix. Only one or the other is needed.
fs_dir (str) – FreeSurfer directory (default = SUBJECTS_DIR)
inv (bool) – if the matrix file you specify with ‘matrix’ is actually mapping native to FreeSurfer, set this flag to True to invert the matrix
out_type (str) – output either the voxel (‘voxel’) or RAS (‘ras’) coordinate
- Returns:
np.ndarray – (4,4) array containing the transformation from Surface RAS to Scanner RAS
list – corrected coordinates if coord-input was a list
Example
>>> off,coord = tkr2rawavg('sub-001', matrix="register.dat", coord=[tkr_coord1,tkr_coord2])
- fmriproc.transform.vert2coord()[source]
Fetch TKR coordinate of surface vertex using mris_info.
- Parameters:
subject (str) – subject ID as used in SUBJECTS_DIR
vert (int) – surface vertex in TKR space that we want to extract information from
surf (str) – surface from which to extract vert.
- Returns:
numpy array containing the coordinate of vert in surface surf
- Return type:
numpy.ndarray