def bedpostx_datacheck(input, shfile="/etc/fsl/5.0/fsl.sh"): """ Wraps bedpostx_datacheck Usage: bedpostx_datacheck input Parameters ---------- input: str (mandatory) the folder to check. shfile: str (optional, default NeuroSpin path) the path to the FSL 'fsl.sh' configuration file. Returns ------- is_valid: bool True if all the data are present in the input directory """ # Call bedpostx_datacheck fslprocess = FSLWrapper("bedpostx_datacheck", shfile=shfile) fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:]), fslprocess.stderr) # Parse outputs is_valid = (fslprocess.stderr == "" and "does not exist" not in fslprocess.stdout) return is_valid
def fslreorient2std(input, output, shfile="/etc/fsl/5.0/fsl.sh"): """ FSL tool for reorienting the image to match the approximate orientation of the standard template images (MNI152). It only applies 0, 90, 180 or 270 degree rotations. It is not a registration tool. It requires NIfTI images with valid orientation information in them (seen by valid labels in FSLView). This tool assumes the labels are correct - if not, fix that before using this. If the output name is not specified the equivalent transformation matrix is written to the standard output Usage: fslreorient2std <input_image> [output_image] Parameters ---------- input: str (mandatory) the image to reorient. output: str (mandatory) the reoriented image. shfile: str (optional, default local path) the path to the FSL 'fsl.sh' configuration file. """ # Call fslreorient2std fslprocess = FSLWrapper("fslreorient2std", shfile=shfile) fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:]), fslprocess.stderr)
def apply_mask(inputfile, outputfile, maskfile, shfile="/etc/fsl/5.0/fsl.sh"): """ Apply a mask to an image. Parameters ---------- inputfile: str (mandatory) the image to mask. outputfile: str (mandatory) the computed masked image. maskfile: str (mandatory) the mask image. shfile: str (optional, default local path) the path to the FSL 'fsl.sh' configuration file. """ # Call fslmaths cmd = ["fslmaths", inputfile, "-mas", maskfile, outputfile] fslprocess = FSLWrapper("fslmaths", shfile=shfile) fslprocess(cmd) if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:]), fslprocess.stderr)
def bedpostx_datacheck(input): """ Wraps bedpostx_datacheck Usage: bedpostx_datacheck input Returns ------- is_valid: bool True if all the data are present in the input directory """ # Call bedpostx_datacheck fslprocess = FSLWrapper("bedpostx_datacheck") fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:])) # Parse outputs is_valid = (fslprocess.stderr == "" and "does not exist" not in fslprocess.stdout) return is_valid
def flirt(in_file, ref_file, omat=None, out=None, init=None, cost="corratio", usesqform=None, displayinit=None, anglerep="euler", bins=256, interp="trilinear", dof=12, applyxfm=None, verbose=0): """ Wraps command flirt. Usage: flirt [options] -in <inputvol> -ref <refvol> -out <outputvol> flirt [options] -in <inputvol> -ref <refvol> -omat <outputmatrix> flirt [options] -in <inputvol> -ref <refvol> -applyxfm -init <matrix> -out <outputvol> Available options are: -in <inputvol> (no default) -ref <refvol> (no default) -init <matrix-filname> (input 4x4 affine matrix) -omat <matrix-filename> (output in 4x4 ascii format) -out, -o <outputvol> (default is none) -datatype {char,short,int,float,double} (force output data type) -cost {mutualinfo,corratio,normcorr,normmi,leastsq,labeldiff,bbr} (default is corratio) -searchcost {mutualinfo,corratio,normcorr,normmi,leastsq,labeldiff,bbr} (default is corratio) -usesqform (initialise using appropriate sform or qform) -displayinit (display initial matrix) -anglerep {quaternion,euler} (default is euler) -interp {trilinear,nearestneighbour,sinc,spline} (final interpolation: def - trilinear) -sincwidth <full-width in voxels> (default is 7) -sincwindow {rectangular,hanning,blackman} -bins <number of histogram bins> (default is 256) -dof <number of transform dofs> (default is 12) -noresample (do not change input sampling) -forcescaling (force rescaling even for low-res images) -minsampling <vox_dim> (set minimum voxel dimension for sampling (in mm)) -applyxfm (applies transform (no optimisation) - requires -init) -applyisoxfm <scale> (as applyxfm but forces isotropic resampling) -paddingsize <number of voxels> (for applyxfm: interpolates outside image by size) -searchrx <min_angle> <max_angle> (angles in degrees: default is -90 90) -searchry <min_angle> <max_angle> (angles in degrees: default is -90 90) -searchrz <min_angle> <max_angle> (angles in degrees: default is -90 90) -nosearch (sets all angular search ranges to 0 0) -coarsesearch <delta_angle> (angle in degrees: default is 60) -finesearch <delta_angle> (angle in degrees: default is 18) -schedule <schedule-file> (replaces default schedule) -refweight <volume> (use weights for reference volume) -inweight <volume> (use weights for input volume) -wmseg <volume> (white matter segmentation volume needed by BBR cost function) -wmcoords <text matrix> (white matter boundary coordinates for BBR cost function) -wmnorms <text matrix> (white matter boundary normals for BBR cost function) -fieldmap <volume> (fieldmap image in rads/s - must be already registered to the reference image) -fieldmapmask <volume> (mask for fieldmap image) -pedir <index> (phase encode direction of EPI - 1/2/3=x/y/z & -1/-2/-3=-x/-y/-z) -echospacing <value> (value of EPI echo spacing - units of seconds) -bbrtype <value> (type of bbr cost function: signed [default], global_abs, local_abs) -bbrslope <value> (value of bbr slope) -setbackground <value> (use specified background value for points outside FOV) -noclamp (do not use intensity clamping) -noresampblur (do not use blurring on downsampling) -2D (use 2D rigid body mode - ignores dof) -verbose <num> (0 is least and default) -v (same as -verbose 1) -i (pauses at each stage: default is off) -version (prints version number) -help """ # Set default parameters dirname = os.path.dirname(in_file) basename = os.path.basename(in_file).split(".")[0] if out is None: out = os.path.join(dirname, "flirt_out_{0}.nii.gz".format(basename)) if omat is None: omat = os.path.join(dirname, "flirt_omat_{0}".format(basename)) # Call flirt fslprocess = FSLWrapper("flirt") fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:])) return out, omat
def bet2(input, output, o=None, m=None, s=None, n=None, f=0.5, g=0, r=None, c=None, t=None, e=None, shfile="/etc/fsl/5.0/fsl.sh"): """ Wraps command bet2. The basic usage is: bet2 <input> <output> [options] Main bet2 options: -o generate brain surface outline overlaid onto original image -m generate binary brain mask -s generate rough skull image (not as clean as what betsurf generates) -n don't generate the default brain image output -f <f> fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates -g <g> vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top -r <r> head radius (mm not voxels); initial surface sphere is set to half of this -c < x y z> centre-of-gravity (voxels not mm) of initial mesh surface. -t apply thresholding to segmented brain image and mask -e generates brain surface as mesh in .vtk format. Returns ------- output: str the extracted brain volume. mask_file: str the binary mask of the extracted brain volume. mesh_file: str the brain surface as a vtk mesh. outline_file: str the brain surface outline overlaid onto original image. inskull_mask_file, inskull_mesh_file, outskull_mask_file, outskull_mesh_file, outskin_mask_file, outskin_mesh_file, skull_mask_file: str rough skull image. shfile: str (optional, default local path) the path to the FSL 'fsl.sh' configuration file. """ # Call bet2 fslprocess = FSLWrapper("bet2", shfile=shfile) fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:]), fslprocess.stderr) # Format outputs image_ext = fslprocess.output_ext[fslprocess.environment["FSLOUTPUTTYPE"]] mask_file = None if m is not None: mask_file = output + "_mask" + image_ext mesh_file = None if e is not None: mesh_file = output + "_mesh.vtk" outline_file = None if o is not None: outline_file = output + "_outline" + image_ext inskull_mask_file = None inskull_mesh_file = None outskull_mask_file = None outskull_mesh_file = None outskin_mask_file = None outskin_mesh_file = None skull_mask_file = None if s is not None: inskull_mask_file = output + "_inskull_mask" + image_ext inskull_mesh_file = output + "_inskull_mesh" + image_ext outskull_mask_file = output + "_outskull_mask" + image_ext outskull_mesh_file = output + "_outskull_mesh" + image_ext outskin_mask_file = output + "_outskin_mask" + image_ext outskin_mesh_file = output + "_outskin_mesh" + image_ext skull_mask_file = output + "_skull_mask" + image_ext if n is not None: output = None else: output += image_ext return (output, mask_file, mesh_file, outline_file, inskull_mask_file, inskull_mesh_file, outskull_mask_file, outskull_mesh_file, outskin_mask_file, outskin_mesh_file, skull_mask_file)
def dtifit(k, r, b, m, o, w=None): """ Wraps command dtifit. Usage: dtifit -k <filename> dtifit --verbose Compulsory arguments (You MUST set one or more of): -k,--data dti data file -o,--out Output basename -m,--mask Bet binary mask file -r,--bvecs b vectors file -b,--bvals b values file Optional arguments (You may optionally specify one or more of): -V,--verbose switch on diagnostic messages -h,--help display this message --cni Input confound regressors --sse Output sum of squared errors -w,--wls Fit the tensor with weighted least squares --littlebit Only process small area of brain --save_tensor Save the elements of the tensor -z,--zmin min z -Z,--zmax max z -y,--ymin min y -Y,--ymax max y -x,--xmin min x -X,--xmax max x Returns ------- v1_file: str 1st eigenvector v2_file: str 2nd eigenvector v3_file: str 3rd eigenvector l1_file: str 1st eigenvalue l2_file: str 2nd eigenvalue l3_file: str 3rd eigenvalue md_file: str mean diffusivity fa_file: str fractional anisotropy s0_file: str raw T2 signal with no diffusion weighting tensor_file: str the full second order coefficients m0_file: str the mode of the anisotropy """ # Check that the output directory exists if not os.path.isdir(o): os.makedirs(o) o = os.path.join(o, "dtifit") # Call bedpostx fslprocess = FSLWrapper("dtifit --save_tensor") fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:])) # Build outputs image_ext = fslprocess.output_ext[fslprocess.environment["FSLOUTPUTTYPE"]] v1_file = o + "_V1" + image_ext v2_file = o + "_V2" + image_ext v3_file = o + "_V3" + image_ext l1_file = o + "_L1" + image_ext l2_file = o + "_L2" + image_ext l3_file = o + "_L3" + image_ext md_file = o + "_MD" + image_ext fa_file = o + "_FA" + image_ext s0_file = o + "_S0" + image_ext tensor_file = o + "_tensor" + image_ext m0_file = o + "_M0" + image_ext return (v1_file, v2_file, v3_file, l1_file, l2_file, l3_file, md_file, fa_file, s0_file, tensor_file, m0_file)
def bedpostx(input, n=2, w=1, b=1000, j=1250, s=25, model=1, g=None, c=None): """ Wraps command bedpostx. Usage: bedpostx <input> [options] expects to find bvals and bvecs in subject directory expects to find data and nodif_brain_mask in subject directory expects to find grad_dev in subject directory, if -g is set options (old syntax) -n (number of fibres per voxel, default 2) -w (ARD weight, more weight means less secondary fibres per voxel, default 1) -b (burnin period, default 1000) -j (number of jumps, default 1250) -s (sample every, default 25) -model (1 for monoexponential, 2 for multiexponential, default 1) -g (consider gradient nonlinearities, default off) -c do not use CUDA capable hardware/queue (if found) ALTERNATIVELY: you can pass on xfibres options onto directly bedpostx For example: bedpostx <subject directory> --noard --cnonlinear Type 'xfibres --help' for a list of available options Default options will be bedpostx default (see above), and not xfibres default. Returns ------- outdir: str The bedpostx output directory merged_th<i>samples - 4D volume Samples from the distribution on theta merged_ph<i>samples Samples from the distribution on phi: theta and phi together represent the principal diffusion direction in spherical polar co-ordinates merged_f<i>samples - 4D volume Samples from the distribution on anisotropic volume fraction. mean_th<i>samples - 3D Volume Mean of distribution on theta mean_ph<i>samples - 3D Volume Mean of distribution on phi mean_f<i>samples - 3D Volume Mean of distribution on f anisotropy. Note that in each voxel, fibres are ordered according to a decreasing mean f-value dyads<i> Mean of PDD distribution in vector form. Note that this file can be loaded into fslview for easy viewing of diffusion directions """ # Call bedpostx fslprocess = FSLWrapper("bedpostx") fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:])) # Format outputs outdir = input + ".bedpostX" merged_th = glob.glob(os.path.join(outdir, "merged_th*")) merged_ph = glob.glob(os.path.join(outdir, "merged_ph*")) merged_f = glob.glob(os.path.join(outdir, "merged_f*")) mean_th = glob.glob(os.path.join(outdir, "mean_th*")) mean_ph = glob.glob(os.path.join(outdir, "mean_ph*")) mean_f = glob.glob(os.path.join(outdir, "mean_f*")) dyads = glob.glob(os.path.join(outdir, "dyads*")) return (outdir, merged_th, merged_ph, merged_f, mean_th, mean_ph, mean_f, dyads)
def probtrackx2(samples, seed, mask, dir, out="fdt_paths", nsamples=5000, nsteps=2000, cthr=0.2, loopcheck=None, onewaycondition=None, usef=None, simple=None, seedref=None, steplength=0.5, fibthresh=0.01, distthresh=0.0, sampvox=0.0, network=None): """ Wraps command probtrackx2. Single voxel ------------ probtrackx2(simple=True, seedref="/.../fsl.bedpostX/nodif_brain_mask", out="fdt_paths", seed="$PATH/tracto/fdt_coordinates.txt", loopcheck=True, onewaycondition=True, samples="/.../fsl.bedpostX/merged" mask="/.../fsl.bedpostX/nodif_brain_mask" dir="$PATH") Single mask ----------- probtrackx2(seed="/.../lh-precentral.nii.gz", loopcheck=True, onewaycondition=True, samples="/.../fsl.bedpostX/merged", mask="/.../fsl.bedpostX/nodif_brain_mask", dir="$PATH") Multiple masks -------------- probtrackx2(network=True, seed="$PATH/masks.txt", loopcheck=True, onewaycondition=True, samples="/.../fsl.bedpostX/merged", mask="/.../fsl.bedpostX/nodif_brain_mask", dir="$PATH") Usage: probtrackx2 -s <basename> -m <maskname> -x <seedfile> -o <output> --targetmasks=<textfile> probtrackx2 --help Compulsory arguments (You MUST set one or more of): -s,--samples Basename for samples files - e.g. 'merged' -m,--mask Bet binary mask file in diffusion space -x,--seed Seed volume or list (ascii text file) of volumes and/or surfaces Optional arguments (You may optionally specify one or more of): -o,--out Output file (default='fdt_paths') --dir Directory to put the final volumes in - code makes this directory - default='logdir' --forcedir Use the actual directory name given - i.e. don't add + to make a new directory --simple Track from a list of voxels (seed must be a ASCII list of coordinates) --network Activate network mode - only keep paths going through at least one of the other seed masks --opd Output path distribution --pd Correct path distribution for the length of the pathways --fopd Other mask for binning tract distribution --os2t Outputs seeds to target images. One per voxel in the seed. There can be quite a lot of these files. --s2tastext Output seed-to-target counts as a text file (default in simple mode) --targetmasks File containing a list of target masks - for seeds_to_targets classification --waypoints Waypoint mask or ascii list of waypoint masks - only keep paths going through ALL the masks --waycond Waypoint condition. Either 'AND' (default) or 'OR' --wayorder Reject streamlines that do not hit waypoints in given order. Only valid if waycond=AND --onewaycondition Apply waypoint conditions to each half tract separately --avoid Reject pathways passing through locations given by this mask --stop Stop tracking at locations given by this mask file --omatrix1 Output matrix1 - SeedToSeed Connectivity --distthresh1 Discards samples (in matrix1) shorter than this threshold (in mm - default=0) --omatrix2 Output matrix2 - SeedToLowResMask --target2 Low resolution binary brain mask for storing connectivity distribution in matrix2 mode --omatrix3 Output matrix3 (NxN connectivity matrix) --target3 Mask used for NxN connectivity matrix (or Nxn if lrtarget3 is set) --lrtarget3 Column-space mask used for Nxn connectivity matrix --distthresh3 Discards samples (in matrix3) shorter than this threshold (in mm - default=0) --omatrix4 Output matrix4 - DtiMaskToSeed (special Oxford Sparse Format) --colmask4 Mask for columns of matrix4 (default=seed mask) --target4 Brain mask in DTI space --xfm Transform taking seed space to DTI space (either FLIRT matrix or FNIRT warpfield) - default is identity --invxfm Transform taking DTI space to seed space (compulsory when using a warpfield for seeds_to_dti) --seedref Reference vol to define seed space in simple mode - diffusion space assumed if absent --meshspace Mesh reference space - either 'caret' (default) or 'freesurfer' or 'first' or 'vox' -P,--nsamples Number of samples - default=5000 -S,--nsteps Number of steps per sample - default=2000 --steplength Steplength in mm - default=0.5 --distthresh Discards samples shorter than this threshold (in mm - default=0) -c,--cthr Curvature threshold - default=0.2 --fibthresh Volume fraction before subsidary fibre orientations are considered - default=0.01 -l,--loopcheck Perform loopchecks on paths - slower, but allows lower curvature threshold -f,--usef Use anisotropy to constrain tracking --modeuler Use modified euler streamlining --sampvox Sample random points within x mm sphere seed voxels (e.g. --sampvox=5). Default=0 --randfib Default 0. Set to 1 to randomly sample initial fibres (with f > fibthresh). Set to 2 to sample in proportion fibres (with f>fibthresh) to f. Set to 3 to sample ALL populations at random (even if f<fibthresh) --fibst Force a starting fibre for tracking - default=1, i.e. first fibre orientation. Only works if randfib==0 --rseed Random seed Returns ------- proba_files: list of str a list of files containing probabilistic fiber maps. network_file: str a voxel-by-target connection matrix. """ # Call bedpostx fslprocess = FSLWrapper("probtrackx2 --opd --forcedir", optional="ALL") fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:])) # Get the outputs proba_files = glob.glob(os.path.join(dir, out + "*")) network_file = None if network is not None: network_file = os.path.join(dir, "fdt_network_matrix") return proba_files, network_file
def bedpostx(input, n=3, w=1, b=1000, j=1250, s=25, model=2, g=None, c=None, rician=None, shfile="/etc/fsl/5.0/fsl.sh", cpus=""): """ Wraps command bedpostx. Usage: bedpostx <input> [options] expects to find bvals and bvecs in input expects to find data and nodif_brain_mask in input expects to find grad_dev in input, if -g is set options (old syntax) -n (number of fibers per voxel, default 3) -w (ARD weight, more weight means less secondary fibers per voxel, default 1) -b (burnin period: number of iterations before starting the sampling. These might be increased if the data are noisy, and the MCMC needs more iterations to converge, default 1000) -j (number of jumps to be made by MCMC, default 1250) -s (sample every, default 25) -model (deconvolution model. 1: single-shell, with sticks, 2: multi-shell, with sticks with a range of diffusivities (default), 3: multi-shell, with zeppelins) -g (consider gradient nonlinearities, instructs bedpostx to use the grad_dev.nii.gz file from the data folder and produce voxel-specific bvals and bvecs, default off) --rician (use a Rician noise modeling to replace the default Gaussian noise assumption) -c do not use CUDA capable hardware/queue (if found) ALTERNATIVELY: you can pass on xfibres options onto directly bedpostx For example: bedpostx <subject directory> --noard --cnonlinear Type 'xfibres --help' for a list of available options Default options will be bedpostx default (see above), and not xfibres default. Parameters ---------- shfile: str (optional, default NeuroSpin path) the path to the FSL 'fsl.sh' configuration file. Returns ------- outdir: str The bedpostx output directory merged_th<i>samples - 4D volume Samples from the distribution on theta merged_ph<i>samples - 4D volume Samples from the distribution on phi: theta and phi together represent the principal diffusion direction in spherical polar co-ordinates merged_f<i>samples - 4D volume Samples from the distribution on anisotropic volume fraction. mean_th<i>samples - 3D Volume Mean of distribution on theta mean_ph<i>samples - 3D Volume Mean of distribution on phi mean_f<i>samples - 3D Volume Mean of distribution on f anisotropy. Note that in each voxel, fibers are ordered according to a decreasing mean f-value mean_dsamples - 3D Volume Mean of distribution on diffusivity d mean_S0samples - 3D Volume Mean of distribution on T2w baseline signal intensity S0 dyads<i> Mean of PDD distribution in vector form. Note that this file can be loaded into fslview for easy viewing of diffusion directions dyads_dispersion - 3D Volume Uncertainty on the estimated fiber orientation. Characterizes how wide the orientation distribution is around the respective PDD. nodif_brain_mask binary mask created from nodif_brain - copied from input directory bvecs contain a 3x1 vector for each gradient, indicating the gradient direction - copied from input directory bvals contain a scalar value for each applied gradient, corresponding to the respective bvalue - copied from input directory """ # Call bedpostx fslprocess = FSLWrapper("bedpostx", shfile=shfile, cpus=cpus) fslprocess() if fslprocess.exitcode != 0: raise FSLRuntimeError(fslprocess.cmd[0], " ".join(fslprocess.cmd[1:]), fslprocess.stderr) # Format outputs outdir = input + ".bedpostX" merged_th = glob.glob(os.path.join(outdir, "merged_th*")) merged_ph = glob.glob(os.path.join(outdir, "merged_ph*")) merged_f = glob.glob(os.path.join(outdir, "merged_f*")) mean_th = glob.glob(os.path.join(outdir, "mean_th*")) mean_ph = glob.glob(os.path.join(outdir, "mean_ph*")) mean_f = glob.glob(os.path.join(outdir, "mean_f*")) mean_d = os.path.join(outdir, "mean_d*") mean_S0 = os.path.join(outdir, "mean_S0*") dyads = glob.glob(os.path.join(outdir, "dyads*")) return (outdir, merged_th, merged_ph, merged_f, mean_th, mean_ph, mean_f, mean_d, mean_S0, dyads)