示例#1
0
def test_track_ensemble(directget, target_samples):
    """
    Test for ensemble tractography functionality
    """
    import tempfile
    from pynets.dmri import track
    from dipy.core.gradients import gradient_table
    from dipy.data import get_sphere
    from nibabel.streamlines.array_sequence import ArraySequence

    base_dir = str(Path(__file__).parent/"examples")
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    gm_in_dwi = f"{base_dir}/003/anat/t1w_gm_in_dwi.nii.gz"
    vent_csf_in_dwi = f"{base_dir}/003/anat/t1w_vent_csf_in_dwi.nii.gz"
    wm_in_dwi = f"{base_dir}/003/anat/t1w_wm_in_dwi.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab = gradient_table(bvals, bvecs)
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-" \
               f"2mm.nii.gz"
    atlas_data_wm_gm_int = f"{dir_path}/whole_brain_cluster_labels_PCA200_" \
                           f"dwi_track_wmgm_int.nii.gz"
    labels_im_file = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_" \
                     f"track.nii.gz"
    conn_model = 'csa'
    tiss_class = 'wm'
    min_length = 10
    maxcrossing = 2
    roi_neighborhood_tol = 6
    waymask = None
    curv_thr_list = [40, 30]
    step_list = [0.1, 0.2, 0.3, 0.4, 0.5]
    sphere = get_sphere('repulsion724')
    track_type = 'local'

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    temp_dir = tempfile.TemporaryDirectory()
    recon_path = temp_dir.name + '/model_file.hdf5'
    model, _ = track.reconstruction(conn_model, gtab, dwi_data, wm_in_dwi)

    with h5py.File(recon_path, 'w') as hf:
        hf.create_dataset("reconstruction",
                          data=model.astype('float32'))
    hf.close()

    streamlines = track.track_ensemble(target_samples, atlas_data_wm_gm_int,
                                       labels_im_file,
                   recon_path, sphere, directget, curv_thr_list, step_list,
                   track_type, maxcrossing, roi_neighborhood_tol, min_length,
                   waymask, B0_mask, gm_in_dwi, gm_in_dwi, vent_csf_in_dwi,
                   wm_in_dwi, tiss_class, temp_dir.name)

    assert isinstance(streamlines, ArraySequence)
示例#2
0
def test_track_ensemble(directget, target_samples):
    """
    Test for ensemble tractography functionality
    """
    from pynets.dmri import track
    from dipy.core.gradients import gradient_table
    from dipy.data import get_sphere

    base_dir = str(Path(__file__).parent/"examples")
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    gm_in_dwi = f"{base_dir}/003/anat/t1w_gm_in_dwi.nii.gz"
    vent_csf_in_dwi = f"{base_dir}/003/anat/t1w_vent_csf_in_dwi.nii.gz"
    wm_in_dwi = f"{base_dir}/003/anat/t1w_wm_in_dwi.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab = gradient_table(bvals, bvecs)
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-2mm.nii.gz"
    atlas_data_wm_gm_int = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track_wmgm_int.nii.gz"
    labels_im_file = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track.nii.gz"
    conn_model = 'csa'
    tiss_class = 'bin'
    min_length = 10
    maxcrossing = 2
    roi_neighborhood_tol = 6
    waymask = None
    curv_thr_list = [40, 30]
    step_list = [0.1, 0.2, 0.3, 0.4, 0.5]
    sphere = get_sphere('repulsion724')
    track_type = 'local'

    # Load atlas parcellation (and its wm-gm interface reduced version for seeding)
    atlas_data = np.array(nib.load(labels_im_file).dataobj).astype('uint16')
    atlas_data_wm_gm_int = np.asarray(nib.load(atlas_data_wm_gm_int).dataobj).astype('uint16')

    # Build mask vector from atlas for later roi filtering
    parcels = []
    i = 0
    for roi_val in np.unique(atlas_data)[1:]:
        parcels.append(atlas_data == roi_val)
        i = i + 1

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    model, _ = track.reconstruction(conn_model, gtab, dwi_data, wm_in_dwi)

    tiss_classifier = track.prep_tissues(B0_mask, gm_in_dwi, vent_csf_in_dwi, wm_in_dwi, tiss_class,
                                         cmc_step_size=0.2)

    track.track_ensemble(target_samples, atlas_data_wm_gm_int, parcels, model, tiss_classifier, sphere, directget,
                         curv_thr_list, step_list, track_type, maxcrossing, roi_neighborhood_tol, min_length, waymask,
                         B0_mask, max_length=1000, n_seeds_per_iter=500, pft_back_tracking_dist=2,
                         pft_front_tracking_dist=1, particle_count=15, min_separation_angle=20)
