def create_mrtrix_dti_pipeline(name="dtiproc", tractography_type='probabilistic'): """Creates a pipeline that does the same diffusion processing as in the :doc:`../../users/examples/dmri_mrtrix_dti` example script. Given a diffusion-weighted image, b-values, and b-vectors, the workflow will return the tractography computed from spherical deconvolution and probabilistic streamline tractography Example ------- >>> dti = create_mrtrix_dti_pipeline("mrtrix_dti") >>> dti.inputs.inputnode.dwi = 'data.nii' >>> dti.inputs.inputnode.bvals = 'bvals' >>> dti.inputs.inputnode.bvecs = 'bvecs' >>> dti.run() # doctest: +SKIP Inputs:: inputnode.dwi inputnode.bvecs inputnode.bvals Outputs:: outputnode.fa outputnode.tdi outputnode.tracts_tck outputnode.tracts_trk outputnode.csdeconv """ inputnode = pe.Node( interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]), name="inputnode") bet = pe.Node(interface=fsl.BET(), name="bet") bet.inputs.mask = True fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') fsl2mrtrix.inputs.invert_y = True dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor') tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(), name='tensor2vector') tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0') threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA') threshold_FA.inputs.absolute_threshold_value = 0.7 threshold_wmmask = pe.Node(interface=mrtrix.Threshold(), name='threshold_wmmask') threshold_wmmask.inputs.absolute_threshold_value = 0.4 MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3D') MRconvert = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert') MRconvert.inputs.extract_at_axis = 3 MRconvert.inputs.extract_at_coordinate = [0] csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') if tractography_type == 'probabilistic': CSDstreamtrack = pe.Node( interface=mrtrix. ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='CSDstreamtrack') else: CSDstreamtrack = pe.Node( interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(), name='CSDstreamtrack') CSDstreamtrack.inputs.desired_number_of_tracks = 15000 tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob') tracks2prob.inputs.colour = True tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') workflow = pe.Workflow(name=name) workflow.base_output_dir = name workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) workflow.connect([(inputnode, dwi2tensor, [("dwi", "in_file")])]) workflow.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", "encoding_file")])]) workflow.connect([ (dwi2tensor, tensor2vector, [['tensor', 'in_file']]), (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), ]) workflow.connect([(inputnode, MRconvert, [("dwi", "in_file")])]) workflow.connect([(MRconvert, threshold_b0, [("converted", "in_file")])]) workflow.connect([(threshold_b0, median3d, [("out_file", "in_file")])]) workflow.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file") ])]) workflow.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) workflow.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])]) workflow.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])]) workflow.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) workflow.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) workflow.connect([(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) workflow.connect([(inputnode, bet, [("dwi", "in_file")])]) workflow.connect([(inputnode, gen_WM_mask, [("dwi", "in_file")])]) workflow.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])]) workflow.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", "encoding_file")])]) workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])]) workflow.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])]) workflow.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", "mask_image")])]) workflow.connect([(estimateresponse, csdeconv, [("response", "response_file")])]) workflow.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])]) workflow.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", "in_file")])]) workflow.connect([(threshold_wmmask, CSDstreamtrack, [("out_file", "seed_file")])]) workflow.connect([(csdeconv, CSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) if tractography_type == 'probabilistic': workflow.connect([(CSDstreamtrack, tracks2prob, [("tracked", "in_file") ])]) workflow.connect([(inputnode, tracks2prob, [("dwi", "template_file")]) ]) workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])]) workflow.connect([(inputnode, tck2trk, [("dwi", "image_file")])]) output_fields = ["fa", "tracts_trk", "csdeconv", "tracts_tck"] if tractography_type == 'probabilistic': output_fields.append("tdi") outputnode = pe.Node( interface=util.IdentityInterface(fields=output_fields), name="outputnode") workflow.connect([ (CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]), (csdeconv, outputnode, [("spherical_harmonics_image", "csdeconv")]), (tensor2fa, outputnode, [("FA", "fa")]), (tck2trk, outputnode, [("out_file", "tracts_trk")]) ]) if tractography_type == 'probabilistic': workflow.connect([(tracks2prob, outputnode, [("tract_image", "tdi")])]) return workflow
estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),name='estimateresponse') estimateresponse.inputs.maximum_harmonic_order = 6 csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),name='csdeconv') csdeconv.inputs.maximum_harmonic_order = 6 """ Finally, we track probabilistically using the orientation distribution functions obtained earlier. The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format. """ probCSDstreamtrack = pe.Node(interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(),name='probCSDstreamtrack') probCSDstreamtrack.inputs.inputmodel = 'SD_PROB' probCSDstreamtrack.inputs.desired_number_of_tracks = 1000000 # more (~5m) is better, but is too much for trackvis: see http://www.nitrc.org/pipermail/mrtrix-discussion/2012-December/000604.html #probCSDstreamtrack.inputs.desired_number_of_tracks = 10000 # minimum in Farquharson et al. 2014 (but ROI to ROI, not whole brain) #probCSDstreamtrack.inputs.minimum_radius_of_curvature = 0.27 # r=0.27 => angle=43.5° (Judith wants ~45°); see http://www.nitrc.org/pipermail/mrtrix-discussion/2011-June/000230.html tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(),name='tracks2prob') tracks2prob.inputs.colour = True tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(),name='tck2trk') tck2trk.inputs.out_filename = 'mrtrix_probCSD.trk' #Node: Datasink - Create a datasink node to store important outputs datasink = pe.Node(interface=nio.DataSink(), name="mrtrix_probCSD") datasink.inputs.base_directory = out_dir # #### Connect and run the workflow """ Creating the workflow ---------------------
def inclusion_filtering_mrtrix3(track_file, roi_file, fa_file, md_file, roi_names=None, registration_image_file=None, registration_matrix_file=None, prefix=None, tdi_threshold=10): import os import os.path as op import numpy as np import glob from coma.workflows.dmn import get_rois, save_heatmap from coma.interfaces.dti import write_trackvis_scene import nipype.pipeline.engine as pe import nipype.interfaces.fsl as fsl import nipype.interfaces.mrtrix as mrtrix import nipype.interfaces.diffusion_toolkit as dtk from nipype.utils.filemanip import split_filename import subprocess import shutil rois = get_rois(roi_file) fa_out_matrix = op.abspath("%s_FA.csv" % prefix) md_out_matrix = op.abspath("%s_MD.csv" % prefix) invLen_invVol_out_matrix = op.abspath("%s_invLen_invVol.csv" % prefix) subprocess.call([ "tck2connectome", "-assignment_voxel_lookup", "-zero_diagonal", "-metric", "mean_scalar", "-image", fa_file, track_file, roi_file, fa_out_matrix ]) subprocess.call([ "tck2connectome", "-assignment_voxel_lookup", "-zero_diagonal", "-metric", "mean_scalar", "-image", md_file, track_file, roi_file, md_out_matrix ]) subprocess.call([ "tck2connectome", "-assignment_voxel_lookup", "-zero_diagonal", "-metric", "invlength_invnodevolume", track_file, roi_file, invLen_invVol_out_matrix ]) subprocess.call([ "tcknodeextract", "-assignment_voxel_lookup", track_file, roi_file, prefix + "_" ]) fa_matrix_thr = np.zeros((len(rois), len(rois))) md_matrix_thr = np.zeros((len(rois), len(rois))) tdi_matrix = np.zeros((len(rois), len(rois))) track_volume_matrix = np.zeros((len(rois), len(rois))) out_files = [] track_files = [] for idx_i, roi_i in enumerate(rois): for idx_j, roi_j in enumerate(rois): if idx_j >= idx_i: filtered_tracks = glob.glob( op.abspath(prefix + "_%s-%s.tck" % (roi_i, roi_j)))[0] print(filtered_tracks) if roi_names is None: roi_i = str(int(roi_i)) roi_j = str(int(roi_j)) idpair = "%s_%s" % (roi_i, roi_j) idpair = idpair.replace(".", "-") else: roi_name_i = roi_names[idx_i] roi_name_j = roi_names[idx_j] idpair = "%s_%s" % (roi_name_i, roi_name_j) tracks2tdi = pe.Node(interface=mrtrix.Tracks2Prob(), name='tdi_%s' % idpair) tracks2tdi.inputs.template_file = fa_file tracks2tdi.inputs.in_file = filtered_tracks out_tdi_name = op.abspath("%s_TDI_%s.nii.gz" % (prefix, idpair)) tracks2tdi.inputs.out_filename = out_tdi_name tracks2tdi.inputs.output_datatype = "Int16" binarize_tdi = pe.Node(interface=fsl.ImageMaths(), name='binarize_tdi_%s' % idpair) binarize_tdi.inputs.op_string = "-thr %d -bin" % tdi_threshold out_tdi_vol_name = op.abspath("%s_TDI_bin_%d_%s.nii.gz" % (prefix, tdi_threshold, idpair)) binarize_tdi.inputs.out_file = out_tdi_vol_name mask_fa = pe.Node(interface=fsl.MultiImageMaths(), name='mask_fa_%s' % idpair) mask_fa.inputs.op_string = "-mul %s" mask_fa.inputs.operand_files = [fa_file] out_fa_name = op.abspath("%s_FA_%s.nii.gz" % (prefix, idpair)) mask_fa.inputs.out_file = out_fa_name mask_md = mask_fa.clone(name='mask_md_%s' % idpair) mask_md.inputs.operand_files = [md_file] out_md_name = op.abspath("%s_MD_%s.nii.gz" % (prefix, idpair)) mask_md.inputs.out_file = out_md_name mean_fa = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='mean_fa_%s' % idpair) mean_md = pe.Node(interface=fsl.ImageStats(op_string='-M'), name='mean_md_%s' % idpair) mean_tdi = pe.Node(interface=fsl.ImageStats( op_string='-l %d -M' % tdi_threshold), name='mean_tdi_%s' % idpair) track_volume = pe.Node(interface=fsl.ImageStats( op_string='-l %d -V' % tdi_threshold), name='track_volume_%s' % idpair) tck2trk = mrtrix.MRTrix2TrackVis() tck2trk.inputs.image_file = fa_file tck2trk.inputs.in_file = filtered_tracks trk_file = op.abspath("%s_%s.trk" % (prefix, idpair)) tck2trk.inputs.out_filename = trk_file tck2trk.base_dir = op.abspath(".") if registration_image_file is not None and registration_matrix_file is not None: tck2trk.inputs.registration_image_file = registration_image_file tck2trk.inputs.matrix_file = registration_matrix_file workflow = pe.Workflow(name=idpair) workflow.base_dir = op.abspath(idpair) workflow.connect([(tracks2tdi, binarize_tdi, [("tract_image", "in_file")])]) workflow.connect([(binarize_tdi, mask_fa, [("out_file", "in_file")])]) workflow.connect([(binarize_tdi, mask_md, [("out_file", "in_file")])]) workflow.connect([(mask_fa, mean_fa, [("out_file", "in_file")]) ]) workflow.connect([(mask_md, mean_md, [("out_file", "in_file")]) ]) workflow.connect([(tracks2tdi, mean_tdi, [("tract_image", "in_file")])]) workflow.connect([(tracks2tdi, track_volume, [("tract_image", "in_file")])]) workflow.config['execution'] = { 'remove_unnecessary_outputs': 'false', 'hash_method': 'timestamp' } result = workflow.run() tck2trk.run() fa_masked = glob.glob(out_fa_name)[0] md_masked = glob.glob(out_md_name)[0] if roi_names is not None: tracks = op.abspath(prefix + "_%s-%s.tck" % (roi_name_i, roi_name_j)) shutil.move(filtered_tracks, tracks) else: tracks = filtered_tracks tdi = glob.glob(out_tdi_vol_name)[0] nodes = result.nodes() node_names = [s.name for s in nodes] mean_fa_node = [ nodes[idx] for idx, s in enumerate(node_names) if "mean_fa" in s ][0] mean_fa = mean_fa_node.result.outputs.out_stat mean_md_node = [ nodes[idx] for idx, s in enumerate(node_names) if "mean_md" in s ][0] mean_md = mean_md_node.result.outputs.out_stat mean_tdi_node = [ nodes[idx] for idx, s in enumerate(node_names) if "mean_tdi" in s ][0] mean_tdi = mean_tdi_node.result.outputs.out_stat track_volume_node = [ nodes[idx] for idx, s in enumerate(node_names) if "track_volume" in s ][0] track_volume = track_volume_node.result.outputs.out_stat[ 1] # First value is in voxels, 2nd is in volume if track_volume == 0: os.remove(fa_masked) os.remove(md_masked) os.remove(tdi) else: out_files.append(md_masked) out_files.append(fa_masked) out_files.append(tracks) out_files.append(tdi) if op.exists(trk_file): out_files.append(trk_file) track_files.append(trk_file) assert (0 <= mean_fa < 1) fa_matrix_thr[idx_i, idx_j] = mean_fa md_matrix_thr[idx_i, idx_j] = mean_md tdi_matrix[idx_i, idx_j] = mean_tdi track_volume_matrix[idx_i, idx_j] = track_volume fa_matrix = np.loadtxt(fa_out_matrix) md_matrix = np.loadtxt(md_out_matrix) fa_matrix = fa_matrix + fa_matrix.T md_matrix = md_matrix + md_matrix.T fa_matrix_thr = fa_matrix_thr + fa_matrix_thr.T md_matrix_thr = md_matrix_thr + md_matrix_thr.T tdi_matrix = tdi_matrix + tdi_matrix.T invLen_invVol_matrix = np.loadtxt(invLen_invVol_out_matrix) invLen_invVol_matrix = invLen_invVol_matrix + invLen_invVol_matrix.T track_volume_matrix = track_volume_matrix + track_volume_matrix.T if prefix is not None: npz_data = op.abspath("%s_connectivity.npz" % prefix) else: _, prefix, _ = split_filename(track_file) npz_data = op.abspath("%s_connectivity.npz" % prefix) np.savez(npz_data, fa=fa_matrix, md=md_matrix, tdi=tdi_matrix, trkvol=track_volume_matrix, fa_thr=fa_matrix_thr, md_thr=md_matrix_thr, invLen_invVol=invLen_invVol_matrix) print("Saving heatmaps...") fa_heatmap = save_heatmap(fa_matrix, roi_names, '%s_fa' % prefix) fa_heatmap_thr = save_heatmap(fa_matrix_thr, roi_names, '%s_fa_thr' % prefix) md_heatmap = save_heatmap(md_matrix, roi_names, '%s_md' % prefix) md_heatmap_thr = save_heatmap(md_matrix_thr, roi_names, '%s_md_thr' % prefix) tdi_heatmap = save_heatmap(tdi_matrix, roi_names, '%s_tdi' % prefix) trk_vol_heatmap = save_heatmap(track_volume_matrix, roi_names, '%s_trk_vol' % prefix) invLen_invVol_heatmap = save_heatmap(invLen_invVol_matrix, roi_names, '%s_invLen_invVol' % prefix) summary_images = [] summary_images.append(fa_heatmap) summary_images.append(fa_heatmap_thr) summary_images.append(md_heatmap) summary_images.append(md_heatmap_thr) summary_images.append(tdi_heatmap) summary_images.append(trk_vol_heatmap) summary_images.append(invLen_invVol_heatmap) out_merged_file = op.abspath('%s_MergedTracks.trk' % prefix) skip = 80. track_merge = pe.Node(interface=dtk.TrackMerge(), name='track_merge') track_merge.inputs.track_files = track_files track_merge.inputs.output_file = out_merged_file track_merge.run() track_names = [] for t in track_files: _, name, _ = split_filename(t) track_names.append(name) out_scene = op.abspath("%s_MergedScene.scene" % prefix) out_scene_file = write_trackvis_scene(out_merged_file, n_clusters=len(track_files), skip=skip, names=track_names, out_file=out_scene) print("Merged track file written to %s" % out_merged_file) print("Scene file written to %s" % out_scene_file) out_files.append(out_merged_file) out_files.append(out_scene_file) return out_files, npz_data, summary_images
def create_connectivity_pipeline(name="connectivity", parcellation_name='scale500'): inputnode_within = pe.Node(util.IdentityInterface(fields=[ "subject_id", "dwi", "bvecs", "bvals", "subjects_dir", "resolution_network_file" ]), name="inputnode_within") FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(), name='fssource') FreeSurferSourceLH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceLH') FreeSurferSourceLH.inputs.hemi = 'lh' FreeSurferSourceRH = pe.Node(interface=nio.FreeSurferSource(), name='fssourceRH') FreeSurferSourceRH.inputs.hemi = 'rh' """ Creating the workflow's nodes ============================= """ """ Conversion nodes ---------------- """ """ A number of conversion operations are required to obtain NIFTI files from the FreesurferSource for each subject. Nodes are used to convert the following: * Original structural image to NIFTI * Pial, white, inflated, and spherical surfaces for both the left and right hemispheres are converted to GIFTI for visualization in ConnectomeViewer * Parcellated annotation files for the left and right hemispheres are also converted to GIFTI """ mri_convert_Brain = pe.Node(interface=fs.MRIConvert(), name='mri_convert_Brain') mri_convert_Brain.inputs.out_type = 'nii' mri_convert_ROI_scale500 = mri_convert_Brain.clone( 'mri_convert_ROI_scale500') mris_convertLH = pe.Node(interface=fs.MRIsConvert(), name='mris_convertLH') mris_convertLH.inputs.out_datatype = 'gii' mris_convertRH = mris_convertLH.clone('mris_convertRH') mris_convertRHwhite = mris_convertLH.clone('mris_convertRHwhite') mris_convertLHwhite = mris_convertLH.clone('mris_convertLHwhite') mris_convertRHinflated = mris_convertLH.clone('mris_convertRHinflated') mris_convertLHinflated = mris_convertLH.clone('mris_convertLHinflated') mris_convertRHsphere = mris_convertLH.clone('mris_convertRHsphere') mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere') mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels') mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels') """ Diffusion processing nodes -------------------------- .. seealso:: dmri_mrtrix_dti.py Tutorial that focuses solely on the MRtrix diffusion processing http://www.brain.org.au/software/mrtrix/index.html MRtrix's online documentation """ """ b-values and b-vectors stored in FSL's format are converted into a single encoding file for MRTrix. """ fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix') """ Distortions induced by eddy currents are corrected prior to fitting the tensors. The first image is used as a reference for which to warp the others. """ eddycorrect = create_eddy_correct_pipeline(name='eddycorrect') eddycorrect.inputs.inputnode.ref_num = 1 """ Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created: * Major eigenvector in each voxel * Apparent diffusion coefficient * Fractional anisotropy """ dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor') tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(), name='tensor2vector') tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(), name='tensor2adc') tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(), name='tensor2fa') MRconvert_fa = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert_fa') MRconvert_fa.inputs.extension = 'nii' """ These nodes are used to create a rough brain mask from the b0 image. The b0 image is extracted from the original diffusion-weighted image, put through a simple thresholding routine, and smoothed using a 3x3 median filter. """ MRconvert = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert') MRconvert.inputs.extract_at_axis = 3 MRconvert.inputs.extract_at_coordinate = [0] threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0') median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3d') """ The brain mask is also used to help identify single-fiber voxels. This is done by passing the brain mask through two erosion steps, multiplying the remaining mask with the fractional anisotropy map, and thresholding the result to obtain some highly anisotropic within-brain voxels. """ erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_firstpass') erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(), name='erode_mask_secondpass') MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply') MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge') threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA') threshold_FA.inputs.absolute_threshold_value = 0.7 """ For whole-brain tracking we also require a broad white-matter seed mask. This is created by generating a white matter mask, given a brainmask, and thresholding it at a reasonably high level. """ bet = pe.Node(interface=fsl.BET(mask=True), name='bet_b0') gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(), name='gen_WM_mask') threshold_wmmask = pe.Node(interface=mrtrix.Threshold(), name='threshold_wmmask') threshold_wmmask.inputs.absolute_threshold_value = 0.4 """ The spherical deconvolution step depends on the estimate of the response function in the highly anisotropic voxels we obtained above. .. warning:: For damaged or pathological brains one should take care to lower the maximum harmonic order of these steps. """ estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(), name='estimateresponse') estimateresponse.inputs.maximum_harmonic_order = 6 csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(), name='csdeconv') csdeconv.inputs.maximum_harmonic_order = 6 """ Finally, we track probabilistically using the orientation distribution functions obtained earlier. The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format. """ probCSDstreamtrack = pe.Node( interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='probCSDstreamtrack') probCSDstreamtrack.inputs.inputmodel = 'SD_PROB' probCSDstreamtrack.inputs.desired_number_of_tracks = 150000 tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob') tracks2prob.inputs.colour = True MRconvert_tracks2prob = MRconvert_fa.clone(name='MRconvert_tracks2prob') tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk') """ Structural segmentation nodes ----------------------------- """ """ The following node identifies the transformation between the diffusion-weighted image and the structural image. This transformation is then applied to the tracts so that they are in the same space as the regions of interest. """ coregister = pe.Node(interface=fsl.FLIRT(dof=6), name='coregister') coregister.inputs.cost = ('normmi') """ Parcellation is performed given the aparc+aseg image from Freesurfer. The CMTK Parcellation step subdivides these regions to return a higher-resolution parcellation scheme. The parcellation used here is entitled "scale500" and returns 1015 regions. """ parcellate = pe.Node(interface=cmtk.Parcellate(), name="Parcellate") parcellate.inputs.parcellation_name = parcellation_name """ The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts and outputs a number of different files. The most important of which is the connectivity network itself, which is stored as a 'gpickle' and can be loaded using Python's NetworkX package (see CreateMatrix docstring). Also outputted are various NumPy arrays containing detailed tract information, such as the start and endpoint regions, and statistics on the mean and standard deviation for the fiber length of each connection. These matrices can be used in the ConnectomeViewer to plot the specific tracts that connect between user-selected regions. Here we choose the Lausanne2008 parcellation scheme, since we are incorporating the CMTK parcellation step. """ creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix") creatematrix.inputs.count_region_intersections = True """ Next we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file. The inspect.getfile command is used to package this script into the resulting CFF file, so that it is easy to look back at the processing parameters that were used. """ CFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="CFFConverter") CFFConverter.inputs.script_files = op.abspath( inspect.getfile(inspect.currentframe())) giftiSurfaces = pe.Node(interface=util.Merge(8), name="GiftiSurfaces") giftiLabels = pe.Node(interface=util.Merge(2), name="GiftiLabels") niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes") fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays") """ We also create a node to calculate several network metrics on our resulting file, and another CFF converter which will be used to package these networks into a single file. """ networkx = create_networkx_pipeline(name='networkx') cmats_to_csv = create_cmats_to_csv_pipeline(name='cmats_to_csv') nfibs_to_csv = pe.Node(interface=misc.Matlab2CSV(), name='nfibs_to_csv') merge_nfib_csvs = pe.Node(interface=misc.MergeCSVFiles(), name='merge_nfib_csvs') merge_nfib_csvs.inputs.extra_column_heading = 'Subject' merge_nfib_csvs.inputs.out_file = 'fibers.csv' NxStatsCFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="NxStatsCFFConverter") NxStatsCFFConverter.inputs.script_files = op.abspath( inspect.getfile(inspect.currentframe())) """ Connecting the workflow ======================= Here we connect our processing pipeline. """ """ Connecting the inputs, FreeSurfer nodes, and conversions -------------------------------------------------------- """ mapping = pe.Workflow(name='mapping') """ First, we connect the input node to the FreeSurfer input nodes. """ mapping.connect([(inputnode_within, FreeSurferSource, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSource, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceLH, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, FreeSurferSourceRH, [("subject_id", "subject_id")])]) mapping.connect([(inputnode_within, parcellate, [("subjects_dir", "subjects_dir")])]) mapping.connect([(inputnode_within, parcellate, [("subject_id", "subject_id")])]) mapping.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file', 'in_file')])]) """ Nifti conversion for subject's stripped brain image from Freesurfer: """ mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])]) """ Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres) """ mapping.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file') ])]) mapping.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file') ])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated, [('inflated', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated, [('inflated', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere, [('sphere', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere, [('sphere', 'in_file')])]) """ The annotation files are converted using the pial surface as a map via the MRIsConvert interface. One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files specifically (rather than e.g. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource. """ mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [('pial', 'in_file')])]) mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels, [(('annot', select_aparc_annot), 'annot_file')])]) """ Diffusion Processing -------------------- Now we connect the tensor computations: """ mapping.connect([(inputnode_within, fsl2mrtrix, [("bvecs", "bvec_file"), ("bvals", "bval_file")])]) mapping.connect([(inputnode_within, eddycorrect, [("dwi", "inputnode.in_file")])]) mapping.connect([(eddycorrect, dwi2tensor, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file", "encoding_file")])]) mapping.connect([ (dwi2tensor, tensor2vector, [['tensor', 'in_file']]), (dwi2tensor, tensor2adc, [['tensor', 'in_file']]), (dwi2tensor, tensor2fa, [['tensor', 'in_file']]), ]) mapping.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])]) mapping.connect([(tensor2fa, MRconvert_fa, [("FA", "in_file")])]) """ This block creates the rough brain mask to be multiplied, mulitplies it with the fractional anisotropy image, and thresholds it to get the single-fiber voxels. """ mapping.connect([(eddycorrect, MRconvert, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(MRconvert, threshold_b0, [("converted", "in_file")])]) mapping.connect([(threshold_b0, median3d, [("out_file", "in_file")])]) mapping.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file") ])]) mapping.connect([(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])]) mapping.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2") ])]) mapping.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])]) mapping.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])]) """ Here the thresholded white matter mask is created for seeding the tractography. """ mapping.connect([(eddycorrect, bet, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(eddycorrect, gen_WM_mask, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])]) mapping.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file", "encoding_file")])]) mapping.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap", "in_file")])]) """ Next we estimate the fiber response distribution. """ mapping.connect([(eddycorrect, estimateresponse, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])]) mapping.connect([(threshold_FA, estimateresponse, [("out_file", "mask_image")])]) """ Run constrained spherical deconvolution. """ mapping.connect([(eddycorrect, csdeconv, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap", "mask_image")])]) mapping.connect([(estimateresponse, csdeconv, [("response", "response_file")])]) mapping.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file") ])]) """ Connect the tractography and compute the tract density image. """ mapping.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file", "seed_file")])]) mapping.connect([(csdeconv, probCSDstreamtrack, [("spherical_harmonics_image", "in_file")])]) mapping.connect([(probCSDstreamtrack, tracks2prob, [("tracked", "in_file") ])]) mapping.connect([(eddycorrect, tracks2prob, [("outputnode.eddy_corrected", "template_file")])]) mapping.connect([(tracks2prob, MRconvert_tracks2prob, [("tract_image", "in_file")])]) """ Structural Processing --------------------- First, we coregister the diffusion image to the structural image """ mapping.connect([(eddycorrect, coregister, [("outputnode.eddy_corrected", "in_file")])]) mapping.connect([(mri_convert_Brain, coregister, [('out_file', 'reference') ])]) """ The MRtrix-tracked fibers are converted to TrackVis format (with voxel and data dimensions grabbed from the DWI). The connectivity matrix is created with the transformed .trk fibers and the parcellation file. """ mapping.connect([(eddycorrect, tck2trk, [("outputnode.eddy_corrected", "image_file")])]) mapping.connect([(mri_convert_Brain, tck2trk, [("out_file", "registration_image_file")])]) mapping.connect([(coregister, tck2trk, [("out_matrix_file", "matrix_file") ])]) mapping.connect([(probCSDstreamtrack, tck2trk, [("tracked", "in_file")])]) mapping.connect([(tck2trk, creatematrix, [("out_file", "tract_file")])]) mapping.connect(inputnode_within, 'resolution_network_file', creatematrix, 'resolution_network_file') mapping.connect([(inputnode_within, creatematrix, [("subject_id", "out_matrix_file")])]) mapping.connect([(inputnode_within, creatematrix, [("subject_id", "out_matrix_mat_file")])]) mapping.connect([(parcellate, creatematrix, [("roi_file", "roi_file")])]) """ The merge nodes defined earlier are used here to create lists of the files which are destined for the CFFConverter. """ mapping.connect([(mris_convertLH, giftiSurfaces, [("converted", "in1")])]) mapping.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])]) mapping.connect([(mris_convertLHwhite, giftiSurfaces, [("converted", "in3") ])]) mapping.connect([(mris_convertRHwhite, giftiSurfaces, [("converted", "in4") ])]) mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted", "in5")])]) mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted", "in6")])]) mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted", "in7")])]) mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted", "in8")])]) mapping.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1") ])]) mapping.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2") ])]) mapping.connect([(parcellate, niftiVolumes, [("roi_file", "in1")])]) mapping.connect([(eddycorrect, niftiVolumes, [("outputnode.eddy_corrected", "in2")])]) mapping.connect([(mri_convert_Brain, niftiVolumes, [("out_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1") ])]) mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm", "in2")])]) mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file", "in3")])]) mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file", "in4")])]) """ This block actually connects the merged lists to the CFF converter. We pass the surfaces and volumes that are to be included, as well as the tracts and the network itself. The currently running pipeline (dmri_connectivity_advanced.py) is also scraped and included in the CFF file. This makes it easy for the user to examine the entire processing pathway used to generate the end product. """ mapping.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")]) ]) mapping.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])]) mapping.connect([(creatematrix, CFFConverter, [("matrix_files", "gpickled_networks")])]) mapping.connect([(niftiVolumes, CFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])]) mapping.connect([(creatematrix, CFFConverter, [("filtered_tractography", "tract_files")])]) mapping.connect([(inputnode_within, CFFConverter, [("subject_id", "title") ])]) """ The graph theoretical metrics which have been generated are placed into another CFF file. """ mapping.connect([(inputnode_within, networkx, [("subject_id", "inputnode.extra_field")])]) mapping.connect([(creatematrix, networkx, [("intersection_matrix_file", "inputnode.network_file")])]) mapping.connect([(networkx, NxStatsCFFConverter, [("outputnode.network_files", "gpickled_networks")])]) mapping.connect([(giftiSurfaces, NxStatsCFFConverter, [("out", "gifti_surfaces")])]) mapping.connect([(giftiLabels, NxStatsCFFConverter, [("out", "gifti_labels")])]) mapping.connect([(niftiVolumes, NxStatsCFFConverter, [("out", "nifti_volumes")])]) mapping.connect([(fiberDataArrays, NxStatsCFFConverter, [("out", "data_files")])]) mapping.connect([(inputnode_within, NxStatsCFFConverter, [("subject_id", "title")])]) mapping.connect([(inputnode_within, cmats_to_csv, [("subject_id", "inputnode.extra_field")])]) mapping.connect([(creatematrix, cmats_to_csv, [ ("matlab_matrix_files", "inputnode.matlab_matrix_files") ])]) mapping.connect([(creatematrix, nfibs_to_csv, [("stats_file", "in_file")]) ]) mapping.connect([(nfibs_to_csv, merge_nfib_csvs, [("csv_files", "in_files") ])]) mapping.connect([(inputnode_within, merge_nfib_csvs, [("subject_id", "extra_field")])]) """ Create a higher-level workflow -------------------------------------- Finally, we create another higher-level workflow to connect our mapping workflow with the info and datagrabbing nodes declared at the beginning. Our tutorial can is now extensible to any arbitrary number of subjects by simply adding their names to the subject list and their data to the proper folders. """ inputnode = pe.Node(interface=util.IdentityInterface( fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir"]), name="inputnode") outputnode = pe.Node(interface=util.IdentityInterface(fields=[ "fa", "struct", "tracts", "tracks2prob", "connectome", "nxstatscff", "nxmatlab", "nxcsv", "fiber_csv", "cmatrices_csv", "nxmergedcsv", "cmatrix", "networks", "filtered_tracts", "rois", "odfs", "tdi", "mean_fiber_length", "median_fiber_length", "fiber_length_std" ]), name="outputnode") connectivity = pe.Workflow(name="connectivity") connectivity.base_output_dir = name connectivity.base_dir = name connectivity.connect([(inputnode, mapping, [ ("dwi", "inputnode_within.dwi"), ("bvals", "inputnode_within.bvals"), ("bvecs", "inputnode_within.bvecs"), ("subject_id", "inputnode_within.subject_id"), ("subjects_dir", "inputnode_within.subjects_dir") ])]) connectivity.connect([(mapping, outputnode, [ ("tck2trk.out_file", "tracts"), ("CFFConverter.connectome_file", "connectome"), ("NxStatsCFFConverter.connectome_file", "nxstatscff"), ("CreateMatrix.matrix_mat_file", "cmatrix"), ("CreateMatrix.mean_fiber_length_matrix_mat_file", "mean_fiber_length"), ("CreateMatrix.median_fiber_length_matrix_mat_file", "median_fiber_length"), ("CreateMatrix.fiber_length_std_matrix_mat_file", "fiber_length_std"), ("CreateMatrix.matrix_files", "networks"), ("CreateMatrix.filtered_tractographies", "filtered_tracts"), ("merge_nfib_csvs.csv_file", "fiber_csv"), ("mri_convert_ROI_scale500.out_file", "rois"), ("csdeconv.spherical_harmonics_image", "odfs"), ("mri_convert_Brain.out_file", "struct"), ("MRconvert_fa.converted", "fa"), ("MRconvert_tracks2prob.converted", "tracks2prob") ])]) connectivity.connect([(cmats_to_csv, outputnode, [("outputnode.csv_file", "cmatrices_csv")])]) connectivity.connect([(networkx, outputnode, [("outputnode.csv_files", "nxcsv")])]) return connectivity
# Extract the tracks from the single Voxel (informed) case tracksFilter = mrt.FilterTracks() tracksFilter.inputs.in_file = multiVoxelTracks tracksFilter.inputs.no_mask_interpolation = True tracksFilter.inputs.include_file = tmpMaskFileName tracksFilter.inputs.invert = False tracksFilter.inputs.out_file = singleVoxelTracks tracksFilter.run() # #tracksFilter.inputs.in_file = multiVoxelTracksRandom #tracksFilter.inputs.out_file = singleVoxelTracksRandom #tracksFilter.run() # ## Generate maps of the connection probability print "Probability Map...." tdi = mrt.Tracks2Prob() tdi.inputs.fraction = False tdi.inputs.template_file = seedmask tdi.inputs.in_file = singleVoxelTracks tdi.inputs.out_filename = singleVoxelTDI tdi.run() tdi.inputs.in_file = singleVoxelTracksRandom tdi.inputs.out_filename = singleVoxelRandomTDI tdi.run() # ## Now calculate the Z-Map tdi_informed = nib.load(singleVoxelTDI) tdi_informed_data = tdi_informed.get_data()