示例#3
0
def test_reconstruction(conn_model):
    """
    Test for reconstruction functionality
    """
    from pynets.dmri import track
    from dipy.core.gradients import gradient_table
    base_dir = str(Path(__file__).parent / "examples")

    dir_path = base_dir + '/003/dmri'
    bvals = dir_path + '/sub-003_dwi.bval'
    bvecs = dir_path + '/sub-003_dwi.bvec'
    gtab = gradient_table(bvals, bvecs)
    dwi_file = dir_path + '/sub-003_dwi.nii.gz'
    wm_in_dwi = dir_path + '/wm_mask_dmri.nii.gz'

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    mod = track.reconstruction(conn_model, gtab, dwi_data, wm_in_dwi)
    assert mod is not None
示例#4
0
def test_track_ensemble_particle():
    """
    Test for ensemble tractography functionality
    """
    import tempfile
    from pynets.dmri import track
    from dipy.core.gradients import gradient_table
    from dipy.data import get_sphere
    from dipy.io.stateful_tractogram import Space, StatefulTractogram, Origin
    from dipy.io.streamline import save_tractogram
    from nibabel.streamlines.array_sequence import ArraySequence

    base_dir = str(Path(__file__).parent/"examples")
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    gm_in_dwi = f"{base_dir}/003/anat/t1w_gm_in_dwi.nii.gz"
    vent_csf_in_dwi = f"{base_dir}/003/anat/t1w_vent_csf_in_dwi.nii.gz"
    wm_in_dwi = f"{base_dir}/003/anat/t1w_wm_in_dwi.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab = gradient_table(bvals, bvecs)
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-2mm.nii.gz"
    atlas_data_wm_gm_int = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track_wmgm_int.nii.gz"
    labels_im_file = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track.nii.gz"
    conn_model = 'csd'
    tiss_class = 'cmc'
    min_length = 10
    maxcrossing = 2
    roi_neighborhood_tol = 6
    waymask = None
    curv_thr_list = [40, 30]
    step_list = [0.1, 0.2, 0.3, 0.4, 0.5]
    sphere = get_sphere('repulsion724')
    directget = 'prob'
    track_type = 'particle'
    target_samples = 1000

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    model, _ = track.reconstruction(conn_model, gtab, dwi_data, wm_in_dwi)
    temp_dir = tempfile.TemporaryDirectory()
    recon_path = temp_dir.name + '/model_file.hdf5'

    with h5py.File(recon_path, 'w') as hf:
        hf.create_dataset("reconstruction",
                          data=model.astype('float32'))
    hf.close()

    streamlines = track.track_ensemble(target_samples, atlas_data_wm_gm_int,
                                       labels_im_file, recon_path, sphere,
                                       directget, curv_thr_list, step_list,
                   track_type, maxcrossing, roi_neighborhood_tol, min_length,
                   waymask, B0_mask, gm_in_dwi, gm_in_dwi, vent_csf_in_dwi,
                   wm_in_dwi, tiss_class, temp_dir.name)

    streams = f"{base_dir}/miscellaneous/streamlines_model-csd_nodetype-parc_samples-1000streams_tracktype-particle_directget-prob_minlength-10.trk"
    save_tractogram(StatefulTractogram(streamlines, reference=dwi_img,
                                       space=Space.VOXMM, origin=Origin.NIFTI),
                    streams, bbox_valid_check=False)
    assert isinstance(streamlines, ArraySequence)
示例#5
0
文件: track.py 项目: devhliu/PyNets
def run_track(B0_mask,
              gm_in_dwi,
              vent_csf_in_dwi,
              wm_in_dwi,
              tiss_class,
              labels_im_file_wm_gm_int,
              labels_im_file,
              target_samples,
              curv_thr_list,
              step_list,
              track_type,
              max_length,
              maxcrossing,
              directget,
              conn_model,
              gtab_file,
              dwi_file,
              network,
              node_size,
              dens_thresh,
              ID,
              roi,
              min_span_tree,
              disp_filt,
              parc,
              prune,
              atlas,
              uatlas,
              labels,
              coords,
              norm,
              binary,
              atlas_mni,
              min_length,
              fa_path,
              waymask,
              roi_neighborhood_tol=8,
              sphere='repulsion724'):
    """
    Run all ensemble tractography and filtering routines.

    Parameters
    ----------
    B0_mask : str
        File path to B0 brain mask.
    gm_in_dwi : str
        File path to grey-matter tissue segmentation Nifti1Image.
    vent_csf_in_dwi : str
        File path to ventricular CSF tissue segmentation Nifti1Image.
    wm_in_dwi : str
        File path to white-matter tissue segmentation Nifti1Image.
    tiss_class : str
        Tissue classification method.
    labels_im_file_wm_gm_int : str
        File path to atlas parcellation Nifti1Image in T1w-warped native diffusion space, restricted to wm-gm interface.
    labels_im_file : str
        File path to atlas parcellation Nifti1Image in T1w-warped native diffusion space.
    target_samples : int
        Total number of streamline samples specified to generate streams.
    curv_thr_list : list
        List of integer curvature thresholds used to perform ensemble tracking.
    step_list : list
        List of float step-sizes used to perform ensemble tracking.
    track_type : str
        Tracking algorithm used (e.g. 'local' or 'particle').
    max_length : int
        Maximum fiber length threshold in mm to restrict tracking.
    maxcrossing : int
        Maximum number if diffusion directions that can be assumed per voxel while tracking.
    directget : str
        The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped),
        and prob (probabilistic).
    conn_model : str
        Connectivity reconstruction method (e.g. 'csa', 'tensor', 'csd').
    gtab_file : str
        File path to pickled DiPy gradient table object.
    dwi_file : str
        File path to diffusion weighted image.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default')
        used to filter nodes in the study of brain subgraphs.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's for tracking.
    dens_thresh : bool
        Indicates whether a target graph density is to be used as the basis for
        thresholding.
    ID : str
        A subject id or other unique identifier.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    min_span_tree : bool
        Indicates whether local thresholding from the Minimum Spanning Tree
        should be used.
    disp_filt : bool
        Indicates whether local thresholding using a disparity filter and
        'backbone network' should be used.
    parc : bool
        Indicates whether to use parcels instead of coordinates as ROI nodes.
    prune : bool
        Indicates whether to prune final graph of disconnected nodes/isolates.
    atlas : str
        Name of atlas parcellation used.
    uatlas : str
        File path to atlas parcellation Nifti1Image in MNI template space.
    labels : list
        List of string labels corresponding to graph nodes.
    coords : list
        List of (x, y, z) tuples corresponding to a coordinate atlas used or
        which represent the center-of-mass of each parcellation node.
    norm : int
        Indicates method of normalizing resulting graph.
    binary : bool
        Indicates whether to binarize resulting graph edges to form an
        unweighted graph.
    atlas_mni : str
        File path to atlas parcellation Nifti1Image in T1w-warped MNI space.
    min_length : int
        Minimum fiber length threshold in mm.
    fa_path : str
        File path to FA Nifti1Image.
    waymask : str
        Path to a Nifti1Image in native diffusion space to constrain tractography.
    roi_neighborhood_tol : float
        Distance (in the units of the streamlines, usually mm). If any
        coordinate in the streamline is within this distance from the center
        of any voxel in the ROI, the filtering criterion is set to True for
        this streamline, otherwise False. Defaults to the distance between
        the center of each voxel and the corner of the voxel. Default is 10 mm.
    sphere : str
        Provide triangulated spheres. Default is repulsion724. Options are:
        `symmetric362`, `symmetric642`, `symmetric724`, `repulsion724`, `repulsion100`, or `repulsion200`

    Returns
    -------
    streams : str
        File path to save streamline array sequence in .trk format.
    track_type : str
        Tracking algorithm used (e.g. 'local' or 'particle').
    target_samples : int
        Total number of streamline samples specified to generate streams.
    conn_model : str
        Connectivity reconstruction method (e.g. 'csa', 'tensor', 'csd').
    dir_path : str
        Path to directory containing subject derivative data for a given pynets run.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default')
        used to filter nodes in the study of brain subgraphs.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's for tracking.
    dens_thresh : bool
        Indicates whether a target graph density is to be used as the basis for
        thresholding.
    ID : str
        A subject id or other unique identifier.
    roi : str
        File path to binarized/boolean region-of-interest Nifti1Image file.
    min_span_tree : bool
        Indicates whether local thresholding from the Minimum Spanning Tree
        should be used.
    disp_filt : bool
        Indicates whether local thresholding using a disparity filter and
        'backbone network' should be used.
    parc : bool
        Indicates whether to use parcels instead of coordinates as ROI nodes.
    prune : bool
        Indicates whether to prune final graph of disconnected nodes/isolates.
    atlas : str
        Name of atlas parcellation used.
    uatlas : str
        File path to atlas parcellation Nifti1Image in MNI template space.
    labels : list
        List of string labels corresponding to graph nodes.
    coords : list
        List of (x, y, z) tuples corresponding to a coordinate atlas used or
        which represent the center-of-mass of each parcellation node.
    norm : int
        Indicates method of normalizing resulting graph.
    binary : bool
        Indicates whether to binarize resulting graph edges to form an
        unweighted graph.
    atlas_mni : str
        File path to atlas parcellation Nifti1Image in T1w-warped MNI space.
    curv_thr_list : list
        List of integer curvature thresholds used to perform ensemble tracking.
    step_list : list
        List of float step-sizes used to perform ensemble tracking.
    fa_path : str
        File path to FA Nifti1Image.
    dm_path : str
        File path to fiber density map Nifti1Image.
    directget : str
        The statistical approach to tracking. Options are: det (deterministic), closest (clos), boot (bootstrapped),
        and prob (probabilistic).
    max_length : int
        Maximum fiber length threshold in mm to restrict tracking.
    """
    import gc
    try:
        import cPickle as pickle
    except ImportError:
        import _pickle as pickle
    from dipy.io import load_pickle
    from colorama import Fore, Style
    from dipy.data import get_sphere
    from pynets.core import utils
    from pynets.dmri.track import prep_tissues, reconstruction, create_density_map, track_ensemble

    # Load diffusion data
    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    # Fit diffusion model
    mod_fit = reconstruction(conn_model, load_pickle(gtab_file), dwi_data,
                             B0_mask)

    # Load atlas parcellation (and its wm-gm interface reduced version for seeding)
    atlas_data = nib.load(labels_im_file).get_fdata().astype('uint16')
    atlas_data_wm_gm_int = nib.load(
        labels_im_file_wm_gm_int).get_fdata().astype('uint16')

    # Build mask vector from atlas for later roi filtering
    parcels = []
    i = 0
    for roi_val in np.unique(atlas_data)[1:]:
        parcels.append(atlas_data == roi_val)
        i = i + 1

    if np.sum(atlas_data) == 0:
        raise ValueError(
            'ERROR: No non-zero voxels found in atlas. Check any roi masks and/or wm-gm interface images '
            'to verify overlap with dwi-registered atlas.')

    # Iteratively build a list of streamlines for each ROI while tracking
    print(
        "%s%s%s%s" %
        (Fore.GREEN, 'Target number of samples: ', Fore.BLUE, target_samples))
    print(Style.RESET_ALL)
    print("%s%s%s%s" % (Fore.GREEN, 'Using curvature threshold(s): ',
                        Fore.BLUE, curv_thr_list))
    print(Style.RESET_ALL)
    print("%s%s%s%s" %
          (Fore.GREEN, 'Using step size(s): ', Fore.BLUE, step_list))
    print(Style.RESET_ALL)
    print("%s%s%s%s" % (Fore.GREEN, 'Tracking type: ', Fore.BLUE, track_type))
    print(Style.RESET_ALL)
    if directget == 'prob':
        print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE,
                            'Probabilistic'))
    elif directget == 'boot':
        print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE,
                            'Bootstrapped'))
    elif directget == 'closest':
        print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE,
                            'Closest Peak'))
    elif directget == 'det':
        print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE,
                            'Deterministic Maximum'))
    print(Style.RESET_ALL)

    # Commence Ensemble Tractography
    streamlines = track_ensemble(
        dwi_data, target_samples, atlas_data_wm_gm_int, parcels, mod_fit,
        prep_tissues(B0_mask,
                     gm_in_dwi, vent_csf_in_dwi, wm_in_dwi, tiss_class),
        get_sphere(sphere), directget, curv_thr_list, step_list, track_type,
        maxcrossing, max_length, roi_neighborhood_tol, min_length, waymask)
    print('Tracking Complete')

    # Create streamline density map
    [streams, dir_path,
     dm_path] = create_density_map(dwi_img, utils.do_dir_path(atlas, dwi_file),
                                   streamlines, conn_model, target_samples,
                                   node_size, curv_thr_list, step_list,
                                   network, roi, directget, max_length)

    del streamlines, dwi_data, atlas_data_wm_gm_int, atlas_data, mod_fit, parcels
    dwi_img.uncache()

    gc.collect()

    return streams, track_type, target_samples, conn_model, dir_path, network, node_size, dens_thresh, ID, roi, min_span_tree, disp_filt, parc, prune, atlas, uatlas, labels, coords, norm, binary, atlas_mni, curv_thr_list, step_list, fa_path, dm_path, directget, labels_im_file, roi_neighborhood_tol, max_length
示例#6
0
    def _run_interface(self, runtime):
        import gc
        import numpy as np
        import nibabel as nib
        try:
            import cPickle as pickle
        except ImportError:
            import _pickle as pickle
        from dipy.io import load_pickle
        from colorama import Fore, Style
        from dipy.data import get_sphere
        from pynets.core import utils
        from pynets.dmri.track import prep_tissues, reconstruction, create_density_map, track_ensemble

        # Load diffusion data
        dwi_img = nib.load(self.inputs.dwi_file)

        # Fit diffusion model
        mod_fit = reconstruction(self.inputs.conn_model, load_pickle(self.inputs.gtab_file),
                                 np.asarray(dwi_img.dataobj), self.inputs.B0_mask)

        # Load atlas parcellation (and its wm-gm interface reduced version for seeding)
        atlas_data = np.array(nib.load(self.inputs.labels_im_file).dataobj).astype('uint16')
        atlas_data_wm_gm_int = np.asarray(nib.load(self.inputs.labels_im_file_wm_gm_int).dataobj).astype('uint16')

        # Build mask vector from atlas for later roi filtering
        parcels = []
        i = 0
        for roi_val in np.unique(atlas_data)[1:]:
            parcels.append(atlas_data == roi_val)
            i = i + 1

        if np.sum(atlas_data) == 0:
            raise ValueError(
                'ERROR: No non-zero voxels found in atlas. Check any roi masks and/or wm-gm interface images '
                'to verify overlap with dwi-registered atlas.')

        # Iteratively build a list of streamlines for each ROI while tracking
        print("%s%s%s%s" % (Fore.GREEN, 'Target number of samples: ', Fore.BLUE, self.inputs.target_samples))
        print(Style.RESET_ALL)
        print("%s%s%s%s" % (Fore.GREEN, 'Using curvature threshold(s): ', Fore.BLUE, self.inputs.curv_thr_list))
        print(Style.RESET_ALL)
        print("%s%s%s%s" % (Fore.GREEN, 'Using step size(s): ', Fore.BLUE, self.inputs.step_list))
        print(Style.RESET_ALL)
        print("%s%s%s%s" % (Fore.GREEN, 'Tracking type: ', Fore.BLUE, self.inputs.track_type))
        print(Style.RESET_ALL)
        if self.inputs.directget == 'prob':
            print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE, 'Probabilistic'))
        elif self.inputs.directget == 'boot':
            print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE, 'Bootstrapped'))
        elif self.inputs.directget == 'closest':
            print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE, 'Closest Peak'))
        elif self.inputs.directget == 'det':
            print("%s%s%s%s" % (Fore.GREEN, 'Direction-getting type: ', Fore.BLUE, 'Deterministic Maximum'))
        else:
            raise ValueError('Direction-getting type not recognized!')
        print(Style.RESET_ALL)

        # Commence Ensemble Tractography
        streamlines = track_ensemble(np.asarray(dwi_img.dataobj), self.inputs.target_samples, atlas_data_wm_gm_int,
                                     parcels, mod_fit,
                                     prep_tissues(self.inputs.t1w2dwi, self.inputs.gm_in_dwi,
                                                  self.inputs.vent_csf_in_dwi, self.inputs.wm_in_dwi,
                                                  self.inputs.tiss_class),
                                     get_sphere(self.inputs.sphere), self.inputs.directget, self.inputs.curv_thr_list,
                                     self.inputs.step_list, self.inputs.track_type, self.inputs.maxcrossing,
                                     int(self.inputs.roi_neighborhood_tol), self.inputs.min_length, self.inputs.waymask)

        # Create streamline density map
        [streams, dir_path, dm_path] = create_density_map(dwi_img, utils.do_dir_path(self.inputs.atlas,
                                                                                     self.inputs.dwi_file), streamlines,
                                                          self.inputs.conn_model, self.inputs.target_samples,
                                                          self.inputs.node_size, self.inputs.curv_thr_list,
                                                          self.inputs.step_list, self.inputs.network, self.inputs.roi,
                                                          self.inputs.directget, self.inputs.min_length)

        self._results['streams'] = streams
        self._results['track_type'] = self.inputs.track_type
        self._results['target_samples'] = self.inputs.target_samples
        self._results['conn_model'] = self.inputs.conn_model
        self._results['dir_path'] = dir_path
        self._results['network'] = self.inputs.network
        self._results['node_size'] = self.inputs.node_size
        self._results['dens_thresh'] = self.inputs.dens_thresh
        self._results['ID'] = self.inputs.ID
        self._results['roi'] = self.inputs.roi
        self._results['min_span_tree'] = self.inputs.min_span_tree
        self._results['disp_filt'] = self.inputs.disp_filt
        self._results['parc'] = self.inputs.parc
        self._results['prune'] = self.inputs.prune
        self._results['atlas'] = self.inputs.atlas
        self._results['uatlas'] = self.inputs.uatlas
        self._results['labels'] = self.inputs.labels
        self._results['coords'] = self.inputs.coords
        self._results['norm'] = self.inputs.norm
        self._results['binary'] = self.inputs.binary
        self._results['atlas_mni'] = self.inputs.atlas_mni
        self._results['curv_thr_list'] = self.inputs.curv_thr_list
        self._results['step_list'] = self.inputs.step_list
        self._results['fa_path'] = self.inputs.fa_path
        self._results['dm_path'] = dm_path
        self._results['directget'] = self.inputs.directget
        self._results['labels_im_file'] = self.inputs.labels_im_file
        self._results['roi_neighborhood_tol'] = self.inputs.roi_neighborhood_tol
        self._results['min_length'] = self.inputs.min_length

        del streamlines, atlas_data_wm_gm_int, atlas_data, mod_fit, parcels
        dwi_img.uncache()
        gc.collect()

        return runtime
示例#7
0
def test_track_ensemble_particle():
    """
    Test for ensemble tractography functionality
    """
    from pynets.dmri import track
    from dipy.core.gradients import gradient_table
    from dipy.data import get_sphere
    from dipy.io.stateful_tractogram import Space, StatefulTractogram, Origin
    from dipy.io.streamline import save_tractogram

    base_dir = str(Path(__file__).parent/"examples")
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    gm_in_dwi = f"{base_dir}/003/anat/t1w_gm_in_dwi.nii.gz"
    vent_csf_in_dwi = f"{base_dir}/003/anat/t1w_vent_csf_in_dwi.nii.gz"
    wm_in_dwi = f"{base_dir}/003/anat/t1w_wm_in_dwi.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab = gradient_table(bvals, bvecs)
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-2mm.nii.gz"
    atlas_data_wm_gm_int = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track_wmgm_int.nii.gz"
    labels_im_file = f"{dir_path}/whole_brain_cluster_labels_PCA200_dwi_track.nii.gz"
    conn_model = 'csd'
    tiss_class = 'cmc'
    min_length = 10
    maxcrossing = 2
    roi_neighborhood_tol = 6
    waymask = None
    curv_thr_list = [40, 30]
    step_list = [0.1, 0.2, 0.3, 0.4, 0.5]
    sphere = get_sphere('repulsion724')
    directget = 'prob'
    track_type = 'particle'
    target_samples = 1000

    # Load atlas parcellation (and its wm-gm interface reduced version for seeding)
    atlas_data = np.array(nib.load(labels_im_file).dataobj).astype('uint16')
    atlas_data_wm_gm_int = np.asarray(nib.load(atlas_data_wm_gm_int).dataobj).astype('uint16')

    # Build mask vector from atlas for later roi filtering
    parcels = []
    i = 0
    for roi_val in np.unique(atlas_data)[1:]:
        parcels.append(atlas_data == roi_val)
        i = i + 1

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    model, _ = track.reconstruction(conn_model, gtab, dwi_data, wm_in_dwi)

    tiss_classifier = track.prep_tissues(gm_in_dwi, gm_in_dwi, vent_csf_in_dwi,
                                         wm_in_dwi, tiss_class, B0_mask,
                                         cmc_step_size=0.2)

    streamlines = track.track_ensemble(target_samples, atlas_data_wm_gm_int, parcels, model, tiss_classifier, sphere,
                                       directget, curv_thr_list, step_list, track_type, maxcrossing,
                                       roi_neighborhood_tol, min_length, waymask, B0_mask, max_length=1000,
                                       n_seeds_per_iter=500, pft_back_tracking_dist=2, pft_front_tracking_dist=1,
                                       particle_count=15, min_separation_angle=20)
    streams = f"{base_dir}/miscellaneous/streamlines_model-csd_nodetype-parc_samples-1000streams_tracktype-particle_directget-prob_minlength-10.trk"
    save_tractogram(StatefulTractogram(streamlines, reference=dwi_img,
                                       space=Space.VOXMM, origin=Origin.NIFTI),
                    streams, bbox_valid_check=False)
示例#8
0
def run_track(nodif_B0_mask, gm_in_dwi, vent_csf_in_dwi, wm_in_dwi, tiss_class, labels_im_file_wm_gm_int,
              labels_im_file, target_samples, curv_thr_list, step_list, track_type, max_length, maxcrossing, directget,
              conn_model, gtab_file, dwi_file, network, node_size, dens_thresh, ID, roi, min_span_tree, disp_filt, parc,
              prune, atlas_select, uatlas_select, label_names, coords, norm, binary, atlas_mni, life_run, min_length,
              fa_path):
    try:
        import cPickle as pickle
    except ImportError:
        import _pickle as pickle
    from dipy.io import load_pickle
    from colorama import Fore, Style
    from dipy.data import get_sphere
    from pynets import utils
    from pynets.dmri.track import prep_tissues, reconstruction, filter_streamlines, track_ensemble

    # Load gradient table
    gtab = load_pickle(gtab_file)

    # Fit diffusion model
    mod_fit = reconstruction(conn_model, gtab, dwi_file, wm_in_dwi)

    # Load atlas parcellation (and its wm-gm interface reduced version for seeding)
    atlas_img = nib.load(labels_im_file)
    atlas_data = atlas_img.get_fdata().astype('int')
    atlas_img_wm_gm_int = nib.load(labels_im_file_wm_gm_int)
    atlas_data_wm_gm_int = atlas_img_wm_gm_int.get_fdata().astype('int')

    # Build mask vector from atlas for later roi filtering
    parcels = []
    i = 0
    for roi_val in np.unique(atlas_data)[1:]:
        parcels.append(atlas_data == roi_val)
        i = i + 1
    parcel_vec = np.ones(len(parcels))

    # Get sphere
    sphere = get_sphere('repulsion724')

    # Instantiate tissue classifier
    tiss_classifier = prep_tissues(nodif_B0_mask, gm_in_dwi, vent_csf_in_dwi, wm_in_dwi, tiss_class)

    if np.sum(atlas_data) == 0:
        raise ValueError('ERROR: No non-zero voxels found in atlas. Check any roi masks and/or wm-gm interface images '
                         'to verify overlap with dwi-registered atlas.')

    # Iteratively build a list of streamlines for each ROI while tracking
    print("%s%s%s%s" % (Fore.GREEN, 'Target number of samples: ', Fore.BLUE, target_samples))
    print(Style.RESET_ALL)
    print("%s%s%s%s" % (Fore.GREEN, 'Using curvature threshold(s): ', Fore.BLUE, curv_thr_list))
    print(Style.RESET_ALL)
    print("%s%s%s%s" % (Fore.GREEN, 'Using step size(s): ', Fore.BLUE, step_list))
    print(Style.RESET_ALL)
    print("%s%s%s%s" % (Fore.GREEN, 'Tracking type: ', Fore.BLUE, track_type))
    print(Style.RESET_ALL)
    if directget == 'prob':
        print("%s%s%s" % ('Using ', Fore.MAGENTA, 'Probabilistic Direction...'))
    elif directget == 'boot':
        print("%s%s%s" % ('Using ', Fore.MAGENTA, 'Bootstrapped Direction...'))
    elif directget == 'closest':
        print("%s%s%s" % ('Using ', Fore.MAGENTA, 'Closest Peak Direction...'))
    elif directget == 'det':
        print("%s%s%s" % ('Using ', Fore.MAGENTA, 'Deterministic Maximum Direction...'))
    print(Style.RESET_ALL)

    # Commence Ensemble Tractography
    streamlines = track_ensemble(target_samples, atlas_data_wm_gm_int, parcels, parcel_vec,
                                 mod_fit, tiss_classifier, sphere, directget, curv_thr_list, step_list, track_type,
                                 maxcrossing, max_length)
    print('Tracking Complete')

    # Perform streamline filtering routines
    dir_path = utils.do_dir_path(atlas_select, dwi_file)
    [streams, dir_path] = filter_streamlines(dwi_file, dir_path, gtab, streamlines, life_run, min_length, conn_model,
                                             target_samples, node_size, curv_thr_list, step_list)

    return streams, track_type, target_samples, conn_model, dir_path, network, node_size, dens_thresh, ID, roi, min_span_tree, disp_filt, parc, prune, atlas_select, uatlas_select, label_names, coords, norm, binary, atlas_mni, curv_thr_list, step_list, fa_path